OSDN Git Service

remove Windows, Mac and other proprietary OS files
authorIvailo Monev <xakepa10@laimg.moc>
Sun, 11 Sep 2016 03:34:17 +0000 (03:34 +0000)
committerIvailo Monev <xakepa10@laimg.moc>
Sun, 11 Sep 2016 03:34:17 +0000 (03:34 +0000)
287 files changed:
mkspecs/aix/qplatformdefs.h [deleted file]
mkspecs/blackberry/qmake.conf [deleted file]
mkspecs/blackberry/qplatformdefs.h [deleted file]
mkspecs/darwin/qplatformdefs.h [deleted file]
mkspecs/integrity/qmake.conf [deleted file]
mkspecs/integrity/qplatformdefs.h [deleted file]
mkspecs/ios/GLES/gl.h [deleted file]
mkspecs/ios/GLES2/gl2.h [deleted file]
mkspecs/ios/arch.conf [deleted file]
mkspecs/ios/clang.conf [deleted file]
mkspecs/ios/g++.conf [deleted file]
mkspecs/ios/gcc-base-ios.conf [deleted file]
mkspecs/ios/ios.conf [deleted file]
mkspecs/ios/llvm.conf [deleted file]
mkspecs/ios/qmake.conf [deleted file]
mkspecs/ios/qplatformdefs.h [deleted file]
mkspecs/ios/versions.conf [deleted file]
mkspecs/mac/qplatformdefs.h [deleted file]
mkspecs/maemo/TODO [deleted file]
mkspecs/qbase.pri [deleted file]
mkspecs/qnx/qmake.conf [deleted file]
mkspecs/qnx/qplatformdefs.h [deleted file]
mkspecs/vxworks/TODO [deleted file]
mkspecs/win32/qplatformdefs.h [deleted file]
mkspecs/wince/qmake.conf [deleted file]
mkspecs/wince/qplatformdefs.h [deleted file]
src/3rdparty/ce-compat/ce_time.c [deleted file]
src/3rdparty/ce-compat/ce_time.h [deleted file]
src/3rdparty/javascriptcore/JavaScriptCore/os-win32/stdint.h [deleted file]
src/3rdparty/miniz/NOTE [deleted file]
src/3rdparty/miniz/miniz.c [deleted file]
src/3rdparty/miniz/zlib.h [deleted file]
src/core/arch/qatomic_macosx.h [deleted file]
src/core/global/qglobal.cpp
src/core/io/qfilesystemengine_win.cpp [deleted file]
src/core/io/qfilesystemiterator_win.cpp [deleted file]
src/core/io/qfilesystemwatcher_win.cpp [deleted file]
src/core/io/qfilesystemwatcher_win_p.h [deleted file]
src/core/io/qfsfileengine_win.cpp [deleted file]
src/core/io/qprocess_win.cpp [deleted file]
src/core/io/qsettings_mac.cpp [deleted file]
src/core/io/qsettings_win.cpp [deleted file]
src/core/io/qstandardpaths_mac.cpp [deleted file]
src/core/io/qstandardpaths_win.cpp [deleted file]
src/core/kernel/qcore_mac.cpp [deleted file]
src/core/kernel/qcore_mac_p.h [deleted file]
src/core/kernel/qcoreapplication_mac.cpp [deleted file]
src/core/kernel/qcoreapplication_win.cpp [deleted file]
src/core/kernel/qeventdispatcher_blackberry.cpp [deleted file]
src/core/kernel/qeventdispatcher_blackberry_p.h [deleted file]
src/core/kernel/qeventdispatcher_win.cpp [deleted file]
src/core/kernel/qeventdispatcher_win_p.h [deleted file]
src/core/kernel/qfunctions_wince.cpp [deleted file]
src/core/kernel/qfunctions_wince.h [deleted file]
src/core/kernel/qsharedmemory_win.cpp [deleted file]
src/core/kernel/qsystemsemaphore_win.cpp [deleted file]
src/core/plugin/qlibrary_win.cpp [deleted file]
src/core/plugin/qsystemlibrary.cpp [deleted file]
src/core/plugin/qsystemlibrary_p.h [deleted file]
src/core/thread/qmutex_win.cpp [deleted file]
src/core/thread/qthread_win.cpp [deleted file]
src/core/thread/qwaitcondition_win.cpp [deleted file]
src/core/tools/qelapsedtimer_mac.cpp [deleted file]
src/core/tools/qelapsedtimer_win.cpp [deleted file]
src/core/tools/qlocale_blackberry.cpp [deleted file]
src/core/tools/qlocale_blackberry.h [deleted file]
src/core/tools/qlocale_mac.mm [deleted file]
src/core/tools/qlocale_win.cpp [deleted file]
src/declarative/util/qdeclarativeview.cpp
src/gui/accessible/qaccessible_mac.mm [deleted file]
src/gui/accessible/qaccessible_mac_carbon.cpp [deleted file]
src/gui/accessible/qaccessible_mac_cocoa.mm [deleted file]
src/gui/accessible/qaccessible_mac_p.h [deleted file]
src/gui/accessible/qaccessible_win.cpp [deleted file]
src/gui/dialogs/qcolordialog_mac.mm [deleted file]
src/gui/dialogs/qfiledialog_mac.mm [deleted file]
src/gui/dialogs/qfiledialog_win.cpp [deleted file]
src/gui/dialogs/qfiledialog_win_p.h [deleted file]
src/gui/dialogs/qfontdialog_mac.mm [deleted file]
src/gui/dialogs/qnspanelproxy_mac.mm [deleted file]
src/gui/dialogs/qpagesetupdialog_mac.mm [deleted file]
src/gui/dialogs/qpagesetupdialog_win.cpp [deleted file]
src/gui/dialogs/qprintdialog_mac.mm [deleted file]
src/gui/dialogs/qprintdialog_win.cpp [deleted file]
src/gui/dialogs/qwizard_win.cpp [deleted file]
src/gui/dialogs/qwizard_win_p.h [deleted file]
src/gui/egl/qegl_wince.cpp [deleted file]
src/gui/image/qpixmap_win.cpp [deleted file]
src/gui/inputmethod/qmacinputcontext_mac.cpp [deleted file]
src/gui/inputmethod/qwininputcontext_win.cpp [deleted file]
src/gui/kernel/qapplication_mac.mm [deleted file]
src/gui/kernel/qapplication_win.cpp [deleted file]
src/gui/kernel/qclipboard_mac.cpp [deleted file]
src/gui/kernel/qclipboard_win.cpp [deleted file]
src/gui/kernel/qcocoaapplication_mac.mm [deleted file]
src/gui/kernel/qcocoaapplication_mac_p.h [deleted file]
src/gui/kernel/qcocoaapplicationdelegate_mac.mm [deleted file]
src/gui/kernel/qcocoaapplicationdelegate_mac_p.h [deleted file]
src/gui/kernel/qcocoaintrospection_mac.mm [deleted file]
src/gui/kernel/qcocoamenuloader_mac.mm [deleted file]
src/gui/kernel/qcocoamenuloader_mac_p.h [deleted file]
src/gui/kernel/qcocoapanel_mac.mm [deleted file]
src/gui/kernel/qcocoapanel_mac_p.h [deleted file]
src/gui/kernel/qcocoasharedwindowmethods_mac_p.h [deleted file]
src/gui/kernel/qcocoaview_mac.mm [deleted file]
src/gui/kernel/qcocoaview_mac_p.h [deleted file]
src/gui/kernel/qcocoawindow_mac.mm [deleted file]
src/gui/kernel/qcocoawindow_mac_p.h [deleted file]
src/gui/kernel/qcocoawindowcustomthemeframe_mac.mm [deleted file]
src/gui/kernel/qcocoawindowcustomthemeframe_mac_p.h [deleted file]
src/gui/kernel/qcocoawindowdelegate_mac.mm [deleted file]
src/gui/kernel/qcocoawindowdelegate_mac_p.h [deleted file]
src/gui/kernel/qcursor_mac.mm [deleted file]
src/gui/kernel/qcursor_win.cpp [deleted file]
src/gui/kernel/qdesktopwidget_mac.mm [deleted file]
src/gui/kernel/qdesktopwidget_mac_p.h [deleted file]
src/gui/kernel/qdesktopwidget_win.cpp [deleted file]
src/gui/kernel/qdnd_mac.mm [deleted file]
src/gui/kernel/qdnd_win.cpp [deleted file]
src/gui/kernel/qeventdispatcher_mac.mm [deleted file]
src/gui/kernel/qeventdispatcher_mac_p.h [deleted file]
src/gui/kernel/qguifunctions_wince.cpp [deleted file]
src/gui/kernel/qguifunctions_wince.h [deleted file]
src/gui/kernel/qkeymapper_mac.cpp [deleted file]
src/gui/kernel/qkeymapper_win.cpp [deleted file]
src/gui/kernel/qmacdefines_mac.h [deleted file]
src/gui/kernel/qmacgesturerecognizer_mac.mm [deleted file]
src/gui/kernel/qmacgesturerecognizer_mac_p.h [deleted file]
src/gui/kernel/qmime_mac.cpp [deleted file]
src/gui/kernel/qmime_win.cpp [deleted file]
src/gui/kernel/qmultitouch_mac.mm [deleted file]
src/gui/kernel/qmultitouch_mac_p.h [deleted file]
src/gui/kernel/qnsframeview_mac_p.h [deleted file]
src/gui/kernel/qnsthemeframe_mac_p.h [deleted file]
src/gui/kernel/qnstitledframe_mac_p.h [deleted file]
src/gui/kernel/qole_win.cpp [deleted file]
src/gui/kernel/qsound_mac.mm [deleted file]
src/gui/kernel/qsound_win.cpp [deleted file]
src/gui/kernel/qt_cocoa_helpers_mac.mm [deleted file]
src/gui/kernel/qt_cocoa_helpers_mac_p.h [deleted file]
src/gui/kernel/qt_mac.cpp [deleted file]
src/gui/kernel/qt_mac_p.h [deleted file]
src/gui/kernel/qwidget_mac.mm [deleted file]
src/gui/kernel/qwidget_win.cpp [deleted file]
src/gui/kernel/qwidget_wince.cpp [deleted file]
src/gui/kernel/qwindowdefs_win.h [deleted file]
src/gui/kernel/qwinnativepangesturerecognizer_win.cpp [deleted file]
src/gui/kernel/qwinnativepangesturerecognizer_win_p.h [deleted file]
src/gui/painting/qcolormap_mac.cpp [deleted file]
src/gui/painting/qcolormap_win.cpp [deleted file]
src/gui/painting/qpaintdevice_mac.cpp [deleted file]
src/gui/painting/qpaintdevice_win.cpp [deleted file]
src/gui/painting/qpaintengine_mac.cpp [deleted file]
src/gui/painting/qpaintengine_mac_p.h [deleted file]
src/gui/painting/qprintengine_mac.mm [deleted file]
src/gui/painting/qprintengine_mac_p.h [deleted file]
src/gui/painting/qprintengine_win.cpp [deleted file]
src/gui/painting/qprintengine_win_p.h [deleted file]
src/gui/painting/qprinterinfo_mac.cpp [deleted file]
src/gui/painting/qprinterinfo_win.cpp [deleted file]
src/gui/painting/qregion_mac.cpp [deleted file]
src/gui/painting/qregion_win.cpp [deleted file]
src/gui/painting/qunifiedtoolbarsurface_mac.cpp [deleted file]
src/gui/painting/qunifiedtoolbarsurface_mac_p.h [deleted file]
src/gui/painting/qwindowsurface_mac.cpp [deleted file]
src/gui/painting/qwindowsurface_mac_p.h [deleted file]
src/gui/styles/qmacstyle_mac.h [deleted file]
src/gui/styles/qmacstyle_mac.mm [deleted file]
src/gui/styles/qmacstyle_mac_p.h [deleted file]
src/gui/styles/qmacstylepixmaps_mac_p.h [deleted file]
src/gui/styles/qstyle_wince.qrc [deleted file]
src/gui/text/qfont_mac.cpp [deleted file]
src/gui/text/qfont_win.cpp [deleted file]
src/gui/text/qfontdatabase_mac.h [deleted file]
src/gui/text/qfontdatabase_win.h [deleted file]
src/gui/text/qfontengine_coretext.mm [deleted file]
src/gui/text/qfontengine_mac.mm [deleted file]
src/gui/text/qfontengine_mac_p.h [deleted file]
src/gui/text/qfontengine_win.cpp [deleted file]
src/gui/text/qfontengine_win_p.h [deleted file]
src/gui/text/qrawfont_mac.cpp [deleted file]
src/gui/text/qrawfont_win.cpp [deleted file]
src/gui/text/qtextengine.cpp
src/gui/text/qtextengine_mac.cpp [deleted file]
src/gui/util/qdesktopservices_blackberry.cpp [deleted file]
src/gui/util/qdesktopservices_mac.cpp [deleted file]
src/gui/util/qdesktopservices_win.cpp [deleted file]
src/gui/util/qsystemtrayicon_mac.mm [deleted file]
src/gui/util/qsystemtrayicon_win.cpp [deleted file]
src/gui/util/qsystemtrayicon_wince.cpp [deleted file]
src/gui/widgets/qcocoamenu_mac.mm [deleted file]
src/gui/widgets/qcocoamenu_mac_p.h [deleted file]
src/gui/widgets/qcocoatoolbardelegate_mac.mm [deleted file]
src/gui/widgets/qcocoatoolbardelegate_mac_p.h [deleted file]
src/gui/widgets/qmaccocoaviewcontainer_mac.h [deleted file]
src/gui/widgets/qmaccocoaviewcontainer_mac.mm [deleted file]
src/gui/widgets/qmacnativewidget_mac.h [deleted file]
src/gui/widgets/qmacnativewidget_mac.mm [deleted file]
src/gui/widgets/qmainwindowlayout_mac.mm [deleted file]
src/gui/widgets/qmenu_mac.mm [deleted file]
src/gui/widgets/qmenu_wince.cpp [deleted file]
src/gui/widgets/qmenu_wince.rc [deleted file]
src/gui/widgets/qmenu_wince_resource_p.h [deleted file]
src/multimedia/audio/qaudio_mac.cpp [deleted file]
src/multimedia/audio/qaudio_mac_p.h [deleted file]
src/multimedia/audio/qaudiodeviceinfo_mac_p.cpp [deleted file]
src/multimedia/audio/qaudiodeviceinfo_mac_p.h [deleted file]
src/multimedia/audio/qaudioinput_mac_p.cpp [deleted file]
src/multimedia/audio/qaudioinput_mac_p.h [deleted file]
src/multimedia/audio/qaudiooutput_mac_p.cpp [deleted file]
src/multimedia/audio/qaudiooutput_mac_p.h [deleted file]
src/network/kernel/qhostinfo_win.cpp [deleted file]
src/network/kernel/qnetworkfunctions_wince.h [deleted file]
src/network/kernel/qnetworkinterface_win.cpp [deleted file]
src/network/kernel/qnetworkinterface_win_p.h [deleted file]
src/network/kernel/qnetworkproxy_blackberry.cpp [deleted file]
src/network/kernel/qnetworkproxy_mac.cpp [deleted file]
src/network/kernel/qnetworkproxy_win.cpp [deleted file]
src/network/socket/qlocalserver.cpp
src/network/socket/qlocalserver_p.h
src/network/socket/qlocalserver_win.cpp [deleted file]
src/network/socket/qlocalsocket.cpp
src/network/socket/qlocalsocket.h
src/network/socket/qlocalsocket_p.h
src/network/socket/qlocalsocket_tcp.cpp
src/network/socket/qlocalsocket_win.cpp [deleted file]
src/network/socket/qnativesocketengine_win.cpp [deleted file]
src/opengl/qgl_mac.mm [deleted file]
src/opengl/qgl_win.cpp [deleted file]
src/opengl/qgl_wince.cpp [deleted file]
src/opengl/qglpixelbuffer_mac.mm [deleted file]
src/opengl/qglpixelbuffer_win.cpp [deleted file]
src/plugins/bearer/blackberry/bbmain.cpp [deleted file]
src/plugins/bearer/blackberry/qbbengine.cpp [deleted file]
src/plugins/bearer/blackberry/qbbengine.h [deleted file]
src/plugins/bearer/corewlan/qcorewlanengine.h [deleted file]
src/plugins/bearer/corewlan/qcorewlanengine.mm [deleted file]
src/plugins/bearer/corewlan/qcorewlanengine_10_6.mm [deleted file]
src/plugins/bearer/corewlan/qcorewlanmain.cpp [deleted file]
src/plugins/bearer/icd/dbusdispatcher.cpp [deleted file]
src/plugins/bearer/icd/dbusdispatcher.h [deleted file]
src/plugins/bearer/icd/iapconf.cpp [deleted file]
src/plugins/bearer/icd/iapconf.h [deleted file]
src/plugins/bearer/icd/iapmonitor.cpp [deleted file]
src/plugins/bearer/icd/iapmonitor.h [deleted file]
src/plugins/bearer/icd/icdmain.cpp [deleted file]
src/plugins/bearer/icd/maemo_icd.cpp [deleted file]
src/plugins/bearer/icd/maemo_icd.h [deleted file]
src/plugins/bearer/icd/proxyconf.cpp [deleted file]
src/plugins/bearer/icd/proxyconf.h [deleted file]
src/plugins/bearer/icd/qicdengine.cpp [deleted file]
src/plugins/bearer/icd/qicdengine.h [deleted file]
src/plugins/bearer/icd/qnetworksession_impl.cpp [deleted file]
src/plugins/bearer/icd/qnetworksession_impl.h [deleted file]
src/plugins/bearer/icd/wlan-utils.h [deleted file]
src/plugins/bearer/nativewifi/platformdefs.h [deleted file]
src/plugins/bearer/nativewifi/qnativewifiemain.cpp [deleted file]
src/plugins/bearer/nativewifi/qnativewifiengine.cpp [deleted file]
src/plugins/bearer/nativewifi/qnativewifiengine.h [deleted file]
src/plugins/bearer/nla/main.cpp [deleted file]
src/plugins/bearer/nla/nla.pro [deleted file]
src/plugins/bearer/nla/qnlaengine.cpp [deleted file]
src/plugins/bearer/nla/qnlaengine.h [deleted file]
src/plugins/bearer/platformdefs_win.h [deleted file]
src/plugins/graphicssystems/meego/dithering.cpp [deleted file]
src/plugins/graphicssystems/meego/qmeegoextensions.cpp [deleted file]
src/plugins/graphicssystems/meego/qmeegoextensions.h [deleted file]
src/plugins/graphicssystems/meego/qmeegographicssystem.cpp [deleted file]
src/plugins/graphicssystems/meego/qmeegographicssystem.h [deleted file]
src/plugins/graphicssystems/meego/qmeegographicssystemplugin.cpp [deleted file]
src/plugins/graphicssystems/meego/qmeegographicssystemplugin.h [deleted file]
src/plugins/graphicssystems/meego/qmeegolivepixmapdata.cpp [deleted file]
src/plugins/graphicssystems/meego/qmeegolivepixmapdata.h [deleted file]
src/plugins/graphicssystems/meego/qmeegopixmapdata.cpp [deleted file]
src/plugins/graphicssystems/meego/qmeegopixmapdata.h [deleted file]
src/plugins/graphicssystems/meego/qmeegorasterpixmapdata.cpp [deleted file]
src/plugins/graphicssystems/meego/qmeegorasterpixmapdata.h [deleted file]
src/tools/designer/Info_mac.plist [deleted file]
src/tools/designer/designer.pro [deleted file]
src/tools/designer/designer.rc [deleted file]
src/tools/idc/main.cpp [deleted file]
src/tools/moc/mwerks_mac.cpp [deleted file]
src/tools/moc/mwerks_mac.h [deleted file]
src/tools/qdbusviewer/Info_mac.plist [deleted file]
src/tools/qdbusviewer/qdbusviewer.pro [deleted file]
src/tools/qdbusviewer/qdbusviewer.rc [deleted file]
src/winmain/qtmain_win.cpp [deleted file]

diff --git a/mkspecs/aix/qplatformdefs.h b/mkspecs/aix/qplatformdefs.h
deleted file mode 100644 (file)
index df61458..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef Q_AIX_QPLATFORMDEFS_H
-#define Q_AIX_QPLATFORMDEFS_H
-
-// Get Qt defines/settings
-
-#include "qglobal.h"
-
-// Set any POSIX/XOPEN defines at the top of this file to turn on specific APIs
-
-#include <unistd.h>
-
-
-// We are hot - unistd.h should have turned on the specific APIs we requested
-
-
-// uncomment if you have problems with <sys/proc.h> because your gcc
-// hasn't been built on exactly the same OS version your are using now.
-// typedef int crid_t;
-// typedef unsigned int class_id_t;
-#include <pthread.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <pwd.h>
-#include <signal.h>
-#include <dlfcn.h>
-#include <strings.h> // AIX X11 headers define FD_ZERO using bzero()
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/ipc.h>
-#include <sys/time.h>
-#include <sys/select.h>
-#include <sys/shm.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#ifndef QT_NO_IPV6IFNAME
-#include <net/if.h>
-#endif
-
-// Only AIX 4.3 and better support 64-bit
-
-#define QT_USE_XOPEN_LFS_EXTENSIONS
-#include "common/mkspecs_posix.h"
-
-#undef QT_SOCKLEN_T
-
-#ifdef _AIX43
-// AIX 4.3 and better
-#define QT_SOCKLEN_T            socklen_t
-#elif _AIX42
-// AIX 4.2
-#define QT_SOCKLEN_T            size_t
-#else
-// AIX 4.1
-#define QT_SOCKLEN_T            size_t
-// override
-#define QT_SOCKOPTLEN_T         int
-#endif
-
-#ifdef QT_LARGEFILE_SUPPORT
-#undef QT_DIR
-#undef QT_OPENDIR
-#undef QT_CLOSEDIR
-
-#define QT_DIR                  DIR64
-#define QT_OPENDIR              ::opendir64
-#define QT_CLOSEDIR             ::closedir64
-#endif
-
-#if defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE-0 >= 500)
-// AIX 4.3 and better
-#define QT_SNPRINTF             ::snprintf
-#define QT_VSNPRINTF            ::vsnprintf
-#endif
-
-#endif // include guard
diff --git a/mkspecs/blackberry/qmake.conf b/mkspecs/blackberry/qmake.conf
deleted file mode 100644 (file)
index 44ea967..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# qmake configuration for blackberry x86 systems
-#
-
-include(../qnx-armv7le-qcc/qmake.conf)
-
-load(qt_config)
-
-DEFINES += Q_OS_BLACKBERRY
-CONFIG += blackberry
-LIBS += -lbps
-
-# Blackberry also has support for stack smashing protection in its libc
-contains(QT_CONFIG, stack-protector-strong) {
-    QMAKE_CFLAGS += -fstack-protector-strong
-    QMAKE_CXXFLAGS += -fstack-protector-strong
-} else {
-    QMAKE_CFLAGS += -fstack-protector -fstack-protector-all
-    QMAKE_CXXFLAGS += -fstack-protector -fstack-protector-all
-}
-
-QMAKE_CFLAGS += -mcpu=cortex-a9
-QMAKE_CXXFLAGS += -mcpu=cortex-a9
-
-QMAKE_LFLAGS_SHLIB += -Wl,-z,relro -Wl,-z,now
diff --git a/mkspecs/blackberry/qplatformdefs.h b/mkspecs/blackberry/qplatformdefs.h
deleted file mode 100644 (file)
index a69dc40..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Research In Motion Limited. <blackberry-qt@qnx.com>
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMDEFS_H
-#define QPLATFORMDEFS_H
-
-// Get Qt defines/settings
-
-#include "qglobal.h"
-
-// Set any POSIX/XOPEN defines at the top of this file to turn on specific APIs
-
-#include <unistd.h>
-
-#define __STDC_CONSTANT_MACROS
-
-// We are hot - unistd.h should have turned on the specific APIs we requested
-
-
-#include <pthread.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <pwd.h>
-#include <signal.h>
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/ipc.h>
-#include <sys/time.h>
-// QNX doesn't have the System V <sys/shm.h> header. This is not a standard
-// POSIX header, it's only documented in the Single UNIX Specification.
-// The preferred POSIX compliant way to share memory is to use the functions
-// in <sys/mman.h> that comply with the POSIX Real Time Interface (1003.1b).
-#include <sys/mman.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#ifndef QT_NO_IPV6IFNAME
-#include <net/if.h>
-#endif
-
-// for htonl
-#include <arpa/inet.h>
-
-#define QT_USE_XOPEN_LFS_EXTENSIONS
-#if defined(__EXT_QNX__READDIR_R) && !defined(__EXT_QNX__READDIR64_R)
-#define QT_NO_READDIR64
-#endif
-#include "../common/posix/qplatformdefs.h"
-#if defined(__EXT_QNX__READDIR64_R)
-#define QT_EXT_QNX_READDIR_R    ::_readdir64_r
-#elif defined(__EXT_QNX__READDIR_R)
-#define QT_EXT_QNX_READDIR_R    ::_readdir_r
-#endif
-
-#define QT_SNPRINTF ::snprintf
-#define QT_VSNPRINTF ::vsnprintf
-
-// QNX6 doesn't have getpagesize()
-inline int getpagesize()
-{
-    return ::sysconf(_SC_PAGESIZE);
-}
-
-#include <stdlib.h>
-
-#define QT_QWS_TEMP_DIR QString::fromLatin1(qgetenv("TMP"))
-
-#define QT_NO_QWS_INPUTMETHODS
-
-#define QT_QPA_DEFAULT_PLATFORM_NAME "blackberry"
-
-#endif // QPLATFORMDEFS_H
-
diff --git a/mkspecs/darwin/qplatformdefs.h b/mkspecs/darwin/qplatformdefs.h
deleted file mode 100644 (file)
index 3292efd..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMDEFS_H
-#define QPLATFORMDEFS_H
-
-// Get Qt defines/settings
-
-#include "qglobal.h"
-
-// Set any POSIX/XOPEN defines at the top of this file to turn on specific APIs
-
-#include <unistd.h>
-
-
-// We are hot - unistd.h should have turned on the specific APIs we requested
-
-
-#include <pthread.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <pwd.h>
-#include <signal.h>
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/ipc.h>
-#include <sys/time.h>
-#include <sys/shm.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#ifndef QT_NO_IPV6IFNAME
-#include <net/if.h>
-#endif
-
-#include "common/mkspecs_posix.h"
-
-#undef QT_OPEN_LARGEFILE
-#define QT_OPEN_LARGEFILE       0
-
-#define QT_SNPRINTF            ::snprintf
-#define QT_VSNPRINTF           ::vsnprintf
-
-#endif // QPLATFORMDEFS_H
diff --git a/mkspecs/integrity/qmake.conf b/mkspecs/integrity/qmake.conf
deleted file mode 100644 (file)
index ddf9e24..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-#
-# Base qmake configuration for integrity-ghs
-#
-
-MAKEFILE_GENERATOR      = GBUILD
-TEMPLATE                = app
-CONFIG                  += qt warn_on release integrity unix
-QT                      += core gui network
-DEFINES                 += QT_NO_SHAREDMEMORY QT_NO_PROCESS QT_NO_QWS_MULTIPROCESS QT_NO_SYSTEMSEMAPHORE QT_NO_PRINTER QT_NO_QWS_QPF2
-
-QMAKE_CFLAGS            = -bsp $$INTEGRITY_BSP -os_dir $__OS_DIR
-QMAKE_CFLAGS            += --diag_suppress=1,228,236,381,611,997,1795
-QMAKE_CFLAGS_WARN_ON    =
-QMAKE_CFLAGS_WARN_OFF   = -w
-QMAKE_CFLAGS_RELEASE    = -g -Ospeed -Olink --signed_fields --no_commons
-QMAKE_CFLAGS_DEBUG      = -g --no_commons --signed_fields
-QMAKE_CFLAGS_SHLIB      =
-QMAKE_CFLAGS_THREAD     = -D_REENTRANT
-
-QMAKE_CXXFLAGS          = $$QMAKE_CFLAGS --no_implicit_include --link_once_templates -non_shared
-QMAKE_CXXFLAGS_WARN_ON  = $$QMAKE_CFLAGS_WARN_ON
-QMAKE_CXXFLAGS_WARN_OFF = $$QMAKE_CFLAGS_WARN_OFF
-QMAKE_CXXFLAGS_RELEASE  = $$QMAKE_CFLAGS_RELEASE
-QMAKE_CXXFLAGS_DEBUG    = $$QMAKE_CFLAGS_DEBUG
-QMAKE_CXXFLAGS_SHLIB    = $$QMAKE_CFLAGS_SHLIB
-QMAKE_CXXFLAGS_YACC     = $$QMAKE_CFLAGS_YACC
-QMAKE_CXXFLAGS_THREAD   = $$QMAKE_CFLAGS_THREAD
-
-QMAKE_INCDIR            =
-QMAKE_LIBDIR            =
-QMAKE_INCDIR_X11        =
-QMAKE_LIBDIR_X11        =
-QMAKE_INCDIR_QT         = $$[QT_INSTALL_HEADERS]
-QMAKE_LIBDIR_QT         = $$[QT_INSTALL_LIBS]
-QMAKE_INCDIR_OPENGL     =
-QMAKE_LIBDIR_OPENGL     =
-QMAKE_INCDIR_QTOPIA     = $(QPEDIR)/include
-QMAKE_LIBDIR_QTOPIA     = $(QPEDIR)/lib
-
-QMAKE_LFLAGS            = -lposix -livfs -lnet -lsocket -lfbdev -lhiddev -ldl
-QMAKE_LFLAGS_RELEASE    = -g -Ospeed -Olink --no_commons -non_shared --link_once_templates
-QMAKE_LFLAGS_DEBUG      = -g --no_commons -non_shared --link_once_templates
-QMAKE_LFLAGS_SHLIB      =
-QMAKE_LFLAGS_PLUGIN     = $$QMAKE_LFLAGS_SHLIB
-QMAKE_LFLAGS_SONAME     =
-QMAKE_LFLAGS_THREAD     =
-QMAKE_LFLAGS_RPATH      =
-
-QMAKE_LIBS              =
-QMAKE_LIBS_DYNLOAD      = -ldl
-QMAKE_LIBS_X11          =
-QMAKE_LIBS_X11SM        =
-QMAKE_LIBS_QTOPIA       =
-QMAKE_LIBS_THREAD       =
diff --git a/mkspecs/integrity/qplatformdefs.h b/mkspecs/integrity/qplatformdefs.h
deleted file mode 100644 (file)
index 6a8198b..0000000
+++ /dev/null
@@ -1,201 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// Get Qt defines/settings
-
-#include "qglobal.h"
-
-// Set any POSIX/XOPEN defines at the top of this file to turn on specific APIs
-
-#include <unistd.h>
-
-// We are hot - unistd.h should have turned on the specific APIs we requested
-
-#include <pthread.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <pwd.h>
-#include <signal.h>
-#include <dlfcn.h>
-#include <limits.h>
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/time.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#ifndef QT_NO_IPV6IFNAME
-#include <net/if.h>
-#endif
-
-#ifdef QT_LARGEFILE_SUPPORT
-#define QT_STATBUF              struct stat64
-#define QT_STATBUF4TSTAT        struct stat64
-#define QT_STAT                 ::stat64
-#define QT_FSTAT                ::fstat64
-#define QT_LSTAT                ::lstat64
-#define QT_OPEN                 ::open64
-#define QT_TRUNCATE             ::truncate64
-#define QT_FTRUNCATE            ::ftruncate64
-#define QT_LSEEK                ::lseek64
-#else
-#define QT_STATBUF              struct stat
-#define QT_STATBUF4TSTAT        struct stat
-#define QT_STAT                 ::stat
-#define QT_FSTAT                ::fstat
-#define QT_LSTAT                ::lstat
-#define QT_OPEN                 ::open
-#define QT_TRUNCATE             ::truncate
-#define QT_FTRUNCATE            ::ftruncate
-#define QT_LSEEK                ::lseek
-#define QT_OPEN_LARGEFILE       0
-#endif
-
-#ifdef QT_LARGEFILE_SUPPORT
-#define QT_FOPEN                ::fopen64
-#define QT_FSEEK                ::fseeko64
-#define QT_FTELL                ::ftello64
-#define QT_FGETPOS              ::fgetpos64
-#define QT_FSETPOS              ::fsetpos64
-#define QT_FPOS_T               fpos64_t
-#define QT_OFF_T                off64_t
-#else
-#define QT_FOPEN                ::fopen
-#define QT_FSEEK                ::fseek
-#define QT_FTELL                ::ftell
-#define QT_FGETPOS              ::fgetpos
-#define QT_FSETPOS              ::fsetpos
-#define QT_FPOS_T               fpos_t
-#define QT_OFF_T                long
-#endif
-
-#define QT_STAT_REG             S_IFREG
-#define QT_STAT_DIR             S_IFDIR
-#define QT_STAT_MASK            S_IFMT
-#define QT_STAT_LNK             S_IFLNK
-#define QT_SOCKET_CONNECT       ::connect
-#define QT_SOCKET_BIND          ::bind
-#define QT_FILENO               fileno
-#ifndef QT_CLOSE
-#define QT_CLOSE                ::close
-#endif
-#ifndef QT_READ
-#define QT_READ                 ::read
-#endif
-#ifndef QT_WRITE
-#define QT_WRITE                ::write
-#endif
-#define QT_ACCESS               ::access
-#define QT_GETCWD               ::getcwd
-#define QT_CHDIR                ::chdir
-#define QT_MKDIR                ::mkdir
-#define QT_RMDIR                ::rmdir
-#define QT_OPEN_RDONLY          O_RDONLY
-#define QT_OPEN_WRONLY          O_WRONLY
-#define QT_OPEN_RDWR            O_RDWR
-#define QT_OPEN_CREAT           O_CREAT
-#define QT_OPEN_TRUNC           O_TRUNC
-#define QT_OPEN_APPEND          O_APPEND
-
-#define QT_SIGNAL_RETTYPE       void
-#define QT_SIGNAL_ARGS          int
-#define QT_SIGNAL_IGNORE        SIG_IGN
-
-#define QT_MMAP                 ::mmap
-
-// Directory iteration
-#define QT_DIR                  DIR
-
-#define QT_OPENDIR              ::opendir
-#define QT_CLOSEDIR             ::closedir
-
-
-#if defined(QT_LARGEFILE_SUPPORT) \
-        && defined(QT_USE_XOPEN_LFS_EXTENSIONS) \
-        && !defined(QT_NO_READDIR64)
-# define QT_DIRENT               struct dirent64
-# define QT_READDIR              ::readdir64
-# define QT_READDIR_R            ::readdir64_r
-#else
-# define QT_DIRENT               struct dirent
-# define QT_READDIR              ::readdir
-# define QT_READDIR_R            ::readdir_r
-#endif
-
-#define QT_SOCKLEN_T           socklen_t
-
-#if defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 500)
-#define QT_SNPRINTF             ::snprintf
-#define QT_VSNPRINTF            ::vsnprintf
-#endif
-
-#ifndef MAXNAMLEN
-#  define MAXNAMLEN NAME_MAX
-#endif
-
-#ifndef PATH_MAX
-#  define PATH_MAX MAXPATHLEN
-#endif
-
-#ifndef NSIG
-#  define NSIG _SIGMAX
-#endif
-
-#ifndef MAP_ANON
-#  define MAP_ANON 0
-#endif
-
-typedef void (*sighandler_t)(int);
-
-#ifndef QT_NO_MMAP
-#  define QT_NO_MMAP
-#endif
-
-#ifndef QT_NO_SHAREDMEMORY
-#  define QT_NO_SHAREDMEMORY
-#endif
-
-#ifndef QT_NO_SYSTEMSEMAPHORE
-#  define QT_NO_SYSTEMSEMAPHORE
-#endif
diff --git a/mkspecs/ios/GLES/gl.h b/mkspecs/ios/GLES/gl.h
deleted file mode 100644 (file)
index 83cfc6c..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <OpenGLES/ES1/gl.h>
-#include <OpenGLES/ES1/glext.h>
\ No newline at end of file
diff --git a/mkspecs/ios/GLES2/gl2.h b/mkspecs/ios/GLES2/gl2.h
deleted file mode 100644 (file)
index 99a81e4..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <OpenGLES/ES2/gl.h>
-#include <OpenGLES/ES2/glext.h>
diff --git a/mkspecs/ios/arch.conf b/mkspecs/ios/arch.conf
deleted file mode 100644 (file)
index 4ad9687..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-#
-# Helper to set CPU architecture flags for iOS configurations
-#
-# Depends on:
-#
-#   QMAKE_IPHONEOS_DEPLOYMENT_TARGET - set in mkspecs/common/ios/versions.conf
-#
-# Note:
-#
-#   Must be included after load(qt_config) in mkspec for auto-detection based
-#   on GL/ES version (GL/ES 2.x implies armv7 on iOS).
-#
-
-# Target architecture for iOS devices (armv6, armv7 or leave blank for default)
-QMAKE_IOS_TARGET_ARCH   =
-
-###########################################################################
-
-# Device?
-!*simulator* {
-    # Let mkspec specify archictecture
-    *armv6*: QMAKE_IOS_TARGET_ARCH = armv6
-    else:*armv7*: QMAKE_IOS_TARGET_ARCH = armv7
-
-    # ARMv7 architecture device (see below) is required for OpenGL/ES 2.x
-    isEmpty(QMAKE_IOS_TARGET_ARCH):contains(QT_CONFIG, opengles2): QMAKE_IOS_TARGET_ARCH = armv7
-
-    # No target architecture specified?
-    isEmpty(QMAKE_IOS_TARGET_ARCH) {
-        # iOS versions < 4.3 can be armv6 or armv7, so need armv6 for max. compatibility,
-        # assume that building for OpenGL/ES 1.x is targeting armv6
-        lessThan(QMAKE_IPHONEOS_DEPLOYMENT_TARGET, "4.3")|contains(QT_CONFIG, opengles1) {
-            QMAKE_IOS_TARGET_ARCH = armv6
-        } else: QMAKE_IOS_TARGET_ARCH = armv7
-    }
-
-    # Samsung S5PC100, Apple A4, A5, A5X
-    equals(QMAKE_IOS_TARGET_ARCH, "armv7") {
-        # iOS CPU architecture (armv7)
-        QMAKE_IOS_ARM_ARCH = __ARM_ARCH_7__
-
-        # Thumb2 instructions
-        QMAKE_IOS_ARM_FLAGS = -mthumb
-        QMAKE_IOS_ARM_ARCH += __MARM_THUMB__
-
-        # NEON instructions
-        *-g++*: QMAKE_IOS_ARM_FLAGS += -mfloat-abi=softfp -mfpu=neon
-        QMAKE_IOS_ARM_ARCH += __ARM_NEON__
-    } else {
-        # Samsung S5L8900
-        if(equals(QMAKE_IOS_TARGET_ARCH, "armv6")) {
-            # iOS CPU architecture (armv6)
-            QMAKE_IOS_ARM_ARCH = __ARM_ARCH_6__
-
-            # ARM instructions
-            QMAKE_IOS_ARM_FLAGS = -marm -mcpu=arm1176jzf-s
-            !*clang*: QMAKE_IOS_ARM_FLAGS += -march=armv6
-        } else {
-            # Unsupported architecture
-            error("Invalid iOS target $${QMAKE_IOS_TARGET_ARCH}! Edit mkspecs/common/ios/arch.conf to specify target architecture.")
-        }
-    }
-# Simulator is i386 only
-} else: QMAKE_IOS_TARGET_ARCH = i386
-
-# iOS architecture build flags
-QMAKE_IOS_ARCH_FLAGS    = -arch $$QMAKE_IOS_TARGET_ARCH
-QMAKE_CFLAGS           += $$QMAKE_IOS_ARCH_FLAGS
-QMAKE_CXXFLAGS         += $$QMAKE_IOS_ARCH_FLAGS
-QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_IOS_ARCH_FLAGS
-QMAKE_LFLAGS           += $$QMAKE_IOS_ARCH_FLAGS
-QMAKE_IOS_TARGET_ARCH   =
-QMAKE_IOS_ARCH_FLAGS    =
-
-# Architecture specific defines/flags
-!*simulator* {
-    DEFINES            += $$QMAKE_IOS_ARM_ARCH
-    QMAKE_IOS_ARM_ARCH  =
-
-    QMAKE_CFLAGS       += $$QMAKE_IOS_ARM_FLAGS
-    QMAKE_CXXFLAGS     += $$QMAKE_IOS_ARM_FLAGS
-    QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_IOS_ARM_FLAGS
-    QMAKE_IOS_ARM_FLAGS =
-}
diff --git a/mkspecs/ios/clang.conf b/mkspecs/ios/clang.conf
deleted file mode 100644 (file)
index 81f76ae..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-#
-# compiler settings for iOS clang compilers
-#
-# Depends on:
-#
-#   QMAKE_IOS_XCODE_VERSION - set in mkspecs/common/ios/versions.conf
-#
-
-# iOS build flags
-QMAKE_IOS_CFLAGS        = -fvisibility=hidden -fpascal-strings -fmessage-length=0
-QMAKE_IOS_CFLAGS       += -Wno-trigraphs -Wreturn-type -Wparentheses -Wswitch -Wno-unused-parameter
-QMAKE_IOS_CFLAGS       += -Wunused-variable -Wunused-value -Wno-shorten-64-to-32 -Wno-sign-conversion
-QMAKE_IOS_CXXFLAGS      = -fvisibility-inlines-hidden
-QMAKE_IOS_OBJ_CFLAGS    = -Wno-arc-abi -Wc++0x-extensions
-
-# Device or simulator specific flags
-*simulator* {
-    QMAKE_IOS_CFLAGS   += -fexceptions -fasm-blocks
-    QMAKE_IOS_OBJ_CFLAGS += -fobjc-abi-version=2 -fobjc-legacy-dispatch
-}
-
-# Compiler version-specific flags
-!lessThan(QMAKE_IOS_XCODE_VERSION, "4.3") {
-    # Clang 3.1 flags (will be used for later versions too)
-    QMAKE_IOS_CFLAGS    += -Wno-missing-field-initializers -Wno-missing-prototypes -Wno-implicit-atomic-properties
-    QMAKE_IOS_CFLAGS    += -Wformat -Wno-missing-braces -Wno-unused-function -Wno-unused-label -Wuninitialized
-    QMAKE_IOS_CFLAGS    += -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-sign-compare -Wpointer-sign
-    QMAKE_IOS_CFLAGS    += -Wno-newline-eof -Wdeprecated-declarations -Winvalid-offsetof -Wno-conversion
-    QMAKE_IOS_CXXFLAGS  += -Wno-non-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wc++11-extensions
-    QMAKE_IOS_OBJ_CFLAGS += -Wno-deprecated-implementations -Wprotocol -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector
-
-    # Warn about unsupported (later than 4.5) Xcode versions
-    !lessThan(QMAKE_IOS_XCODE_VERSION, "4.6"): warning("The version of Xcode installed on this system is not recognised - custom compiler settings may be necessary")
-} else {
-    if (!lessThan(QMAKE_IOS_XCODE_VERSION, "4.2")) {
-        # Clang 3.0 flags
-        QMAKE_IOS_CFLAGS += -fdiagnostics-print-source-range-info -fdiagnostics-show-category=id -fdiagnostics-parseable-fixits
-    } else {
-        # Older Clang versions are not supported
-        error("Unsupported Xcode version $${QMAKE_IOS_XCODE_VERSION}")
-    }
-}
-
-# Set build flags
-QMAKE_CFLAGS           += $$QMAKE_IOS_CFLAGS
-QMAKE_CXXFLAGS         += $$QMAKE_IOS_CFLAGS $$QMAKE_IOS_CXXFLAGS
-QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_IOS_CFLAGS $$QMAKE_IOS_CXXFLAGS $$QMAKE_IOS_OBJ_CFLAGS
-
-QMAKE_IOS_CFLAGS =
-QMAKE_IOS_CXXFLAGS =
-QMAKE_IOS_OBJ_CFLAGS =
diff --git a/mkspecs/ios/g++.conf b/mkspecs/ios/g++.conf
deleted file mode 100644 (file)
index 8a1e0b2..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-# compiler settings for iOS g++ compilers
-#
-
-# iOS build flags
-QMAKE_IOS_CFLAGS        = -fvisibility=hidden -fexceptions -fmessage-length=0
-QMAKE_IOS_CFLAGS       += -Wno-trigraphs -Wreturn-type -Wunused-variable
-QMAKE_IOS_CXXFLAGS      = -fvisibility-inlines-hidden
-
-# Device or simulator specific flags
-!*simulator*: QMAKE_IOS_OBJ_CFLAGS =
-else: QMAKE_IOS_OBJ_CFLAGS = -fobjc-abi-version=2 -fobjc-legacy-dispatch
-
-# Set build flags
-QMAKE_CFLAGS           += $$QMAKE_IOS_CFLAGS
-QMAKE_CXXFLAGS         += $$QMAKE_IOS_CFLAGS $$QMAKE_IOS_CXXFLAGS
-QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_IOS_CFLAGS $$QMAKE_IOS_CXXFLAGS $$QMAKE_IOS_OBJ_CFLAGS
-
-QMAKE_IOS_CFLAGS =
-QMAKE_IOS_CXXFLAGS =
-QMAKE_IOS_OBJ_CFLAGS =
diff --git a/mkspecs/ios/gcc-base-ios.conf b/mkspecs/ios/gcc-base-ios.conf
deleted file mode 100644 (file)
index 68ec777..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-#
-# Base qmake configuration for GCC on iOS
-#
-# Before making changes to this file, please read the comment in
-# gcc-base.conf, to make sure the change goes in the right place.
-#
-# To verify that your change has the desired effect on the final configuration
-# you can use the manual test in tests/manual/mkspecs.
-#
-
-include(gcc-base.conf)
-
-QMAKE_COMPILER_DEFINES += __APPLE__ __GNUC__=4
-
-QMAKE_CFLAGS_DWARF2    += -gdwarf-2
-
-QMAKE_CXXFLAGS_DWARF2  += $$QMAKE_CFLAGS_DWARF2
-
-QMAKE_OBJECTIVE_CFLAGS          = $$QMAKE_CFLAGS
-QMAKE_OBJECTIVE_CFLAGS_WARN_ON  = $$QMAKE_CFLAGS_WARN_ON
-QMAKE_OBJECTIVE_CFLAGS_WARN_OFF = $$QMAKE_CFLAGS_WARN_OFF
-QMAKE_OBJECTIVE_CFLAGS_DEBUG    = $$QMAKE_CFLAGS_DEBUG
-QMAKE_OBJECTIVE_CFLAGS_RELEASE  = $$QMAKE_CFLAGS_RELEASE
-QMAKE_OBJECTIVE_CFLAGS_HIDESYMS = $$QMAKE_CXXFLAGS_HIDESYMS
-
-QMAKE_LFLAGS                += -headerpad_max_install_names
-QMAKE_LFLAGS_SHLIB          += -single_module -dynamiclib
-QMAKE_LFLAGS_PLUGIN         += $$QMAKE_LFLAGS_SHLIB
-QMAKE_LFLAGS_INCREMENTAL    += -undefined suppress -flat_namespace
-QMAKE_LFLAGS_SONAME         += -install_name$${LITERAL_WHITESPACE}@executable_path/
-QMAKE_LFLAGS_VERSION        += -current_version$${LITERAL_WHITESPACE}
-QMAKE_LFLAGS_COMPAT_VERSION += -compatibility_version$${LITERAL_WHITESPACE}
-
diff --git a/mkspecs/ios/ios.conf b/mkspecs/ios/ios.conf
deleted file mode 100644 (file)
index 050852e..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-# qmake common configuration for iOS
-#
-
-MAKEFILE_GENERATOR      = UNIX
-TEMPLATE                = app
-CONFIG                 += qt ios warn_on release reduce_exports incremental global_init_link_order lib_version_first plugin_no_soname link_prl
-QT                     += core gui opengl
-QMAKE_INCREMENTAL_STYLE = sublib
-
-# Qt can't build iOS app bundle :(
-CONFIG                 -= app_bundle
-
-# Not deploying to Mac OSX
-QMAKE_MACOSX_DEPLOYMENT_TARGET =
-
-# Add iOS common folder to include path
-INCLUDEPATH            += $$PWD/ios
-
-# iOS defines
-DEFINES                += DARWIN_NO_CARBON Q_OS_IOS QT_NO_QWS_QPF QT_NO_QWS_QPF2 QT_NO_QWS_INPUTMETHODS QT_NO_PRINTER QT_NO_PRINTDIALOG
diff --git a/mkspecs/ios/llvm.conf b/mkspecs/ios/llvm.conf
deleted file mode 100644 (file)
index fa2e519..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-#
-# compiler settings for iOS llvm-g++ compilers
-#
-# Depends on:
-#
-#   QMAKE_IOS_XCODE_VERSION - set in mkspecs/common/ios/versions.conf
-#
-
-# iOS build flags
-QMAKE_IOS_CFLAGS        = -fvisibility=hidden -fpascal-strings -fmessage-length=0
-QMAKE_IOS_CFLAGS       += -Wno-trigraphs -Wreturn-type -Wunused-variable
-QMAKE_IOS_CXXFLAGS      = -fvisibility-inlines-hidden
-
-# Device or simulator specific flags
-!*simulator*: QMAKE_IOS_OBJ_CFLAGS =
-else: QMAKE_IOS_OBJ_CFLAGS = -fobjc-abi-version=2 -fobjc-legacy-dispatch
-
-# Compiler version specific flags
-!lessThan(QMAKE_IOS_XCODE_VERSION, "4.3") {
-    # Xcode 4.3+ specific flags
-    QMAKE_IOS_CFLAGS   += -Wuninitialized
-}
-
-# Set build flags
-QMAKE_CFLAGS           += $$QMAKE_IOS_CFLAGS
-QMAKE_CXXFLAGS         += $$QMAKE_IOS_CFLAGS $$QMAKE_IOS_CXXFLAGS
-QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_IOS_CFLAGS $$QMAKE_IOS_CXXFLAGS $$QMAKE_IOS_OBJ_CFLAGS
-
-QMAKE_IOS_CFLAGS =
-QMAKE_IOS_CXXFLAGS =
-QMAKE_IOS_OBJ_CFLAGS =
diff --git a/mkspecs/ios/qmake.conf b/mkspecs/ios/qmake.conf
deleted file mode 100644 (file)
index 8ee2575..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-#
-# Common build settings for all iOS configurations
-#
-# Depends on:
-#
-#   QMAKE_IOS_XCODE_VERSION - set in mkspecs/common/ios/versions.conf
-#   QMAKE_IOS_SDK_VERSION   - set in mkspecs/common/ios/versions.conf
-#   QMAKE_IOSSIMULATOR_SDK_VERSION - set in mkspecs/common/ios/versions.conf
-#
-
-# iOS SDK device type
-!*simulator*: QMAKE_IOS_DEVICE_TYPE = iPhoneOS
-else {
-    QMAKE_IOS_DEVICE_TYPE = iPhoneSimulator
-
-    # Use simulator SDK version
-    QMAKE_IOS_SDK_VERSION = $$QMAKE_IOS_SIMULATOR_SDK_VERSION
-    QMAKE_IOS_SIMULATOR_SDK_VERSION =
-}
-
-!lessThan(QMAKE_IOS_XCODE_VERSION, "4.3") {
-    # Xcode 4.3+ is stored in /Applications
-    QMAKE_IOS_XCODE_PATH = /Applications/Xcode.app/Contents
-} else: QMAKE_IOS_XCODE_PATH =
-
-# iOS platform /Developer path
-QMAKE_IOS_DEV_PATH      = $$QMAKE_IOS_XCODE_PATH/Developer/Platforms/$${QMAKE_IOS_DEVICE_TYPE}.platform/Developer
-QMAKE_IOS_XCODE_PATH    =
-
-# iOS platform SDK path
-QMAKE_IOS_SDK           = $$QMAKE_IOS_DEV_PATH/SDKs/$${QMAKE_IOS_DEVICE_TYPE}$${QMAKE_IOS_SDK_VERSION}.sdk
-QMAKE_IOS_DEV_PATH      =
-QMAKE_IOS_DEVICE_TYPE   =
-
-QMAKE_CFLAGS           += -isysroot $$QMAKE_IOS_SDK
-QMAKE_CXXFLAGS         += -isysroot $$QMAKE_IOS_SDK
-QMAKE_OBJECTIVE_CFLAGS += -isysroot $$QMAKE_IOS_SDK
-QMAKE_LFLAGS           += -Wl,-syslibroot,$$QMAKE_IOS_SDK
-QMAKE_IOS_SDK           =
-
-# Basic iOS frameworks needed for any GUI app
-QMAKE_LFLAGS           += -framework Foundation -framework UIKit -framework QuartzCore -lz
-
-# OpenGL ES1
-QMAKE_INCDIR_OPENGL_ES1 = $$QMAKE_IOS_SDK/System/Library/Frameworks/OpenGLES.framework/Headers
-QMAKE_LIBDIR_OPENGL_ES1 =
-QMAKE_LIBS_OPENGL_ES1   = -framework OpenGLES
-
-# OpenGL ES2
-QMAKE_INCDIR_OPENGL_ES2 = $$QMAKE_IOS_SDK/System/Library/Frameworks/OpenGLES.framework/Headers
-QMAKE_LIBDIR_OPENGL_ES2 =
-QMAKE_LIBS_OPENGL_ES2   = -framework OpenGLES
-
-# No desktop OpenGL
-QMAKE_INCDIR_OPENGL     =
-QMAKE_LIBS_OPENGL       =
-QMAKE_LIBS_OPENGL_QT    =
-
-# Compiler-specific flags
-!*-g++* {
-    # Objective-C/C++ precompile flags
-    QMAKE_OBJCFLAGS_PRECOMPILE = -x objective-c-header -c ${QMAKE_PCH_INPUT} -o ${QMAKE_PCH_OUTPUT}
-    QMAKE_OBJCFLAGS_USE_PRECOMPILE = $$QMAKE_CFLAGS_USE_PRECOMPILE
-    QMAKE_OBJCXXFLAGS_PRECOMPILE = -x objective-c++-header -c ${QMAKE_PCH_INPUT} -o ${QMAKE_PCH_OUTPUT}
-    QMAKE_OBJCXXFLAGS_USE_PRECOMPILE = $$QMAKE_CFLAGS_USE_PRECOMPILE
-}
diff --git a/mkspecs/ios/qplatformdefs.h b/mkspecs/ios/qplatformdefs.h
deleted file mode 100644 (file)
index 93742b9..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMDEFS_H
-#define QPLATFORMDEFS_H
-
-// Get Qt defines/settings
-
-#include "qglobal.h"
-
-// Set any POSIX/XOPEN defines at the top of this file to turn on specific APIs
-
-#include <unistd.h>
-
-
-// We are hot - unistd.h should have turned on the specific APIs we requested
-
-
-#include <pthread.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <pwd.h>
-#include <signal.h>
-#define QT_NO_LIBRARY_UNLOAD
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/ipc.h>
-#include <sys/time.h>
-#include <sys/shm.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#ifndef QT_NO_IPV6IFNAME
-#include <net/if.h>
-#endif
-
-#include "common/mkspecs_posix.h"
-
-#undef QT_OPEN_LARGEFILE
-#undef QT_SOCKLEN_T
-#undef QT_SIGNAL_IGNORE
-
-#define QT_OPEN_LARGEFILE       0
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
-#define QT_SOCKLEN_T            socklen_t
-#else
-#define QT_SOCKLEN_T            int
-#endif
-
-#define QT_SIGNAL_IGNORE        (void (*)(int))1
-
-#define QT_SNPRINTF             ::snprintf
-#define QT_VSNPRINTF            ::vsnprintf
-
-#endif // QPLATFORMDEFS_H
diff --git a/mkspecs/ios/versions.conf b/mkspecs/ios/versions.conf
deleted file mode 100644 (file)
index b755068..0000000
+++ /dev/null
@@ -1,184 +0,0 @@
-#
-# Helper to set build tool & SDK versions for iOS configurations
-#
-# This file sets up the following configuration variables:
-#
-#   QMAKE_IOS_XCODE_VERSION          - version number of Xcode being used
-#   QMAKE_IOS_SDK_VERSION            - version number of iOS device SDK
-#   QMAKE_IOS_SIMULATOR_SDK_VERSION  - version number of iOS simulator SDK
-#
-# Used in:
-#
-#   mkspecs/common/ios/clang.conf
-#   mkspecs/common/ios/llvm.conf
-#   mkspecs/common/ios/qmake.conf
-#   mkspecs/unsupported/macx-iosdevice-clang-legacy/qmake.conf
-#   mkspecs/unsupported/macx-iosdevice-clang/qmake.conf
-#   mkspecs/unsupported/macx-iosdevice-llvm-legacy/qmake.conf
-#   mkspecs/unsupported/macx-iosdevice-llvm/qmake.conf
-#   mkspecs/unsupported/macx-iosdevice-g++-legacy/qmake.conf
-#   mkspecs/unsupported/macx-iossimulator-llvm-legacy/qmake.conf
-#   mkspecs/unsupported/macx-iossimulator-llvm/qmake.conf
-#   mkspecs/unsupported/macx-iossimulator-g++-legacy/qmake.conf
-#
-
-#
-# IMPORTANT:
-#
-# Xcode versions <= 4.2.x must be installed in /Developer.
-# Xcode versions >= 4.3.x must be installed in /Applications
-#
-# Xcode versions >= 4.10 & < 5.0 and versions >= 10.0 are not supported due to
-# the way the version checks are done here. As Apple (so far) has not used
-# minor version numbers greater than 3 for Xcode, and the Xcode major version
-# has only changed three times in the period 2003-2012, this is viewed as an
-# acceptable limitation.
-#
-
-#
-# Edit values below to match iOS build environment, or leave blank for
-# autodetection (slower!)
-#
-
-# Xcode version used for cross-compiling
-QMAKE_IOS_XCODE_VERSION =
-
-# iOS SDK version used for cross-compiling for iOS devices
-QMAKE_IOS_SDK_VERSION   =
-
-# iOS SDK version used for cross-compiling for the iOS simulator
-QMAKE_IOS_SIMULATOR_SDK_VERSION =
-
-#
-# Do not edit values below here if using a pre-built SDK
-#
-
-# Minimum iOS version required on deployment target (if not specified, will
-# default to minimum version that guarantees ARMv7 & OpenGL/ES 2.x).
-#
-# No part of Qt or any known plugin uses features that require iOS versions
-# later than 4.0.
-QMAKE_IPHONEOS_DEPLOYMENT_TARGET = 4.0
-
-###########################################################################
-
-# No Xcode version specified?
-isEmpty(QMAKE_IOS_XCODE_VERSION) {
-    # Get version string from installed Xcode
-    exists(/Applications/Xcode.app/Contents/Developer) {
-        QMAKE_IOS_XCODE_INFO = $$system(/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -version)
-    } else: QMAKE_IOS_XCODE_INFO = $$system(/Developer/usr/bin/xcodebuild -version)
-
-    # Extract Xcode version number from output
-    QMAKE_IOS_XCODE_VERSION = $$member(QMAKE_IOS_XCODE_INFO, 1)
-    QMAKE_IOS_XCODE_INFO =
-}
-
-# Make sure Xcode version is valid
-!lessThan(QMAKE_IOS_XCODE_VERSION, "4.3") {
-    # Xcode 4.3+ is stored in /Applications
-    QMAKE_IOS_PLATFORM_PATH  = /Applications/Xcode.app/Contents/Developer/Platforms
-
-    # Make sure Xcode path is valid
-    !exists($$QMAKE_IOS_PLATFORM_PATH): error("Xcode is not installed in /Applications/Xcode.app! Edit mkspecs/common/ios/versions.conf to specify version installed.")
-} else {
-    # Older Xcode versions are stored in /Developer
-    QMAKE_IOS_PLATFORM_PATH  = /Developer/Platforms
-
-    # Make sure Xcode path is valid
-    !exists($$QMAKE_IOS_PLATFORM_PATH): error("Xcode is not installed in /Developer! Edit mkspecs/common/ios/versions.conf to specify version installed.")
-}
-
-# iOS 4.3 is the preferred version as it is the earliest version that is armv7/gles2 only
-QMAKE_IPHONEOS_PREFERRED_TARGET = 4.3
-
-# Building for iOS device?
-!*simulator* {
-    # No iOS SDK version specified?
-    isEmpty(QMAKE_IOS_SDK_VERSION) {
-        # Get version string from installed Xcode
-        !lessThan(QMAKE_IOS_XCODE_VERSION, "4.3") {
-            QMAKE_IOS_SDK_INFO = $$system(/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -showsdks)
-        } else: QMAKE_IOS_SDK_INFO = $$system(/Developer/usr/bin/xcodebuild -showsdks)
-
-        # Get names of installed device SDKs
-        QMAKE_IOS_SDK_INFO = $$find(QMAKE_IOS_SDK_INFO, ^iphoneos)
-        for(v, QMAKE_IOS_SDK_INFO): {
-            # Extract SDK version number from output
-            v = $$replace(v,iphoneos,)
-
-            # Use latest SDK version
-            greaterThan(v, $$QMAKE_IOS_SDK_VERSION): QMAKE_IOS_SDK_VERSION = $$v
-        }
-        QMAKE_IOS_SDK_INFO =
-    }
-
-    # Make sure iOS SDK version is valid
-    !exists($$QMAKE_IOS_PLATFORM_PATH/iPhoneOS.platform/Developer/SDKs/iPhoneOS$${QMAKE_IOS_SDK_VERSION}.sdk) {
-        error("iOS $$QMAKE_IOS_SDK_VERSION SDK not found! Edit mkspecs/common/ios/versions.conf to specify version installed.")
-    }
-
-    # No deployment target specified?
-    isEmpty(QMAKE_IPHONEOS_DEPLOYMENT_TARGET) {
-        # Use SDK version for iOS versions < preferred
-        lessThan(QMAKE_IOS_SDK_VERSION, $$QMAKE_IPHONEOS_PREFERRED_TARGET) {
-            QMAKE_IPHONEOS_DEPLOYMENT_TARGET = $$QMAKE_IOS_SDK_VERSION
-        } else: QMAKE_IPHONEOS_DEPLOYMENT_TARGET = $$QMAKE_IPHONEOS_PREFERRED_TARGET
-    }
-
-    # Make sure iOS SDK version is >= iOS target version
-    !lessThan(QMAKE_IPHONEOS_DEPLOYMENT_TARGET, $$QMAKE_IOS_SDK_VERSION) {
-        error("Target iOS version is greater that iOS SDK version $$QMAKE_IOS_SDK_VERSION! Edit mkspecs/common/ios/versions.conf to specify target iOS version.")
-    }
-# Building for iOS simulator
-} else {
-    # No iOS simulator SDK version specified?
-    isEmpty(QMAKE_IOS_SIMULATOR_SDK_VERSION) {
-        # Get version string from installed Xcode
-        !lessThan(QMAKE_IOS_XCODE_VERSION, "4.3") {
-            QMAKE_IOS_SDK_INFO = $$system(/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -showsdks)
-        } else: QMAKE_IOS_SDK_INFO = $$system(/Developer/usr/bin/xcodebuild -showsdks)
-
-        # Get names of installed device SDKs
-        QMAKE_IOS_SDK_INFO = $$find(QMAKE_IOS_SDK_INFO, ^iphonesimulator)
-        for(v, QMAKE_IOS_SDK_INFO): {
-            # Extract SDK version number from output
-            v = $$replace(v,iphonesimulator,)
-
-            # Use latest SDK version
-            greaterThan(v, $$QMAKE_IOS_SIMULATOR_SDK_VERSION): QMAKE_IOS_SIMULATOR_SDK_VERSION = $$v
-        }
-        QMAKE_IOS_SDK_INFO =
-    }
-
-    # Make sure iOS simulator SDK version is valid
-    !exists($$QMAKE_IOS_PLATFORM_PATH/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator$${QMAKE_IOS_SIMULATOR_SDK_VERSION}.sdk) {
-        error("iOS $$QMAKE_IOS_SIMULATOR_SDK_VERSION simulator SDK not found! Edit mkspecs/common/ios/versions.conf to specify version installed.")
-    }
-
-    # No deployment target specified?
-    isEmpty(QMAKE_IPHONEOS_DEPLOYMENT_TARGET) {
-        # Use SDK version for iOS versions < preferred
-        lessThan(QMAKE_IOS_SIMULATOR_SDK_VERSION, $$QMAKE_IPHONEOS_PREFERRED_TARGET) {
-            QMAKE_IPHONEOS_DEPLOYMENT_TARGET = $$QMAKE_IOS_SIMULATOR_SDK_VERSION
-        } else: QMAKE_IPHONEOS_DEPLOYMENT_TARGET = $$QMAKE_IPHONEOS_PREFERRED_TARGET
-    }
-
-    # Make sure iOS simulator SDK version is >= iOS target version
-    !lessThan(QMAKE_IPHONEOS_DEPLOYMENT_TARGET, $$QMAKE_IOS_SIMULATOR_SDK_VERSION) {
-        error("Target iOS version is greater that iOS simulator SDK version $$QMAKE_IOS_SIMULATOR_SDK_VERSION! Edit mkspecs/common/ios/versions.conf to specify target iOS version.")
-    }
-}
-
-QMAKE_IPHONEOS_PREFERRED_TARGET =
-QMAKE_IOS_PLATFORM_PATH =
-
-# Set deployment target
-QMAKE_IOS_VERSION_FLAGS = -miphoneos-version-min=$$QMAKE_IPHONEOS_DEPLOYMENT_TARGET
-
-# Set build flags
-QMAKE_CFLAGS           += $$QMAKE_IOS_VERSION_FLAGS
-QMAKE_CXXFLAGS         += $$QMAKE_IOS_VERSION_FLAGS
-QMAKE_OBJECTIVE_CFLAGS += $$QMAKE_IOS_VERSION_FLAGS
-QMAKE_LFLAGS           += $$QMAKE_IOS_VERSION_FLAGS
-QMAKE_IOS_VERSION_FLAGS =
diff --git a/mkspecs/mac/qplatformdefs.h b/mkspecs/mac/qplatformdefs.h
deleted file mode 100644 (file)
index 400e7c9..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMDEFS_H
-#define QPLATFORMDEFS_H
-
-// Get Qt defines/settings
-
-#include "qglobal.h"
-
-// Set any POSIX/XOPEN defines at the top of this file to turn on specific APIs
-
-#include <unistd.h>
-
-
-// We are hot - unistd.h should have turned on the specific APIs we requested
-
-
-#include <pthread.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <pwd.h>
-#include <signal.h>
-#define QT_NO_LIBRARY_UNLOAD
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/ipc.h>
-#include <sys/time.h>
-#include <sys/shm.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#ifndef QT_NO_IPV6IFNAME
-#include <net/if.h>
-#endif
-
-#include "common/mkspecs_posix.h"
-
-#undef QT_OPEN_LARGEFILE
-#undef QT_SOCKLEN_T
-#undef QT_SIGNAL_IGNORE
-
-#define QT_OPEN_LARGEFILE       0
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
-#define QT_SOCKLEN_T            socklen_t
-#else
-#define QT_SOCKLEN_T            int
-#endif
-
-#define QT_SIGNAL_IGNORE        (void (*)(int))1
-
-#define QT_SNPRINTF            ::snprintf
-#define QT_VSNPRINTF           ::vsnprintf
-
-#endif // QPLATFORMDEFS_H
diff --git a/mkspecs/maemo/TODO b/mkspecs/maemo/TODO
deleted file mode 100644 (file)
index 8d1c8b6..0000000
+++ /dev/null
@@ -1 +0,0 @@
diff --git a/mkspecs/qbase.pri b/mkspecs/qbase.pri
deleted file mode 100644 (file)
index ff5c70b..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-contains(QT_CONFIG, reduce_exports):CONFIG += hide_symbols
-unix:contains(QT_CONFIG, reduce_relocations):CONFIG += bsymbolic_functions
-
-mac {
-   CONFIG += explicitlib
-   macx-g++ {
-       QMAKE_CFLAGS += -fconstant-cfstrings
-       QMAKE_CXXFLAGS += -fconstant-cfstrings
-   }
-}
-
-win32-borland {
-    mng:QMAKE_CFLAGS_WARN_ON   += -w-par
-    mng:QMAKE_CXXFLAGS_WARN_ON += -w-par
-    # Keep the size of the .tds file for the Qt library smaller than
-    # 34 Mbytes to avoid linking problems
-    QMAKE_CFLAGS_DEBUG += -vi -y-
-    QMAKE_CXXFLAGS_DEBUG += -vi -y-
-}
-
-aix-g++* {
-     QMAKE_CFLAGS   += -mminimal-toc
-     QMAKE_CXXFLAGS += -mminimal-toc
-}
diff --git a/mkspecs/qnx/qmake.conf b/mkspecs/qnx/qmake.conf
deleted file mode 100644 (file)
index e9352df..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-#
-# qmake configuration common for qnx-g++ without X11
-#
-
-QT                     -= network
-
-QMAKE_COMPILER_DEFINES += __QNXNTO__
-
-# modifications to linux.conf and qws.conf
-QMAKE_LIBS             =
-QMAKE_LIBS_DYNLOAD     =
-QMAKE_LIBS_NIS         =
-QMAKE_LIBS_EGL         = -lEGL
-QMAKE_LIBS_OPENGL      = $$QMAKE_LIBS_EGL -lGLESv1_CM -lGLESv2
-QMAKE_LIBS_OPENGL_QT   = $$QMAKE_LIBS_OPENGL
-QMAKE_LIBS_OPENGL_ES1  = $$QMAKE_LIBS_EGL -lGLESv1_CM
-QMAKE_LIBS_OPENGL_ES2  = $$QMAKE_LIBS_EGL -lGLESv2
-QMAKE_LIBS_OPENVG      = $$QMAKE_LIBS_EGL -lOpenVG
-QMAKE_LIBS_THREAD      =
-
-QMAKE_LIBS_CORE        =
-QMAKE_LIBS_NETWORK     += -lsocket
-QMAKE_LIBS_GUI         += -lsocket
-
-# QNX doesn't have install
-QMAKE_INSTALL_FILE     =
-QMAKE_INSTALL_PROGRAM  =
-
-QMAKE_LFLAGS_SHLIB  += -shared
-QMAKE_LFLAGS_PLUGIN += $$QMAKE_LFLAGS_SHLIB
-QMAKE_LFLAGS_SONAME += -Wl,-soname,
-QMAKE_LFLAGS_THREAD +=
-QMAKE_LFLAGS_RPATH   = -Wl,-rpath,
-
-# -Bsymbolic-functions (ld) support
-QMAKE_LFLAGS_BSYMBOLIC_FUNC = -Wl,-Bsymbolic-functions
-QMAKE_LFLAGS_DYNAMIC_LIST   = -Wl,--dynamic-list,
-
-# Generic options for all BlackBerry/QNX qcc mkspecs
-QMAKE_CFLAGS_THREAD     = -D_REENTRANT
-QMAKE_CXXFLAGS_THREAD   = $$QMAKE_CFLAGS_THREAD
-QMAKE_COMPILER_DEFINES  += __QNXNTO__
-
-QMAKE_LIBS              = -lm
-QMAKE_LIBS_NETWORK      = -lsocket
-
-# OpenGL libraries have a dependency on libEGL
-QMAKE_LIBS_OPENGL_ES1   = -lGLES_CM -lEGL
-QMAKE_LIBS_OPENGL_ES2   = -lGLESv2 -lEGL
-
-QMAKE_INCDIR            = $${QNX_DIR}/usr/include $${QNX_DIR}/usr/include/freetype2
-QMAKE_LIBDIR            = $${QNX_DIR}/$${QNX_CPUDIR}/lib $${QNX_DIR}/$${QNX_CPUDIR}/usr/lib
-QMAKE_LFLAGS           += -Wl,-rpath-link,$${QNX_DIR}/$${QNX_CPUDIR}/lib -Wl,-rpath-link,$${QNX_DIR}/$${QNX_CPUDIR}/usr/lib
-
diff --git a/mkspecs/qnx/qplatformdefs.h b/mkspecs/qnx/qplatformdefs.h
deleted file mode 100644 (file)
index 14a4b0f..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMDEFS_H
-#define QPLATFORMDEFS_H
-
-// Get Qt defines/settings
-#include <qglobal.h>
-
-// Set any POSIX/XOPEN defines at the top of this file to turn on specific APIs
-
-#include <unistd.h>
-
-// We are hot - unistd.h should have turned on the specific APIs we requested
-
-#include <pthread.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <grp.h>
-#include <pwd.h>
-#include <signal.h>
-
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/ipc.h>
-#include <sys/time.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-#include <netinet/in.h>
-#ifndef QT_NO_IPV6IFNAME
-#include <net/if.h>
-#endif
-
-// for htonl
-#include <arpa/inet.h>
-
-#define QT_USE_XOPEN_LFS_EXTENSIONS
-#if !defined(__EXT_QNX__READDIR64_R)
-#define QT_NO_READDIR64
-#endif
-#include "common/mkspecs_posix.h"
-#if defined(__EXT_QNX__READDIR64_R)
-#define QT_EXT_QNX_READDIR_R    ::_readdir64_r
-#elif defined(__EXT_QNX__READDIR_R)
-#define QT_EXT_QNX_READDIR_R    ::_readdir_r
-#endif
-
-#include <stdlib.h>
-
-#define QT_SNPRINTF             ::snprintf
-#define QT_VSNPRINTF            ::vsnprintf
-
-
-#include <sys/neutrino.h>
-
-#if !defined(_NTO_VERSION) || _NTO_VERSION < 650
-// pre-6.5 versions of QNX doesn't have getpagesize()
-inline int getpagesize()
-{
-    return ::sysconf(_SC_PAGESIZE);
-}
-
-// pre-6.5 versions of QNX doesn't have strtof()
-inline float strtof(const char *b, char **e)
-{
-    return float(strtod(b, e));
-}
-#endif
-
-#define QT_QWS_TEMP_DIR QString::fromLocal8Bit(qgetenv("TMPDIR").constData())
-
-#endif // QPLATFORMDEFS_H
diff --git a/mkspecs/vxworks/TODO b/mkspecs/vxworks/TODO
deleted file mode 100644 (file)
index 8d1c8b6..0000000
+++ /dev/null
@@ -1 +0,0 @@
diff --git a/mkspecs/win32/qplatformdefs.h b/mkspecs/win32/qplatformdefs.h
deleted file mode 100644 (file)
index c82d0d8..0000000
+++ /dev/null
@@ -1,155 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMDEFS_H
-#define QPLATFORMDEFS_H
-
-#ifdef UNICODE
-#ifndef _UNICODE
-#define _UNICODE
-#endif
-#endif
-
-// Get Qt defines/settings
-
-#include "qglobal.h"
-#include "qt_windows.h"
-
-#define _POSIX_
-#include <limits.h>
-#undef _POSIX_
-
-#include <tchar.h>
-#include <io.h>
-#include <direct.h>
-#include <stdio.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <sys/stat.h>
-#include <stdlib.h>
-#include <windows.h>
-
-#define Q_FS_FAT
-#ifdef QT_LARGEFILE_SUPPORT
-#define QT_STATBUF             struct _stati64         // non-ANSI defs
-#define QT_STATBUF4TSTAT       struct _stati64         // non-ANSI defs
-#define QT_STAT                        ::_stati64
-#define QT_FSTAT               ::_fstati64
-#else
-#define QT_STATBUF             struct _stat            // non-ANSI defs
-#define QT_STATBUF4TSTAT       struct _stat            // non-ANSI defs
-#define QT_STAT                        ::_stat
-#define QT_FSTAT               ::_fstat
-#endif
-#define QT_STAT_REG            _S_IFREG
-#define QT_STAT_DIR            _S_IFDIR
-#define QT_STAT_MASK           _S_IFMT
-#if defined(_S_IFLNK)
-#  define QT_STAT_LNK          _S_IFLNK
-#endif
-#define QT_FILENO              _fileno
-#define QT_OPEN                        ::_open
-#define QT_CLOSE               ::_close
-#ifdef QT_LARGEFILE_SUPPORT
-#define QT_LSEEK               ::_lseeki64
-#define QT_TSTAT               ::_tstati64
-#else
-#define QT_LSEEK               ::_lseek
-#define QT_TSTAT               ::_tstat
-#endif
-#define QT_READ                        ::_read
-#define QT_WRITE               ::_write
-#define QT_ACCESS              ::_access
-#define QT_GETCWD              ::_getcwd
-#define QT_CHDIR               ::_chdir
-#define QT_MKDIR               ::_mkdir
-#define QT_RMDIR               ::_rmdir
-#define QT_OPEN_LARGEFILE       0
-#define QT_OPEN_RDONLY         _O_RDONLY
-#define QT_OPEN_WRONLY         _O_WRONLY
-#define QT_OPEN_RDWR           _O_RDWR
-#define QT_OPEN_CREAT          _O_CREAT
-#define QT_OPEN_TRUNC          _O_TRUNC
-#define QT_OPEN_APPEND         _O_APPEND
-#if defined(O_TEXT)
-# define QT_OPEN_TEXT          _O_TEXT
-# define QT_OPEN_BINARY                _O_BINARY
-#endif
-
-#include "common/mkspecs_c89.h"
-
-#ifdef QT_LARGEFILE_SUPPORT
-#undef QT_FSEEK
-#undef QT_FTELL
-#undef QT_OFF_T
-
-#ifdef __MINGW32__
-#define QT_FSEEK                ::fseeko64
-#define QT_FTELL                ::ftello64
-#define QT_OFF_T                off64_t
-#else
-#define QT_FSEEK                ::_fseeki64
-#define QT_FTELL                ::_ftelli64
-#define QT_OFF_T                __int64
-#endif
-#endif
-
-#define QT_SIGNAL_ARGS         int
-
-#ifdef __MINGW32__
-#define QT_VSNPRINTF           ::_vsnprintf
-#else
-#define QT_VSNPRINTF(buffer, count, format, arg) \
-    vsnprintf_s(buffer, count, count-1, format, arg)
-#endif
-#define QT_SNPRINTF            ::_snprintf
-
-
-#define F_OK   0
-#define X_OK   1
-#define W_OK   2
-#define R_OK   4
-
-#ifndef __MINGW32__
-typedef int mode_t;
-#endif
-
-#endif // QPLATFORMDEFS_H
diff --git a/mkspecs/wince/qmake.conf b/mkspecs/wince/qmake.conf
deleted file mode 100644 (file)
index b795daf..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-#
-# qmake configuration for common Windows CE
-#
-
-MAKEFILE_GENERATOR = MSVC.NET
-TEMPLATE = app
-QT            += core gui
-CONFIG += qt warn_on release incremental flat link_prl precompile_header autogen_precompile_source copy_dir_files debug_and_release debug_and_release_target embed_manifest_dll embed_manifest_exe
-
-DEFINES    += UNDER_CE WINCE _WINDOWS _UNICODE UNICODE _WIN32 QT_NO_PRINTER QT_NO_PRINTDIALOG
-
-QMAKE_COMPILER_DEFINES  += _MSC_VER=1400
-
-QMAKE_CC               = cl
-QMAKE_LEX              = flex
-QMAKE_LEXFLAGS         =
-QMAKE_YACC             = byacc
-QMAKE_YACCFLAGS                = -d
-QMAKE_CFLAGS           = -nologo -Zm200 -Zc:wchar_t-
-QMAKE_CFLAGS_WARN_ON   = -W3
-QMAKE_CFLAGS_WARN_OFF  = -W0
-QMAKE_CFLAGS_RELEASE    = -O2 -MD
-QMAKE_CFLAGS_LTCG       = -GL
-QMAKE_CFLAGS_DEBUG     = -DDEBUG -D_DEBUG -Zi -MDd
-QMAKE_CFLAGS_YACC      =
-
-# Uncomment the following lines to reduce library sizes
-# with potential cost of performance
-# QMAKE_CFLAGS += -Os
-# QMAKE_CFLAGS_RELEASE += -Os
-
-QMAKE_CXX              = $$QMAKE_CC
-QMAKE_CXXFLAGS         = $$QMAKE_CFLAGS
-QMAKE_CXXFLAGS_WARN_ON = $$QMAKE_CFLAGS_WARN_ON -w34100 -w34189
-QMAKE_CXXFLAGS_WARN_OFF        = $$QMAKE_CFLAGS_WARN_OFF
-QMAKE_CXXFLAGS_RELEASE = $$QMAKE_CFLAGS_RELEASE
-QMAKE_CXXFLAGS_DEBUG   = $$QMAKE_CFLAGS_DEBUG
-QMAKE_CXXFLAGS_LTCG     = $$QMAKE_CFLAGS_LTCG
-QMAKE_CXXFLAGS_YACC    = $$QMAKE_CFLAGS_YACC
-QMAKE_CXXFLAGS_STL_ON  = -EHsc
-QMAKE_CXXFLAGS_STL_OFF =
-QMAKE_CXXFLAGS_RTTI_ON = -GR
-QMAKE_CXXFLAGS_RTTI_OFF        =
-QMAKE_CXXFLAGS_EXCEPTIONS_ON = -EHsc
-QMAKE_CXXFLAGS_EXCEPTIONS_OFF = -EHs-c-
-
-QMAKE_INCDIR           =
-QMAKE_INCDIR_QT                = $$[QT_INSTALL_HEADERS]
-QMAKE_LIBDIR_QT                = $$[QT_INSTALL_LIBS]
-
-QMAKE_RUN_CC           = $(CC) -c $(CFLAGS) $(INCPATH) -Fo$obj $src
-QMAKE_RUN_CC_IMP       = $(CC) -c $(CFLAGS) $(INCPATH) -Fo$@ $<
-QMAKE_RUN_CC_IMP_BATCH = $(CC) -c $(CFLAGS) $(INCPATH) -Fo$@ @<<
-QMAKE_RUN_CXX          = $(CXX) -c $(CXXFLAGS) $(INCPATH) -Fo$obj $src
-QMAKE_RUN_CXX_IMP      = $(CXX) -c $(CXXFLAGS) $(INCPATH) -Fo$@ $<
-QMAKE_RUN_CXX_IMP_BATCH        = $(CXX) -c $(CXXFLAGS) $(INCPATH) -Fo$@ @<<
-
-QMAKE_LINK             = link
-QMAKE_LFLAGS           = /NOLOGO /NODEFAULTLIB:OLDNAMES.LIB
-QMAKE_LFLAGS_RELEASE    = /INCREMENTAL:NO
-QMAKE_LFLAGS_DEBUG     = /DEBUG
-QMAKE_LFLAGS_LTCG       = /LTCG
-QMAKE_LIBS_NETWORK      = ws2.lib
-QMAKE_LIBS_OPENGL       = 
-QMAKE_LIBS_COMPAT       = 
-
-QMAKE_LIBS_EGL          = libEGL.lib
-QMAKE_LIBS_OPENGL_ES1 = libGLES_CM.lib
-QMAKE_LIBS_OPENGL_ES2 = libGLESv2.lib
-
-QMAKE_LIBS_QT_ENTRY    = -lqtmain
-
diff --git a/mkspecs/wince/qplatformdefs.h b/mkspecs/wince/qplatformdefs.h
deleted file mode 100644 (file)
index f9de8ef..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the qmake spec 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMDEFS_H
-#define QPLATFORMDEFS_H
-
-#ifdef UNICODE
-#ifndef _UNICODE
-#define _UNICODE
-#endif
-#endif
-
-// Get Qt defines/settings
-
-#include "qglobal.h"
-#include "qfunctions_wince.h"
-
-#define _POSIX_
-#include <limits.h>
-#undef _POSIX_
-
-#include <tchar.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <windows.h>
-
-#define Q_FS_FAT
-#ifdef QT_LARGEFILE_SUPPORT
-#define QT_STATBUF             struct _stati64         // non-ANSI defs
-#define QT_STATBUF4TSTAT       struct _stati64         // non-ANSI defs
-#define QT_STAT                        ::_stati64
-#define QT_FSTAT               ::_fstati64
-#else
-#define QT_STATBUF             struct stat             // non-ANSI defs
-#define QT_STATBUF4TSTAT       struct stat             // non-ANSI defs
-#define QT_STAT                        ::qt_wince_stat
-#define QT_FSTAT               ::qt_wince__fstat
-#endif
-#define QT_STAT_REG            _S_IFREG
-#define QT_STAT_DIR            _S_IFDIR
-#define QT_STAT_MASK           _S_IFMT
-#if defined(_S_IFLNK)
-#  define QT_STAT_LNK          _S_IFLNK
-#endif
-#define QT_FILENO              ::qt_wince___fileno
-#define QT_OPEN                        ::qt_wince_open
-#define QT_CLOSE               ::qt_wince__close
-#ifdef QT_LARGEFILE_SUPPORT
-#define QT_LSEEK               ::_lseeki64
-#define QT_TSTAT               ::_tstati64
-#else
-#define QT_LSEEK               ::qt_wince__lseek
-#define QT_TSTAT               ::_tstat
-#endif
-#define QT_READ                        ::qt_wince__read
-#define QT_WRITE               ::qt_wince__write
-#define QT_ACCESS              ::qt_wince__access
-#define QT_GETCWD              ::_getcwd
-#define QT_CHDIR               ::_chdir
-#define QT_MKDIR               ::qt_wince__mkdir
-#define QT_RMDIR               ::qt_wince__rmdir
-#define QT_OPEN_LARGEFILE      0
-#define QT_OPEN_RDONLY         _O_RDONLY
-#define QT_OPEN_WRONLY         _O_WRONLY
-#define QT_OPEN_RDWR           _O_RDWR
-#define QT_OPEN_CREAT          _O_CREAT
-#define QT_OPEN_TRUNC          _O_TRUNC
-#define QT_OPEN_APPEND         _O_APPEND
-# define QT_OPEN_TEXT          _O_TEXT
-# define QT_OPEN_BINARY                _O_BINARY
-
-#define QT_FOPEN                ::fopen
-#define QT_FSEEK                ::fseek
-#define QT_FTELL                ::ftell
-#define QT_FGETPOS              ::fgetpos
-#define QT_FSETPOS              ::fsetpos
-#define QT_MMAP                 ::mmap
-#define QT_FPOS_T               fpos_t
-#define QT_OFF_T                long
-
-#define QT_SIGNAL_ARGS         int
-
-#define QT_VSNPRINTF(buffer, count, format, arg) \
-    _vsnprintf(buffer, count, format, arg)
-
-#define QT_SNPRINTF            ::_snprintf
-
-# define F_OK  0
-# define X_OK  1
-# define W_OK  2
-# define R_OK  4
-
-typedef int mode_t;
-
-#endif // QPLATFORMDEFS_H
diff --git a/src/3rdparty/ce-compat/ce_time.c b/src/3rdparty/ce-compat/ce_time.c
deleted file mode 100644 (file)
index 92efae0..0000000
+++ /dev/null
@@ -1,677 +0,0 @@
-//
-// strftime.c
-//
-// Date to string conversion
-//
-// Copyright (C) 2002 Michael Ringgaard. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions
-// are met:
-//
-// 1. Redistributions of source code must retain the above copyright
-//    notice, this list of conditions and the following disclaimer.
-// 2. Redistributions in binary form must reproduce the above copyright
-//    notice, this list of conditions and the following disclaimer in the
-//    documentation and/or other materials provided with the distribution.
-// 3. Neither the name of the project nor the names of its contributors
-//    may be used to endorse or promote products derived from this software
-//    without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
-// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-// SUCH DAMAGE.
-//
-
-/////////////////////////////////////////////////////////////////////////////////////////////
-//                                                                                         //
-//                                         time()                                          //
-//                                                                                         //
-/////////////////////////////////////////////////////////////////////////////////////////////
-
-
-#include <windows.h>
-#include <time.h>
-#include "ce_time.h"
-
-time_t
-time(time_t* timer)
-{
-       SYSTEMTIME systime;
-       struct tm tmtime;
-       time_t tt;
-
-       GetLocalTime(&systime);
-
-       tmtime.tm_year = systime.wYear-1900;
-       tmtime.tm_mon = systime.wMonth-1;
-       tmtime.tm_mday = systime.wDay;
-       tmtime.tm_wday = systime.wDayOfWeek;
-       tmtime.tm_hour = systime.wHour;
-       tmtime.tm_min = systime.wMinute;
-       tmtime.tm_sec = systime.wSecond;
-
-       tt = mktime(&tmtime);
-
-       if(timer)
-               *timer = tt;
-
-       return tt;
-}
-
-
-/////////////////////////////////////////////////////////////////////////////////////////////
-//                                                                                         //
-//                                        mktime()                                         //
-//                                                                                         //
-/////////////////////////////////////////////////////////////////////////////////////////////
-
-static int month_to_day[12] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
-
-time_t mktime(struct tm *t)
-{
-        short  month, year;
-        time_t result;
-
-        month = t->tm_mon;
-        year = t->tm_year + month / 12 + 1900;
-        month %= 12;
-        if (month < 0)
-        {
-                year -= 1;
-                month += 12;
-        }
-        result = (year - 1970) * 365 + (year - 1969) / 4 + month_to_day[month];
-        result = (year - 1970) * 365 + month_to_day[month];
-        if (month <= 1)
-                year -= 1;
-        result += (year - 1968) / 4;
-        result -= (year - 1900) / 100;
-        result += (year - 1600) / 400;
-        result += t->tm_mday;
-        result -= 1;
-        result *= 24;
-        result += t->tm_hour;
-        result *= 60;
-        result += t->tm_min;
-        result *= 60;
-        result += t->tm_sec;
-        return(result);
-}
-
-
-/////////////////////////////////////////////////////////////////////////////////////////////
-//                                                                                         //
-//                             strftime() - taken from OpenBSD                             //
-//                                                                                         //
-/////////////////////////////////////////////////////////////////////////////////////////////
-
-#define IN_NONE        0
-#define IN_SOME        1
-#define IN_THIS        2
-#define IN_ALL 3
-#define CHAR_BIT      8
-
-#define TYPE_BIT(type) (sizeof (type) * CHAR_BIT)
-#define TYPE_SIGNED(type) (((type) -1) < 0)
-
-#define INT_STRLEN_MAXIMUM(type) \
-    ((TYPE_BIT(type) - TYPE_SIGNED(type)) * 302 / 1000 + 1 + TYPE_SIGNED(type))
-
-#define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0))
-
-#define MONSPERYEAR    12
-#define DAYSPERWEEK    7
-#define TM_YEAR_BASE   1900
-#define HOURSPERDAY    24
-#define DAYSPERNYEAR   365
-#define DAYSPERLYEAR   366
-
-static char            wildabbr[] = "WILDABBR";
-
-static char *                  tzname[2] = {
-       wildabbr,
-       wildabbr
-};
-
-
-#define Locale (&C_time_locale)
-
-struct lc_time_T {
-       const char *    mon[MONSPERYEAR];
-       const char *    month[MONSPERYEAR];
-       const char *    wday[DAYSPERWEEK];
-       const char *    weekday[DAYSPERWEEK];
-       const char *    X_fmt;
-       const char *    x_fmt;
-       const char *    c_fmt;
-       const char *    am;
-       const char *    pm;
-       const char *    date_fmt;
-};
-
-static const struct lc_time_T  C_time_locale = {
-       {
-               "Jan", "Feb", "Mar", "Apr", "May", "Jun",
-               "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-       }, {
-               "January", "February", "March", "April", "May", "June",
-               "July", "August", "September", "October", "November", "December"
-       }, {
-               "Sun", "Mon", "Tue", "Wed",
-               "Thu", "Fri", "Sat"
-       }, {
-               "Sunday", "Monday", "Tuesday", "Wednesday",
-               "Thursday", "Friday", "Saturday"
-       },
-
-       /* X_fmt */
-       "%H:%M:%S",
-
-       /*
-       ** x_fmt
-       ** C99 requires this format.
-       ** Using just numbers (as here) makes Quakers happier;
-       ** it's also compatible with SVR4.
-       */
-       "%m/%d/%y",
-
-       /*
-       ** c_fmt
-       ** C99 requires this format.
-       ** Previously this code used "%D %X", but we now conform to C99.
-       ** Note that
-       **      "%a %b %d %H:%M:%S %Y"
-       ** is used by Solaris 2.3.
-       */
-       "%a %b %e %T %Y",
-
-       /* am */
-       "AM",
-
-       /* pm */
-       "PM",
-
-       /* date_fmt */
-       "%a %b %e %H:%M:%S %Z %Y"
-};
-
-
-static char *
-_add(const char * str, char * pt, const char * const ptlim)
-{
-       while (pt < ptlim && (*pt = *str++) != '\0')
-               ++pt;
-       return pt;
-}
-
-
-static char *
-_conv(const int n, const char * const format, char * const pt, const char * const ptlim)
-{
-       char    buf[INT_STRLEN_MAXIMUM(int) + 1];
-
-       (void) _snprintf(buf, sizeof buf, format, n);
-       return _add(buf, pt, ptlim);
-}
-
-
-static char *
-_fmt(const char * format, const struct tm * const t, char * pt, const char * const ptlim, int * warnp)
-{
-       for ( ; *format; ++format) {
-               if (*format == '%') {
-label:
-                       switch (*++format) {
-                       case '\0':
-                               --format;
-                               break;
-                       case 'A':
-                               pt = _add((t->tm_wday < 0 ||
-                                       t->tm_wday >= DAYSPERWEEK) ?
-                                       "?" : Locale->weekday[t->tm_wday],
-                                       pt, ptlim);
-                               continue;
-                       case 'a':
-                               pt = _add((t->tm_wday < 0 ||
-                                       t->tm_wday >= DAYSPERWEEK) ?
-                                       "?" : Locale->wday[t->tm_wday],
-                                       pt, ptlim);
-                               continue;
-                       case 'B':
-                               pt = _add((t->tm_mon < 0 ||
-                                       t->tm_mon >= MONSPERYEAR) ?
-                                       "?" : Locale->month[t->tm_mon],
-                                       pt, ptlim);
-                               continue;
-                       case 'b':
-                       case 'h':
-                               pt = _add((t->tm_mon < 0 ||
-                                       t->tm_mon >= MONSPERYEAR) ?
-                                       "?" : Locale->mon[t->tm_mon],
-                                       pt, ptlim);
-                               continue;
-                       case 'C':
-                               /*
-                               ** %C used to do a...
-                               **      _fmt("%a %b %e %X %Y", t);
-                               ** ...whereas now POSIX 1003.2 calls for
-                               ** something completely different.
-                               ** (ado, 1993-05-24)
-                               */
-                               pt = _conv((t->tm_year + TM_YEAR_BASE) / 100,
-                                       "%02d", pt, ptlim);
-                               continue;
-                       case 'c':
-                               {
-                               int warn2 = IN_SOME;
-
-                               pt = _fmt(Locale->c_fmt, t, pt, ptlim, warnp);
-                               if (warn2 == IN_ALL)
-                                       warn2 = IN_THIS;
-                               if (warn2 > *warnp)
-                                       *warnp = warn2;
-                               }
-                               continue;
-                       case 'D':
-                               pt = _fmt("%m/%d/%y", t, pt, ptlim, warnp);
-                               continue;
-                       case 'd':
-                               pt = _conv(t->tm_mday, "%02d", pt, ptlim);
-                               continue;
-                       case 'E':
-                       case 'O':
-                               /*
-                               ** C99 locale modifiers.
-                               ** The sequences
-                               **      %Ec %EC %Ex %EX %Ey %EY
-                               **      %Od %oe %OH %OI %Om %OM
-                               **      %OS %Ou %OU %OV %Ow %OW %Oy
-                               ** are supposed to provide alternate
-                               ** representations.
-                               */
-                               goto label;
-                       case 'e':
-                               pt = _conv(t->tm_mday, "%2d", pt, ptlim);
-                               continue;
-                       case 'F':
-                               pt = _fmt("%Y-%m-%d", t, pt, ptlim, warnp);
-                               continue;
-                       case 'H':
-                               pt = _conv(t->tm_hour, "%02d", pt, ptlim);
-                               continue;
-                       case 'I':
-                               pt = _conv((t->tm_hour % 12) ?
-                                       (t->tm_hour % 12) : 12,
-                                       "%02d", pt, ptlim);
-                               continue;
-                       case 'j':
-                               pt = _conv(t->tm_yday + 1, "%03d", pt, ptlim);
-                               continue;
-                       case 'k':
-                               /*
-                               ** This used to be...
-                               **      _conv(t->tm_hour % 12 ?
-                               **              t->tm_hour % 12 : 12, 2, ' ');
-                               ** ...and has been changed to the below to
-                               ** match SunOS 4.1.1 and Arnold Robbins'
-                               ** strftime version 3.0.  That is, "%k" and
-                               ** "%l" have been swapped.
-                               ** (ado, 1993-05-24)
-                               */
-                               pt = _conv(t->tm_hour, "%2d", pt, ptlim);
-                               continue;
-#ifdef KITCHEN_SINK
-                       case 'K':
-                               /*
-                               ** After all this time, still unclaimed!
-                               */
-                               pt = _add("kitchen sink", pt, ptlim);
-                               continue;
-#endif /* defined KITCHEN_SINK */
-                       case 'l':
-                               /*
-                               ** This used to be...
-                               **      _conv(t->tm_hour, 2, ' ');
-                               ** ...and has been changed to the below to
-                               ** match SunOS 4.1.1 and Arnold Robbin's
-                               ** strftime version 3.0.  That is, "%k" and
-                               ** "%l" have been swapped.
-                               ** (ado, 1993-05-24)
-                               */
-                               pt = _conv((t->tm_hour % 12) ?
-                                       (t->tm_hour % 12) : 12,
-                                       "%2d", pt, ptlim);
-                               continue;
-                       case 'M':
-                               pt = _conv(t->tm_min, "%02d", pt, ptlim);
-                               continue;
-                       case 'm':
-                               pt = _conv(t->tm_mon + 1, "%02d", pt, ptlim);
-                               continue;
-                       case 'n':
-                               pt = _add("\n", pt, ptlim);
-                               continue;
-                       case 'p':
-                               pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
-                                       Locale->pm :
-                                       Locale->am,
-                                       pt, ptlim);
-                               continue;
-                       case 'R':
-                               pt = _fmt("%H:%M", t, pt, ptlim, warnp);
-                               continue;
-                       case 'r':
-                               pt = _fmt("%I:%M:%S %p", t, pt, ptlim, warnp);
-                               continue;
-                       case 'S':
-                               pt = _conv(t->tm_sec, "%02d", pt, ptlim);
-                               continue;
-                       case 's':
-                               {
-                                       struct tm       tm;
-                                       char            buf[INT_STRLEN_MAXIMUM(
-                                                               time_t) + 1];
-                                       time_t          mkt;
-
-                                       tm = *t;
-                                       mkt = mktime(&tm);
-                                       if (TYPE_SIGNED(time_t))
-                                               (void) _snprintf(buf, sizeof buf,
-                                                   "%ld", (long) mkt);
-                                       else    (void) _snprintf(buf, sizeof buf,
-                                                   "%lu", (unsigned long) mkt);
-                                       pt = _add(buf, pt, ptlim);
-                               }
-                               continue;
-                       case 'T':
-                               pt = _fmt("%H:%M:%S", t, pt, ptlim, warnp);
-                               continue;
-                       case 't':
-                               pt = _add("\t", pt, ptlim);
-                               continue;
-                       case 'U':
-                               pt = _conv((t->tm_yday + DAYSPERWEEK -
-                                       t->tm_wday) / DAYSPERWEEK,
-                                       "%02d", pt, ptlim);
-                               continue;
-                       case 'u':
-                               /*
-                               ** From Arnold Robbins' strftime version 3.0:
-                               ** "ISO 8601: Weekday as a decimal number
-                               ** [1 (Monday) - 7]"
-                               ** (ado, 1993-05-24)
-                               */
-                               pt = _conv((t->tm_wday == 0) ?
-                                       DAYSPERWEEK : t->tm_wday,
-                                       "%d", pt, ptlim);
-                               continue;
-                       case 'V':       /* ISO 8601 week number */
-                       case 'G':       /* ISO 8601 year (four digits) */
-                       case 'g':       /* ISO 8601 year (two digits) */
-                               {
-                                       int     year;
-                                       int     yday;
-                                       int     wday;
-                                       int     w;
-
-                                       year = t->tm_year + TM_YEAR_BASE;
-                                       yday = t->tm_yday;
-                                       wday = t->tm_wday;
-                                       for ( ; ; ) {
-                                               int     len;
-                                               int     bot;
-                                               int     top;
-
-                                               len = isleap(year) ?
-                                                       DAYSPERLYEAR :
-                                                       DAYSPERNYEAR;
-                                               /*
-                                               ** What yday (-3 ... 3) does
-                                               ** the ISO year begin on?
-                                               */
-                                               bot = ((yday + 11 - wday) %
-                                                       DAYSPERWEEK) - 3;
-                                               /*
-                                               ** What yday does the NEXT
-                                               ** ISO year begin on?
-                                               */
-                                               top = bot -
-                                                       (len % DAYSPERWEEK);
-                                               if (top < -3)
-                                                       top += DAYSPERWEEK;
-                                               top += len;
-                                               if (yday >= top) {
-                                                       ++year;
-                                                       w = 1;
-                                                       break;
-                                               }
-                                               if (yday >= bot) {
-                                                       w = 1 + ((yday - bot) /
-                                                               DAYSPERWEEK);
-                                                       break;
-                                               }
-                                               --year;
-                                               yday += isleap(year) ?
-                                                       DAYSPERLYEAR :
-                                                       DAYSPERNYEAR;
-                                       }
-                                       if (*format == 'V')
-                                               pt = _conv(w, "%02d",
-                                                       pt, ptlim);
-                                       else if (*format == 'g') {
-                                               *warnp = IN_ALL;
-                                               pt = _conv(year % 100, "%02d",
-                                                       pt, ptlim);
-                                       } else  pt = _conv(year, "%04d",
-                                                       pt, ptlim);
-                               }
-                               continue;
-                       case 'v':
-                               pt = _fmt("%e-%b-%Y", t, pt, ptlim, warnp);
-                               continue;
-                       case 'W':
-                               pt = _conv((t->tm_yday + DAYSPERWEEK -
-                                       (t->tm_wday ?
-                                       (t->tm_wday - 1) :
-                                       (DAYSPERWEEK - 1))) / DAYSPERWEEK,
-                                       "%02d", pt, ptlim);
-                               continue;
-                       case 'w':
-                               pt = _conv(t->tm_wday, "%d", pt, ptlim);
-                               continue;
-                       case 'X':
-                               pt = _fmt(Locale->X_fmt, t, pt, ptlim, warnp);
-                               continue;
-                       case 'x':
-                               {
-                               int     warn2 = IN_SOME;
-
-                               pt = _fmt(Locale->x_fmt, t, pt, ptlim, &warn2);
-                               if (warn2 == IN_ALL)
-                                       warn2 = IN_THIS;
-                               if (warn2 > *warnp)
-                                       *warnp = warn2;
-                               }
-                               continue;
-                       case 'y':
-                               *warnp = IN_ALL;
-                               pt = _conv((t->tm_year + TM_YEAR_BASE) % 100,
-                                       "%02d", pt, ptlim);
-                               continue;
-                       case 'Y':
-                               pt = _conv(t->tm_year + TM_YEAR_BASE, "%04d",
-                                       pt, ptlim);
-                               continue;
-                       case 'Z':
-                               if (t->tm_isdst >= 0)
-                                       pt = _add(tzname[t->tm_isdst != 0],
-                                               pt, ptlim);
-                               /*
-                               ** C99 says that %Z must be replaced by the
-                               ** empty string if the time zone is not
-                               ** determinable.
-                               */
-                               continue;
-                       case 'z':
-                               {
-                               int             diff;
-                               char const *    sign;
-
-                               if (t->tm_isdst < 0)
-                                       continue;
-                               continue;
-                               if (diff < 0) {
-                                       sign = "-";
-                                       diff = -diff;
-                               } else  sign = "+";
-                               pt = _add(sign, pt, ptlim);
-                               diff /= 60;
-                               pt = _conv((diff/60)*100 + diff%60,
-                                       "%04d", pt, ptlim);
-                               }
-                               continue;
-                       case '+':
-                               pt = _fmt(Locale->date_fmt, t, pt, ptlim,
-                                       warnp);
-                               continue;
-                       case '%':
-                       default:
-                               break;
-                       }
-               }
-               if (pt == ptlim)
-                       break;
-               *pt++ = *format;
-       }
-       return pt;
-}
-
-
-size_t
-strftime(char * const s, const size_t maxsize, const char * const format, const struct tm * const t)
-{
-       char *  p;
-       int     warn;
-
-       //tzset();
-
-       warn = IN_NONE;
-       p = _fmt(((format == NULL) ? "%c" : format), t, s, s + maxsize, &warn);
-
-       if (p == s + maxsize) {
-               if (maxsize > 0)
-                       s[maxsize - 1] = '\0';
-               return 0;
-       }
-       *p = '\0';
-       return p - s;
-}
-
-
-
-/////////////////////////////////////////////////////////////////////////////////////////////
-//                                                                                         //
-//                                      gmtime()                                           //
-//                                                                                         //
-/////////////////////////////////////////////////////////////////////////////////////////////
-
-
-
-static struct tm mytm;
-
-static int DMonth[13] = { 0,31,59,90,120,151,181,212,243,273,304,334,365 };
-static int monthCodes[12] = { 6, 2, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
-
-
-static int
-calcDayOfWeek(const struct tm* nTM)
-{
-       int day;
-
-       day = (nTM->tm_year%100);
-       day += day/4;
-       day += monthCodes[nTM->tm_mon];
-       day += nTM->tm_mday;
-       while(day>=7)
-               day -= 7;
-
-       return day;
-}
-
-
-static struct tm *
-gmtime(const time_t *timer)
-{
-       unsigned long x = *timer;
-       int imin, ihrs, iday, iyrs;
-       int sec, min, hrs, day, mon, yrs;
-       int lday, qday, jday, mday;
-
-
-       imin = x / 60;                                                  // whole minutes since 1/1/70
-       sec = x - (60 * imin);                                  // leftover seconds
-       ihrs = imin / 60;                                               // whole hours since 1/1/70
-       min = imin - 60 * ihrs;                                 // leftover minutes
-       iday = ihrs / 24;                                               // whole days since 1/1/70
-       hrs = ihrs - 24 * iday;                                 // leftover hours
-       iday = iday + 365 + 366;                                // whole days since 1/1/68
-       lday = iday / (( 4* 365) + 1);                  // quadyr = 4 yr period = 1461 days
-       qday = iday % (( 4 * 365) + 1);                 // days since current quadyr began
-       if(qday >= (31 + 29))                                   // if past feb 29 then
-               lday = lday + 1;                                        // add this quadyr\92s leap day to the
-                                                                                       // # of quadyrs (leap days) since 68
-       iyrs = (iday - lday) / 365;                             // whole years since 1968
-       jday = iday - (iyrs * 365) - lday;              // days since 1 /1 of current year.
-       if(qday <= 365 && qday >= 60)                   // if past 2/29 and a leap year then
-               jday = jday + 1;                                        // add a leap day to the # of whole
-                                                                                       // days since 1/1 of current year
-       yrs = iyrs + 1968;                                              // compute year
-       mon = 13;                                                               // estimate month ( +1)
-       mday = 366;                                                             // max days since 1/1 is 365
-       while(jday < mday)                                              // mday = # of days passed from 1/1
-       {                                                                               // until first day of current month
-               mon = mon - 1;                                          // mon = month (estimated)
-               mday = DMonth[mon];                                     // # elapsed days at first of \94mon\94
-               if((mon > 2) && (yrs % 4) == 0)         // if past 2/29 and leap year then
-                       mday = mday + 1;                                // add leap day
-                                                                                       // compute month by decrementing
-       }                                                                               // month until found
-
-       day = jday - mday + 1;                                  // compute day of month
-
-       mytm.tm_sec = sec;
-       mytm.tm_min = min;
-       mytm.tm_hour = hrs;
-       mytm.tm_mday = day;
-       mytm.tm_mon = mon;
-       mytm.tm_year = yrs - 1900;
-
-       mytm.tm_wday = calcDayOfWeek(&mytm);
-       mytm.tm_yday = jday;
-       mytm.tm_isdst = 0;
-
-       return &mytm;
-}
-
-
-/////////////////////////////////////////////////////////////////////////////////////////////
-//                                                                                         //
-//                            localtime() - simply using gmtime()                          //
-//                                                                                         //
-/////////////////////////////////////////////////////////////////////////////////////////////
-
-
-struct tm *
-localtime(const time_t *timer)
-{
-       return gmtime(timer);
-}
diff --git a/src/3rdparty/ce-compat/ce_time.h b/src/3rdparty/ce-compat/ce_time.h
deleted file mode 100644 (file)
index 07ca094..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-#ifndef __CE_TIME_H__
-#define __CE_TIME_H__
-
-#if defined(_WIN32_WCE) && _WIN32_WCE >= 0x600
-/* we need to prototype the time functions for Windows CE >= 6.0 */
-#include <crtdefs.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-struct tm;
-
-time_t time(time_t* timer);
-time_t mktime(struct tm *t);
-size_t strftime(char * const s, const size_t maxsize, const char * const format, const struct tm * const t);
-struct tm *localtime(const time_t *timer);
-
-#ifdef __cplusplus
-}   /* closing brace for extern "C" */
-#endif
-
-#endif /* defined(_WIN32_WCE) && _WIN32_WCE >= 0x600 */
-
-#endif /* !defined(__CE_TIME_H__) */
diff --git a/src/3rdparty/javascriptcore/JavaScriptCore/os-win32/stdint.h b/src/3rdparty/javascriptcore/JavaScriptCore/os-win32/stdint.h
deleted file mode 100644 (file)
index b5dff56..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2005, 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef STDINT_WIN32_H
-#define STDINT_WIN32_H
-
-#include <wtf/Platform.h>
-
-/* This file emulates enough of stdint.h on Windows to make JavaScriptCore and WebCore
-   compile using MSVC which does not ship with the stdint.h header. */
-
-#if !COMPILER(MSVC)
-#error "This stdint.h file should only be compiled with MSVC"
-#endif
-
-#include <limits.h>
-
-typedef unsigned char uint8_t;
-typedef signed char int8_t;
-typedef unsigned short uint16_t;
-typedef short int16_t;
-typedef unsigned int uint32_t;
-typedef int int32_t;
-typedef __int64 int64_t;
-typedef unsigned __int64 uint64_t;
-
-#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS)
-#ifndef SIZE_MAX
-#ifdef _WIN64
-#define SIZE_MAX  _UI64_MAX
-#else
-#define SIZE_MAX  _UI32_MAX
-#endif
-#endif
-#endif
-
-#ifndef CASSERT
-#define CASSERT(exp, name) typedef int dummy##name [(exp) ? 1 : -1];
-#endif
-
-CASSERT(sizeof(int8_t) == 1, int8_t_is_one_byte)
-CASSERT(sizeof(uint8_t) == 1, uint8_t_is_one_byte)
-CASSERT(sizeof(int16_t) == 2, int16_t_is_two_bytes)
-CASSERT(sizeof(uint16_t) == 2, uint16_t_is_two_bytes)
-CASSERT(sizeof(int32_t) == 4, int32_t_is_four_bytes)
-CASSERT(sizeof(uint32_t) == 4, uint32_t_is_four_bytes)
-CASSERT(sizeof(int64_t) == 8, int64_t_is_eight_bytes)
-CASSERT(sizeof(uint64_t) == 8, uint64_t_is_eight_bytes)
-
-#endif
diff --git a/src/3rdparty/miniz/NOTE b/src/3rdparty/miniz/NOTE
deleted file mode 100644 (file)
index 4d0fa3b..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-This is Git checkout 28f5066e332590c8a68fa4870e89233e72ce7a44
-from https://github.com/richgel999/miniz that has not been modified.
diff --git a/src/3rdparty/miniz/miniz.c b/src/3rdparty/miniz/miniz.c
deleted file mode 100644 (file)
index 358143a..0000000
+++ /dev/null
@@ -1,4916 +0,0 @@
-/* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing\r
-   See "unlicense" statement at the end of this file.\r
-   Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013\r
-   Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt\r
-\r
-   Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define\r
-   MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).\r
-\r
-   * Change History\r
-     10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!):\r
-       - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug\r
-        would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place()\r
-        (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag).\r
-       - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size\r
-       - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries.\r
-         Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice).\r
-       - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes\r
-       - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed\r
-       - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6.\r
-       - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti\r
-       - Merged MZ_FORCEINLINE fix from hdeanclark\r
-       - Fix <time.h> include before config #ifdef, thanks emil.brink\r
-       - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can\r
-        set it to 1 for real-time compression).\r
-       - Merged in some compiler fixes from paulharris's github repro.\r
-       - Retested this build under Windows (VS 2010, including static analysis), tcc  0.9.26, gcc v4.6 and clang v3.3.\r
-       - Added example6.c, which dumps an image of the mandelbrot set to a PNG file.\r
-       - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.\r
-       - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled\r
-                - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch\r
-     5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect).\r
-     5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.\r
-       - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files.\r
-       - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.\r
-       - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly\r
-        "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning).\r
-       - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64.\r
-       - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test.\r
-       - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives.\r
-       - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.)\r
-       - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself).\r
-     4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's.\r
-      level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report.\r
-     5/28/11 v1.11 - Added statement from unlicense.org\r
-     5/27/11 v1.10 - Substantial compressor optimizations:\r
-      - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a\r
-      - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86).\r
-      - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types.\r
-      - Refactored the compression code for better readability and maintainability.\r
-      - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large\r
-       drop in throughput on some files).\r
-     5/15/11 v1.09 - Initial stable release.\r
-\r
-   * Low-level Deflate/Inflate implementation notes:\r
-\r
-     Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or\r
-     greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses\r
-     approximately as well as zlib.\r
-\r
-     Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function\r
-     coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory\r
-     block large enough to hold the entire file.\r
-\r
-     The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation.\r
-\r
-   * zlib-style API notes:\r
-\r
-     miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in\r
-     zlib replacement in many apps:\r
-        The z_stream struct, optional memory allocation callbacks\r
-        deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound\r
-        inflateInit/inflateInit2/inflate/inflateEnd\r
-        compress, compress2, compressBound, uncompress\r
-        CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines.\r
-        Supports raw deflate streams or standard zlib streams with adler-32 checking.\r
-\r
-     Limitations:\r
-      The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries.\r
-      I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but\r
-      there are no guarantees that miniz.c pulls this off perfectly.\r
-\r
-   * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by\r
-     Alex Evans. Supports 1-4 bytes/pixel images.\r
-\r
-   * ZIP archive API notes:\r
-\r
-     The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to\r
-     get the job done with minimal fuss. There are simple API's to retrieve file information, read files from\r
-     existing archives, create new archives, append new files to existing archives, or clone archive data from\r
-     one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h),\r
-     or you can specify custom file read/write callbacks.\r
-\r
-     - Archive reading: Just call this function to read a single file from a disk archive:\r
-\r
-      void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name,\r
-        size_t *pSize, mz_uint zip_flags);\r
-\r
-     For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central\r
-     directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files.\r
-\r
-     - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file:\r
-\r
-     int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);\r
-\r
-     The locate operation can optionally check file comments too, which (as one example) can be used to identify\r
-     multiple versions of the same file in an archive. This function uses a simple linear search through the central\r
-     directory, so it's not very fast.\r
-\r
-     Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and\r
-     retrieve detailed info on each file by calling mz_zip_reader_file_stat().\r
-\r
-     - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data\r
-     to disk and builds an exact image of the central directory in memory. The central directory image is written\r
-     all at once at the end of the archive file when the archive is finalized.\r
-\r
-     The archive writer can optionally align each file's local header and file data to any power of 2 alignment,\r
-     which can be useful when the archive will be read from optical media. Also, the writer supports placing\r
-     arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still\r
-     readable by any ZIP tool.\r
-\r
-     - Archive appending: The simple way to add a single file to an archive is to call this function:\r
-\r
-      mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name,\r
-        const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);\r
-\r
-     The archive will be created if it doesn't already exist, otherwise it'll be appended to.\r
-     Note the appending is done in-place and is not an atomic operation, so if something goes wrong\r
-     during the operation it's possible the archive could be left without a central directory (although the local\r
-     file headers and file data will be fine, so the archive will be recoverable).\r
-\r
-     For more complex archive modification scenarios:\r
-     1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to\r
-     preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the\r
-     compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and\r
-     you're done. This is safe but requires a bunch of temporary disk space or heap memory.\r
-\r
-     2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(),\r
-     append new files as needed, then finalize the archive which will write an updated central directory to the\r
-     original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a\r
-     possibility that the archive's central directory could be lost with this method if anything goes wrong, though.\r
-\r
-     - ZIP archive support limitations:\r
-     No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files.\r
-     Requires streams capable of seeking.\r
-\r
-   * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the\r
-     below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.\r
-\r
-   * Important: For best perf. be sure to customize the below macros for your target platform:\r
-     #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1\r
-     #define MINIZ_LITTLE_ENDIAN 1\r
-     #define MINIZ_HAS_64BIT_REGISTERS 1\r
-\r
-   * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz\r
-     uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files\r
-     (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).\r
-*/\r
-\r
-#ifndef MINIZ_HEADER_INCLUDED\r
-#define MINIZ_HEADER_INCLUDED\r
-\r
-#include <stdlib.h>\r
-\r
-// Defines to completely disable specific portions of miniz.c:\r
-// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.\r
-\r
-// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.\r
-//#define MINIZ_NO_STDIO\r
-\r
-// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or\r
-// get/set file times, and the C run-time funcs that get/set times won't be called.\r
-// The current downside is the times written to your archives will be from 1979.\r
-//#define MINIZ_NO_TIME\r
-\r
-// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.\r
-//#define MINIZ_NO_ARCHIVE_APIS\r
-\r
-// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.\r
-//#define MINIZ_NO_ARCHIVE_WRITING_APIS\r
-\r
-// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.\r
-//#define MINIZ_NO_ZLIB_APIS\r
-\r
-// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.\r
-//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES\r
-\r
-// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.\r
-// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc\r
-// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user\r
-// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.\r
-//#define MINIZ_NO_MALLOC\r
-\r
-#if defined(__TINYC__) && (defined(__linux) || defined(__linux__))\r
-  // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux\r
-  #define MINIZ_NO_TIME\r
-#endif\r
-\r
-#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)\r
-  #include <time.h>\r
-#endif\r
-\r
-#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)\r
-// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.\r
-#define MINIZ_X86_OR_X64_CPU 1\r
-#endif\r
-\r
-#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU\r
-// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.\r
-#define MINIZ_LITTLE_ENDIAN 1\r
-#endif\r
-\r
-#if MINIZ_X86_OR_X64_CPU\r
-// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.\r
-#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1\r
-#endif\r
-\r
-#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)\r
-// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions).\r
-#define MINIZ_HAS_64BIT_REGISTERS 1\r
-#endif\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-// ------------------- zlib-style API Definitions.\r
-\r
-// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!\r
-typedef unsigned long mz_ulong;\r
-\r
-// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap.\r
-void mz_free(void *p);\r
-\r
-#define MZ_ADLER32_INIT (1)\r
-// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.\r
-mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);\r
-\r
-#define MZ_CRC32_INIT (0)\r
-// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.\r
-mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);\r
-\r
-// Compression strategies.\r
-enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };\r
-\r
-// Method\r
-#define MZ_DEFLATED 8\r
-\r
-#ifndef MINIZ_NO_ZLIB_APIS\r
-\r
-// Heap allocation callbacks.\r
-// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.\r
-typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);\r
-typedef void (*mz_free_func)(void *opaque, void *address);\r
-typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);\r
-\r
-#define MZ_VERSION          "9.1.15"\r
-#define MZ_VERNUM           0x91F0\r
-#define MZ_VER_MAJOR        9\r
-#define MZ_VER_MINOR        1\r
-#define MZ_VER_REVISION     15\r
-#define MZ_VER_SUBREVISION  0\r
-\r
-// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs).\r
-enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };\r
-\r
-// Return status codes. MZ_PARAM_ERROR is non-standard.\r
-enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 };\r
-\r
-// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.\r
-enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 };\r
-\r
-// Window bits\r
-#define MZ_DEFAULT_WINDOW_BITS 15\r
-\r
-struct mz_internal_state;\r
-\r
-// Compression/decompression stream struct.\r
-typedef struct mz_stream_s\r
-{\r
-  const unsigned char *next_in;     // pointer to next byte to read\r
-  unsigned int avail_in;            // number of bytes available at next_in\r
-  mz_ulong total_in;                // total number of bytes consumed so far\r
-\r
-  unsigned char *next_out;          // pointer to next byte to write\r
-  unsigned int avail_out;           // number of bytes that can be written to next_out\r
-  mz_ulong total_out;               // total number of bytes produced so far\r
-\r
-  char *msg;                        // error msg (unused)\r
-  struct mz_internal_state *state;  // internal state, allocated by zalloc/zfree\r
-\r
-  mz_alloc_func zalloc;             // optional heap allocation function (defaults to malloc)\r
-  mz_free_func zfree;               // optional heap free function (defaults to free)\r
-  void *opaque;                     // heap alloc function user pointer\r
-\r
-  int data_type;                    // data_type (unused)\r
-  mz_ulong adler;                   // adler32 of the source or uncompressed data\r
-  mz_ulong reserved;                // not used\r
-} mz_stream;\r
-\r
-typedef mz_stream *mz_streamp;\r
-\r
-// Returns the version string of miniz.c.\r
-const char *mz_version(void);\r
-\r
-// mz_deflateInit() initializes a compressor with default options:\r
-// Parameters:\r
-//  pStream must point to an initialized mz_stream struct.\r
-//  level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].\r
-//  level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.\r
-//  (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)\r
-// Return values:\r
-//  MZ_OK on success.\r
-//  MZ_STREAM_ERROR if the stream is bogus.\r
-//  MZ_PARAM_ERROR if the input parameters are bogus.\r
-//  MZ_MEM_ERROR on out of memory.\r
-int mz_deflateInit(mz_streamp pStream, int level);\r
-\r
-// mz_deflateInit2() is like mz_deflate(), except with more control:\r
-// Additional parameters:\r
-//   method must be MZ_DEFLATED\r
-//   window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer)\r
-//   mem_level must be between [1, 9] (it's checked but ignored by miniz.c)\r
-int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);\r
-\r
-// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().\r
-int mz_deflateReset(mz_streamp pStream);\r
-\r
-// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.\r
-// Parameters:\r
-//   pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.\r
-//   flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.\r
-// Return values:\r
-//   MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full).\r
-//   MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore.\r
-//   MZ_STREAM_ERROR if the stream is bogus.\r
-//   MZ_PARAM_ERROR if one of the parameters is invalid.\r
-//   MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.)\r
-int mz_deflate(mz_streamp pStream, int flush);\r
-\r
-// mz_deflateEnd() deinitializes a compressor:\r
-// Return values:\r
-//  MZ_OK on success.\r
-//  MZ_STREAM_ERROR if the stream is bogus.\r
-int mz_deflateEnd(mz_streamp pStream);\r
-\r
-// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH.\r
-mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);\r
-\r
-// Single-call compression functions mz_compress() and mz_compress2():\r
-// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.\r
-int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);\r
-int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);\r
-\r
-// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().\r
-mz_ulong mz_compressBound(mz_ulong source_len);\r
-\r
-// Initializes a decompressor.\r
-int mz_inflateInit(mz_streamp pStream);\r
-\r
-// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer:\r
-// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).\r
-int mz_inflateInit2(mz_streamp pStream, int window_bits);\r
-\r
-// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible.\r
-// Parameters:\r
-//   pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.\r
-//   flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.\r
-//   On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster).\r
-//   MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data.\r
-// Return values:\r
-//   MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full.\r
-//   MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified.\r
-//   MZ_STREAM_ERROR if the stream is bogus.\r
-//   MZ_DATA_ERROR if the deflate stream is invalid.\r
-//   MZ_PARAM_ERROR if one of the parameters is invalid.\r
-//   MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again\r
-//   with more input data, or with more room in the output buffer (except when using single call decompression, described above).\r
-int mz_inflate(mz_streamp pStream, int flush);\r
-\r
-// Deinitializes a decompressor.\r
-int mz_inflateEnd(mz_streamp pStream);\r
-\r
-// Single-call decompression.\r
-// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.\r
-int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);\r
-\r
-// Returns a string description of the specified error code, or NULL if the error code is invalid.\r
-const char *mz_error(int err);\r
-\r
-// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports.\r
-// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.\r
-#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES\r
-  typedef unsigned char Byte;\r
-  typedef unsigned int uInt;\r
-  typedef mz_ulong uLong;\r
-  typedef Byte Bytef;\r
-  typedef uInt uIntf;\r
-  typedef char charf;\r
-  typedef int intf;\r
-  typedef void *voidpf;\r
-  typedef uLong uLongf;\r
-  typedef void *voidp;\r
-  typedef void *const voidpc;\r
-  #define Z_NULL                0\r
-  #define Z_NO_FLUSH            MZ_NO_FLUSH\r
-  #define Z_PARTIAL_FLUSH       MZ_PARTIAL_FLUSH\r
-  #define Z_SYNC_FLUSH          MZ_SYNC_FLUSH\r
-  #define Z_FULL_FLUSH          MZ_FULL_FLUSH\r
-  #define Z_FINISH              MZ_FINISH\r
-  #define Z_BLOCK               MZ_BLOCK\r
-  #define Z_OK                  MZ_OK\r
-  #define Z_STREAM_END          MZ_STREAM_END\r
-  #define Z_NEED_DICT           MZ_NEED_DICT\r
-  #define Z_ERRNO               MZ_ERRNO\r
-  #define Z_STREAM_ERROR        MZ_STREAM_ERROR\r
-  #define Z_DATA_ERROR          MZ_DATA_ERROR\r
-  #define Z_MEM_ERROR           MZ_MEM_ERROR\r
-  #define Z_BUF_ERROR           MZ_BUF_ERROR\r
-  #define Z_VERSION_ERROR       MZ_VERSION_ERROR\r
-  #define Z_PARAM_ERROR         MZ_PARAM_ERROR\r
-  #define Z_NO_COMPRESSION      MZ_NO_COMPRESSION\r
-  #define Z_BEST_SPEED          MZ_BEST_SPEED\r
-  #define Z_BEST_COMPRESSION    MZ_BEST_COMPRESSION\r
-  #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION\r
-  #define Z_DEFAULT_STRATEGY    MZ_DEFAULT_STRATEGY\r
-  #define Z_FILTERED            MZ_FILTERED\r
-  #define Z_HUFFMAN_ONLY        MZ_HUFFMAN_ONLY\r
-  #define Z_RLE                 MZ_RLE\r
-  #define Z_FIXED               MZ_FIXED\r
-  #define Z_DEFLATED            MZ_DEFLATED\r
-  #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS\r
-  #define alloc_func            mz_alloc_func\r
-  #define free_func             mz_free_func\r
-  #define internal_state        mz_internal_state\r
-  #define z_stream              mz_stream\r
-  #define deflateInit           mz_deflateInit\r
-  #define deflateInit2          mz_deflateInit2\r
-  #define deflateReset          mz_deflateReset\r
-  #define deflate               mz_deflate\r
-  #define deflateEnd            mz_deflateEnd\r
-  #define deflateBound          mz_deflateBound\r
-  #define compress              mz_compress\r
-  #define compress2             mz_compress2\r
-  #define compressBound         mz_compressBound\r
-  #define inflateInit           mz_inflateInit\r
-  #define inflateInit2          mz_inflateInit2\r
-  #define inflate               mz_inflate\r
-  #define inflateEnd            mz_inflateEnd\r
-  #define uncompress            mz_uncompress\r
-  #define crc32                 mz_crc32\r
-  #define adler32               mz_adler32\r
-  #define MAX_WBITS             15\r
-  #define MAX_MEM_LEVEL         9\r
-  #define zError                mz_error\r
-  #define ZLIB_VERSION          MZ_VERSION\r
-  #define ZLIB_VERNUM           MZ_VERNUM\r
-  #define ZLIB_VER_MAJOR        MZ_VER_MAJOR\r
-  #define ZLIB_VER_MINOR        MZ_VER_MINOR\r
-  #define ZLIB_VER_REVISION     MZ_VER_REVISION\r
-  #define ZLIB_VER_SUBREVISION  MZ_VER_SUBREVISION\r
-  #define zlibVersion           mz_version\r
-  #define zlib_version          mz_version()\r
-#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES\r
-\r
-#endif // MINIZ_NO_ZLIB_APIS\r
-\r
-// ------------------- Types and macros\r
-\r
-typedef unsigned char mz_uint8;\r
-typedef signed short mz_int16;\r
-typedef unsigned short mz_uint16;\r
-typedef unsigned int mz_uint32;\r
-typedef unsigned int mz_uint;\r
-typedef long long mz_int64;\r
-typedef unsigned long long mz_uint64;\r
-typedef int mz_bool;\r
-\r
-#define MZ_FALSE (0)\r
-#define MZ_TRUE (1)\r
-\r
-// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.\r
-#ifdef _MSC_VER\r
-   #define MZ_MACRO_END while (0, 0)\r
-#else\r
-   #define MZ_MACRO_END while (0)\r
-#endif\r
-\r
-// ------------------- ZIP archive reading/writing\r
-\r
-#ifndef MINIZ_NO_ARCHIVE_APIS\r
-\r
-enum\r
-{\r
-  MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024,\r
-  MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,\r
-  MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256\r
-};\r
-\r
-typedef struct\r
-{\r
-  mz_uint32 m_file_index;\r
-  mz_uint32 m_central_dir_ofs;\r
-  mz_uint16 m_version_made_by;\r
-  mz_uint16 m_version_needed;\r
-  mz_uint16 m_bit_flag;\r
-  mz_uint16 m_method;\r
-#ifndef MINIZ_NO_TIME\r
-  time_t m_time;\r
-#endif\r
-  mz_uint32 m_crc32;\r
-  mz_uint64 m_comp_size;\r
-  mz_uint64 m_uncomp_size;\r
-  mz_uint16 m_internal_attr;\r
-  mz_uint32 m_external_attr;\r
-  mz_uint64 m_local_header_ofs;\r
-  mz_uint32 m_comment_size;\r
-  char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];\r
-  char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];\r
-} mz_zip_archive_file_stat;\r
-\r
-typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);\r
-typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);\r
-\r
-struct mz_zip_internal_state_tag;\r
-typedef struct mz_zip_internal_state_tag mz_zip_internal_state;\r
-\r
-typedef enum\r
-{\r
-  MZ_ZIP_MODE_INVALID = 0,\r
-  MZ_ZIP_MODE_READING = 1,\r
-  MZ_ZIP_MODE_WRITING = 2,\r
-  MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3\r
-} mz_zip_mode;\r
-\r
-typedef struct mz_zip_archive_tag\r
-{\r
-  mz_uint64 m_archive_size;\r
-  mz_uint64 m_central_directory_file_ofs;\r
-  mz_uint m_total_files;\r
-  mz_zip_mode m_zip_mode;\r
-\r
-  mz_uint m_file_offset_alignment;\r
-\r
-  mz_alloc_func m_pAlloc;\r
-  mz_free_func m_pFree;\r
-  mz_realloc_func m_pRealloc;\r
-  void *m_pAlloc_opaque;\r
-\r
-  mz_file_read_func m_pRead;\r
-  mz_file_write_func m_pWrite;\r
-  void *m_pIO_opaque;\r
-\r
-  mz_zip_internal_state *m_pState;\r
-\r
-} mz_zip_archive;\r
-\r
-typedef enum\r
-{\r
-  MZ_ZIP_FLAG_CASE_SENSITIVE                = 0x0100,\r
-  MZ_ZIP_FLAG_IGNORE_PATH                   = 0x0200,\r
-  MZ_ZIP_FLAG_COMPRESSED_DATA               = 0x0400,\r
-  MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800\r
-} mz_zip_flags;\r
-\r
-// ZIP archive reading\r
-\r
-// Inits a ZIP archive reader.\r
-// These functions read and validate the archive's central directory.\r
-mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags);\r
-mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags);\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);\r
-#endif\r
-\r
-// Returns the total number of files in the archive.\r
-mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);\r
-\r
-// Returns detailed information about an archive file entry.\r
-mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat);\r
-\r
-// Determines if an archive file entry is a directory entry.\r
-mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);\r
-mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);\r
-\r
-// Retrieves the filename of an archive file entry.\r
-// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename.\r
-mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size);\r
-\r
-// Attempts to locates a file in the archive's central directory.\r
-// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH\r
-// Returns -1 if the file cannot be found.\r
-int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);\r
-\r
-// Extracts a archive file to a memory buffer using no memory allocation.\r
-mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);\r
-mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);\r
-\r
-// Extracts a archive file to a memory buffer.\r
-mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags);\r
-mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags);\r
-\r
-// Extracts a archive file to a dynamically allocated heap buffer.\r
-void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags);\r
-void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags);\r
-\r
-// Extracts a archive file using a callback function to output the file's data.\r
-mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);\r
-mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-// Extracts a archive file to a disk file and sets its last accessed and modified times.\r
-// This function only extracts files, not archive directory records.\r
-mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags);\r
-mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags);\r
-#endif\r
-\r
-// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.\r
-mz_bool mz_zip_reader_end(mz_zip_archive *pZip);\r
-\r
-// ZIP archive writing\r
-\r
-#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS\r
-\r
-// Inits a ZIP archive writer.\r
-mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);\r
-mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size);\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning);\r
-#endif\r
-\r
-// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.\r
-// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called.\r
-// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it).\r
-// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.\r
-// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before\r
-// the archive is finalized the file's central directory will be hosed.\r
-mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);\r
-\r
-// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.\r
-// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.\r
-// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.\r
-mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags);\r
-mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.\r
-// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.\r
-mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);\r
-#endif\r
-\r
-// Adds a file to an archive by fully cloning the data from another archive.\r
-// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.\r
-mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index);\r
-\r
-// Finalizes the archive by writing the central directory records followed by the end of central directory record.\r
-// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().\r
-// An archive must be manually finalized by calling this function for it to be valid.\r
-mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);\r
-mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize);\r
-\r
-// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.\r
-// Note for the archive to be valid, it must have been finalized before ending.\r
-mz_bool mz_zip_writer_end(mz_zip_archive *pZip);\r
-\r
-// Misc. high-level helper functions:\r
-\r
-// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.\r
-// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.\r
-mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);\r
-\r
-// Reads a single file from an archive into a heap block.\r
-// Returns NULL on failure.\r
-void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags);\r
-\r
-#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS\r
-\r
-#endif // #ifndef MINIZ_NO_ARCHIVE_APIS\r
-\r
-// ------------------- Low-level Decompression API Definitions\r
-\r
-// Decompression flags used by tinfl_decompress().\r
-// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream.\r
-// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input.\r
-// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB).\r
-// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.\r
-enum\r
-{\r
-  TINFL_FLAG_PARSE_ZLIB_HEADER = 1,\r
-  TINFL_FLAG_HAS_MORE_INPUT = 2,\r
-  TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,\r
-  TINFL_FLAG_COMPUTE_ADLER32 = 8\r
-};\r
-\r
-// High level decompression functions:\r
-// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().\r
-// On entry:\r
-//  pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.\r
-// On return:\r
-//  Function returns a pointer to the decompressed data, or NULL on failure.\r
-//  *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.\r
-//  The caller must call mz_free() on the returned block when it's no longer needed.\r
-void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);\r
-\r
-// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.\r
-// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.\r
-#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))\r
-size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);\r
-\r
-// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer.\r
-// Returns 1 on success or 0 on failure.\r
-typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);\r
-int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);\r
-\r
-struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;\r
-\r
-// Max size of LZ dictionary.\r
-#define TINFL_LZ_DICT_SIZE 32768\r
-\r
-// Return status.\r
-typedef enum\r
-{\r
-  TINFL_STATUS_BAD_PARAM = -3,\r
-  TINFL_STATUS_ADLER32_MISMATCH = -2,\r
-  TINFL_STATUS_FAILED = -1,\r
-  TINFL_STATUS_DONE = 0,\r
-  TINFL_STATUS_NEEDS_MORE_INPUT = 1,\r
-  TINFL_STATUS_HAS_MORE_OUTPUT = 2\r
-} tinfl_status;\r
-\r
-// Initializes the decompressor to its initial state.\r
-#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END\r
-#define tinfl_get_adler32(r) (r)->m_check_adler32\r
-\r
-// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability.\r
-// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output.\r
-tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);\r
-\r
-// Internal/private bits follow.\r
-enum\r
-{\r
-  TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,\r
-  TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS\r
-};\r
-\r
-typedef struct\r
-{\r
-  mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];\r
-  mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];\r
-} tinfl_huff_table;\r
-\r
-#if MINIZ_HAS_64BIT_REGISTERS\r
-  #define TINFL_USE_64BIT_BITBUF 1\r
-#endif\r
-\r
-#if TINFL_USE_64BIT_BITBUF\r
-  typedef mz_uint64 tinfl_bit_buf_t;\r
-  #define TINFL_BITBUF_SIZE (64)\r
-#else\r
-  typedef mz_uint32 tinfl_bit_buf_t;\r
-  #define TINFL_BITBUF_SIZE (32)\r
-#endif\r
-\r
-struct tinfl_decompressor_tag\r
-{\r
-  mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];\r
-  tinfl_bit_buf_t m_bit_buf;\r
-  size_t m_dist_from_out_buf_start;\r
-  tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];\r
-  mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];\r
-};\r
-\r
-// ------------------- Low-level Compression API Definitions\r
-\r
-// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).\r
-#define TDEFL_LESS_MEMORY 0\r
-\r
-// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):\r
-// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression).\r
-enum\r
-{\r
-  TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF\r
-};\r
-\r
-// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data.\r
-// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).\r
-// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.\r
-// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory).\r
-// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)\r
-// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.\r
-// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.\r
-// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.\r
-// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).\r
-enum\r
-{\r
-  TDEFL_WRITE_ZLIB_HEADER             = 0x01000,\r
-  TDEFL_COMPUTE_ADLER32               = 0x02000,\r
-  TDEFL_GREEDY_PARSING_FLAG           = 0x04000,\r
-  TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,\r
-  TDEFL_RLE_MATCHES                   = 0x10000,\r
-  TDEFL_FILTER_MATCHES                = 0x20000,\r
-  TDEFL_FORCE_ALL_STATIC_BLOCKS       = 0x40000,\r
-  TDEFL_FORCE_ALL_RAW_BLOCKS          = 0x80000\r
-};\r
-\r
-// High level compression functions:\r
-// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().\r
-// On entry:\r
-//  pSrc_buf, src_buf_len: Pointer and size of source block to compress.\r
-//  flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.\r
-// On return:\r
-//  Function returns a pointer to the compressed data, or NULL on failure.\r
-//  *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.\r
-//  The caller must free() the returned block when it's no longer needed.\r
-void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);\r
-\r
-// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.\r
-// Returns 0 on failure.\r
-size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);\r
-\r
-// Compresses an image to a compressed PNG file in memory.\r
-// On entry:\r
-//  pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. \r
-//  The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.\r
-//  level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL\r
-//  If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).\r
-// On return:\r
-//  Function returns a pointer to the compressed data, or NULL on failure.\r
-//  *pLen_out will be set to the size of the PNG image file.\r
-//  The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.\r
-void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip);\r
-void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out);\r
-\r
-// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.\r
-typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);\r
-\r
-// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.\r
-mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);\r
-\r
-enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 };\r
-\r
-// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).\r
-#if TDEFL_LESS_MEMORY\r
-enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };\r
-#else\r
-enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };\r
-#endif\r
-\r
-// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions.\r
-typedef enum\r
-{\r
-  TDEFL_STATUS_BAD_PARAM = -2,\r
-  TDEFL_STATUS_PUT_BUF_FAILED = -1,\r
-  TDEFL_STATUS_OKAY = 0,\r
-  TDEFL_STATUS_DONE = 1,\r
-} tdefl_status;\r
-\r
-// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums\r
-typedef enum\r
-{\r
-  TDEFL_NO_FLUSH = 0,\r
-  TDEFL_SYNC_FLUSH = 2,\r
-  TDEFL_FULL_FLUSH = 3,\r
-  TDEFL_FINISH = 4\r
-} tdefl_flush;\r
-\r
-// tdefl's compression state structure.\r
-typedef struct\r
-{\r
-  tdefl_put_buf_func_ptr m_pPut_buf_func;\r
-  void *m_pPut_buf_user;\r
-  mz_uint m_flags, m_max_probes[2];\r
-  int m_greedy_parsing;\r
-  mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;\r
-  mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;\r
-  mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;\r
-  mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;\r
-  tdefl_status m_prev_return_status;\r
-  const void *m_pIn_buf;\r
-  void *m_pOut_buf;\r
-  size_t *m_pIn_buf_size, *m_pOut_buf_size;\r
-  tdefl_flush m_flush;\r
-  const mz_uint8 *m_pSrc;\r
-  size_t m_src_buf_left, m_out_buf_ofs;\r
-  mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];\r
-  mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];\r
-  mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];\r
-  mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];\r
-  mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];\r
-  mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];\r
-  mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];\r
-  mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];\r
-} tdefl_compressor;\r
-\r
-// Initializes the compressor.\r
-// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.\r
-// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression.\r
-// If pBut_buf_func is NULL the user should always call the tdefl_compress() API.\r
-// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)\r
-tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);\r
-\r
-// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible.\r
-tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);\r
-\r
-// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.\r
-// tdefl_compress_buffer() always consumes the entire input buffer.\r
-tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);\r
-\r
-tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);\r
-mz_uint32 tdefl_get_adler32(tdefl_compressor *d);\r
-\r
-// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros.\r
-#ifndef MINIZ_NO_ZLIB_APIS\r
-// Create tdefl_compress() flags given zlib-style compression parameters.\r
-// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)\r
-// window_bits may be -15 (raw deflate) or 15 (zlib)\r
-// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED\r
-mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);\r
-#endif // #ifndef MINIZ_NO_ZLIB_APIS\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-\r
-#endif // MINIZ_HEADER_INCLUDED\r
-\r
-// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)\r
-\r
-#ifndef MINIZ_HEADER_FILE_ONLY\r
-\r
-typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1];\r
-typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1];\r
-typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1];\r
-\r
-#include <string.h>\r
-#include <assert.h>\r
-\r
-#define MZ_ASSERT(x) assert(x)\r
-\r
-#ifdef MINIZ_NO_MALLOC\r
-  #define MZ_MALLOC(x) NULL\r
-  #define MZ_FREE(x) (void)x, ((void)0)\r
-  #define MZ_REALLOC(p, x) NULL\r
-#else\r
-  #define MZ_MALLOC(x) malloc(x)\r
-  #define MZ_FREE(x) free(x)\r
-  #define MZ_REALLOC(p, x) realloc(p, x)\r
-#endif\r
-\r
-#define MZ_MAX(a,b) (((a)>(b))?(a):(b))\r
-#define MZ_MIN(a,b) (((a)<(b))?(a):(b))\r
-#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))\r
-\r
-#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN\r
-  #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))\r
-  #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))\r
-#else\r
-  #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))\r
-  #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))\r
-#endif\r
-\r
-#ifdef _MSC_VER\r
-  #define MZ_FORCEINLINE __forceinline\r
-#elif defined(__GNUC__)\r
-  #define MZ_FORCEINLINE inline __attribute__((__always_inline__))\r
-#else\r
-  #define MZ_FORCEINLINE inline\r
-#endif\r
-\r
-#ifdef __cplusplus\r
-  extern "C" {\r
-#endif\r
-\r
-// ------------------- zlib-style API's\r
-\r
-mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len)\r
-{\r
-  mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552;\r
-  if (!ptr) return MZ_ADLER32_INIT;\r
-  while (buf_len) {\r
-    for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {\r
-      s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;\r
-      s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;\r
-    }\r
-    for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;\r
-    s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;\r
-  }\r
-  return (s2 << 16) + s1;\r
-}\r
-\r
-// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/\r
-mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)\r
-{\r
-  static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,\r
-    0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };\r
-  mz_uint32 crcu32 = (mz_uint32)crc;\r
-  if (!ptr) return MZ_CRC32_INIT;\r
-  crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; }\r
-  return ~crcu32;\r
-}\r
-\r
-void mz_free(void *p)\r
-{\r
-  MZ_FREE(p);\r
-}\r
-\r
-#ifndef MINIZ_NO_ZLIB_APIS\r
-\r
-static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); }\r
-static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); }\r
-static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); }\r
-\r
-const char *mz_version(void)\r
-{\r
-  return MZ_VERSION;\r
-}\r
-\r
-int mz_deflateInit(mz_streamp pStream, int level)\r
-{\r
-  return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY);\r
-}\r
-\r
-int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy)\r
-{\r
-  tdefl_compressor *pComp;\r
-  mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);\r
-\r
-  if (!pStream) return MZ_STREAM_ERROR;\r
-  if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR;\r
-\r
-  pStream->data_type = 0;\r
-  pStream->adler = MZ_ADLER32_INIT;\r
-  pStream->msg = NULL;\r
-  pStream->reserved = 0;\r
-  pStream->total_in = 0;\r
-  pStream->total_out = 0;\r
-  if (!pStream->zalloc) pStream->zalloc = def_alloc_func;\r
-  if (!pStream->zfree) pStream->zfree = def_free_func;\r
-\r
-  pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor));\r
-  if (!pComp)\r
-    return MZ_MEM_ERROR;\r
-\r
-  pStream->state = (struct mz_internal_state *)pComp;\r
-\r
-  if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY)\r
-  {\r
-    mz_deflateEnd(pStream);\r
-    return MZ_PARAM_ERROR;\r
-  }\r
-\r
-  return MZ_OK;\r
-}\r
-\r
-int mz_deflateReset(mz_streamp pStream)\r
-{\r
-  if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR;\r
-  pStream->total_in = pStream->total_out = 0;\r
-  tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags);\r
-  return MZ_OK;\r
-}\r
-\r
-int mz_deflate(mz_streamp pStream, int flush)\r
-{\r
-  size_t in_bytes, out_bytes;\r
-  mz_ulong orig_total_in, orig_total_out;\r
-  int mz_status = MZ_OK;\r
-\r
-  if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR;\r
-  if (!pStream->avail_out) return MZ_BUF_ERROR;\r
-\r
-  if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;\r
-\r
-  if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE)\r
-    return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;\r
-\r
-  orig_total_in = pStream->total_in; orig_total_out = pStream->total_out;\r
-  for ( ; ; )\r
-  {\r
-    tdefl_status defl_status;\r
-    in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;\r
-\r
-    defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush);\r
-    pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;\r
-    pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state);\r
-\r
-    pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes;\r
-    pStream->total_out += (mz_uint)out_bytes;\r
-\r
-    if (defl_status < 0)\r
-    {\r
-      mz_status = MZ_STREAM_ERROR;\r
-      break;\r
-    }\r
-    else if (defl_status == TDEFL_STATUS_DONE)\r
-    {\r
-      mz_status = MZ_STREAM_END;\r
-      break;\r
-    }\r
-    else if (!pStream->avail_out)\r
-      break;\r
-    else if ((!pStream->avail_in) && (flush != MZ_FINISH))\r
-    {\r
-      if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out))\r
-        break;\r
-      return MZ_BUF_ERROR; // Can't make forward progress without some input.\r
-    }\r
-  }\r
-  return mz_status;\r
-}\r
-\r
-int mz_deflateEnd(mz_streamp pStream)\r
-{\r
-  if (!pStream) return MZ_STREAM_ERROR;\r
-  if (pStream->state)\r
-  {\r
-    pStream->zfree(pStream->opaque, pStream->state);\r
-    pStream->state = NULL;\r
-  }\r
-  return MZ_OK;\r
-}\r
-\r
-mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len)\r
-{\r
-  (void)pStream;\r
-  // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.)\r
-  return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);\r
-}\r
-\r
-int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level)\r
-{\r
-  int status;\r
-  mz_stream stream;\r
-  memset(&stream, 0, sizeof(stream));\r
-\r
-  // In case mz_ulong is 64-bits (argh I hate longs).\r
-  if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;\r
-\r
-  stream.next_in = pSource;\r
-  stream.avail_in = (mz_uint32)source_len;\r
-  stream.next_out = pDest;\r
-  stream.avail_out = (mz_uint32)*pDest_len;\r
-\r
-  status = mz_deflateInit(&stream, level);\r
-  if (status != MZ_OK) return status;\r
-\r
-  status = mz_deflate(&stream, MZ_FINISH);\r
-  if (status != MZ_STREAM_END)\r
-  {\r
-    mz_deflateEnd(&stream);\r
-    return (status == MZ_OK) ? MZ_BUF_ERROR : status;\r
-  }\r
-\r
-  *pDest_len = stream.total_out;\r
-  return mz_deflateEnd(&stream);\r
-}\r
-\r
-int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)\r
-{\r
-  return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION);\r
-}\r
-\r
-mz_ulong mz_compressBound(mz_ulong source_len)\r
-{\r
-  return mz_deflateBound(NULL, source_len);\r
-}\r
-\r
-typedef struct\r
-{\r
-  tinfl_decompressor m_decomp;\r
-  mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits;\r
-  mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];\r
-  tinfl_status m_last_status;\r
-} inflate_state;\r
-\r
-int mz_inflateInit2(mz_streamp pStream, int window_bits)\r
-{\r
-  inflate_state *pDecomp;\r
-  if (!pStream) return MZ_STREAM_ERROR;\r
-  if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR;\r
-\r
-  pStream->data_type = 0;\r
-  pStream->adler = 0;\r
-  pStream->msg = NULL;\r
-  pStream->total_in = 0;\r
-  pStream->total_out = 0;\r
-  pStream->reserved = 0;\r
-  if (!pStream->zalloc) pStream->zalloc = def_alloc_func;\r
-  if (!pStream->zfree) pStream->zfree = def_free_func;\r
-\r
-  pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state));\r
-  if (!pDecomp) return MZ_MEM_ERROR;\r
-\r
-  pStream->state = (struct mz_internal_state *)pDecomp;\r
-\r
-  tinfl_init(&pDecomp->m_decomp);\r
-  pDecomp->m_dict_ofs = 0;\r
-  pDecomp->m_dict_avail = 0;\r
-  pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;\r
-  pDecomp->m_first_call = 1;\r
-  pDecomp->m_has_flushed = 0;\r
-  pDecomp->m_window_bits = window_bits;\r
-\r
-  return MZ_OK;\r
-}\r
-\r
-int mz_inflateInit(mz_streamp pStream)\r
-{\r
-   return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);\r
-}\r
-\r
-int mz_inflate(mz_streamp pStream, int flush)\r
-{\r
-  inflate_state* pState;\r
-  mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;\r
-  size_t in_bytes, out_bytes, orig_avail_in;\r
-  tinfl_status status;\r
-\r
-  if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;\r
-  if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;\r
-  if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;\r
-\r
-  pState = (inflate_state*)pStream->state;\r
-  if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;\r
-  orig_avail_in = pStream->avail_in;\r
-\r
-  first_call = pState->m_first_call; pState->m_first_call = 0;\r
-  if (pState->m_last_status < 0) return MZ_DATA_ERROR;\r
-\r
-  if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;\r
-  pState->m_has_flushed |= (flush == MZ_FINISH);\r
-\r
-  if ((flush == MZ_FINISH) && (first_call))\r
-  {\r
-    // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file.\r
-    decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;\r
-    in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;\r
-    status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags);\r
-    pState->m_last_status = status;\r
-    pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes;\r
-    pStream->adler = tinfl_get_adler32(&pState->m_decomp);\r
-    pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes;\r
-\r
-    if (status < 0)\r
-      return MZ_DATA_ERROR;\r
-    else if (status != TINFL_STATUS_DONE)\r
-    {\r
-      pState->m_last_status = TINFL_STATUS_FAILED;\r
-      return MZ_BUF_ERROR;\r
-    }\r
-    return MZ_STREAM_END;\r
-  }\r
-  // flush != MZ_FINISH then we must assume there's more input.\r
-  if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;\r
-\r
-  if (pState->m_dict_avail)\r
-  {\r
-    n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);\r
-    memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);\r
-    pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;\r
-    pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);\r
-    return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;\r
-  }\r
-\r
-  for ( ; ; )\r
-  {\r
-    in_bytes = pStream->avail_in;\r
-    out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;\r
-\r
-    status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);\r
-    pState->m_last_status = status;\r
-\r
-    pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;\r
-    pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp);\r
-\r
-    pState->m_dict_avail = (mz_uint)out_bytes;\r
-\r
-    n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);\r
-    memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);\r
-    pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;\r
-    pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);\r
-\r
-    if (status < 0)\r
-       return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well).\r
-    else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))\r
-      return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH.\r
-    else if (flush == MZ_FINISH)\r
-    {\r
-       // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH.\r
-       if (status == TINFL_STATUS_DONE)\r
-          return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;\r
-       // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong.\r
-       else if (!pStream->avail_out)\r
-          return MZ_BUF_ERROR;\r
-    }\r
-    else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail))\r
-      break;\r
-  }\r
-\r
-  return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;\r
-}\r
-\r
-int mz_inflateEnd(mz_streamp pStream)\r
-{\r
-  if (!pStream)\r
-    return MZ_STREAM_ERROR;\r
-  if (pStream->state)\r
-  {\r
-    pStream->zfree(pStream->opaque, pStream->state);\r
-    pStream->state = NULL;\r
-  }\r
-  return MZ_OK;\r
-}\r
-\r
-int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)\r
-{\r
-  mz_stream stream;\r
-  int status;\r
-  memset(&stream, 0, sizeof(stream));\r
-\r
-  // In case mz_ulong is 64-bits (argh I hate longs).\r
-  if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;\r
-\r
-  stream.next_in = pSource;\r
-  stream.avail_in = (mz_uint32)source_len;\r
-  stream.next_out = pDest;\r
-  stream.avail_out = (mz_uint32)*pDest_len;\r
-\r
-  status = mz_inflateInit(&stream);\r
-  if (status != MZ_OK)\r
-    return status;\r
-\r
-  status = mz_inflate(&stream, MZ_FINISH);\r
-  if (status != MZ_STREAM_END)\r
-  {\r
-    mz_inflateEnd(&stream);\r
-    return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status;\r
-  }\r
-  *pDest_len = stream.total_out;\r
-\r
-  return mz_inflateEnd(&stream);\r
-}\r
-\r
-const char *mz_error(int err)\r
-{\r
-  static struct { int m_err; const char *m_pDesc; } s_error_descs[] =\r
-  {\r
-    { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" },\r
-    { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" }\r
-  };\r
-  mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc;\r
-  return NULL;\r
-}\r
-\r
-#endif //MINIZ_NO_ZLIB_APIS\r
-\r
-// ------------------- Low-level Decompression (completely independent from all compression API's)\r
-\r
-#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)\r
-#define TINFL_MEMSET(p, c, l) memset(p, c, l)\r
-\r
-#define TINFL_CR_BEGIN switch(r->m_state) { case 0:\r
-#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END\r
-#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END\r
-#define TINFL_CR_FINISH }\r
-\r
-// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never\r
-// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.\r
-#define TINFL_GET_BYTE(state_index, c) do { \\r
-  if (pIn_buf_cur >= pIn_buf_end) { \\r
-    for ( ; ; ) { \\r
-      if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \\r
-        TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \\r
-        if (pIn_buf_cur < pIn_buf_end) { \\r
-          c = *pIn_buf_cur++; \\r
-          break; \\r
-        } \\r
-      } else { \\r
-        c = 0; \\r
-        break; \\r
-      } \\r
-    } \\r
-  } else c = *pIn_buf_cur++; } MZ_MACRO_END\r
-\r
-#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))\r
-#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END\r
-#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END\r
-\r
-// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.\r
-// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a\r
-// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the\r
-// bit buffer contains >=15 bits (deflate's max. Huffman code size).\r
-#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \\r
-  do { \\r
-    temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \\r
-    if (temp >= 0) { \\r
-      code_len = temp >> 9; \\r
-      if ((code_len) && (num_bits >= code_len)) \\r
-      break; \\r
-    } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \\r
-       code_len = TINFL_FAST_LOOKUP_BITS; \\r
-       do { \\r
-          temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \\r
-       } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \\r
-    } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \\r
-  } while (num_bits < 15);\r
-\r
-// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read\r
-// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully\r
-// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32.\r
-// The slow path is only executed at the very end of the input buffer.\r
-#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \\r
-  int temp; mz_uint code_len, c; \\r
-  if (num_bits < 15) { \\r
-    if ((pIn_buf_end - pIn_buf_cur) < 2) { \\r
-       TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \\r
-    } else { \\r
-       bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \\r
-    } \\r
-  } \\r
-  if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \\r
-    code_len = temp >> 9, temp &= 511; \\r
-  else { \\r
-    code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \\r
-  } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END\r
-\r
-tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags)\r
-{\r
-  static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };\r
-  static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };\r
-  static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};\r
-  static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};\r
-  static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };\r
-  static const int s_min_table_sizes[3] = { 257, 1, 4 };\r
-\r
-  tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf;\r
-  const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;\r
-  mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;\r
-  size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;\r
-\r
-  // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter).\r
-  if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; }\r
-\r
-  num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start;\r
-  TINFL_CR_BEGIN\r
-\r
-  bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1;\r
-  if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)\r
-  {\r
-    TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1);\r
-    counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));\r
-    if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));\r
-    if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); }\r
-  }\r
-\r
-  do\r
-  {\r
-    TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1;\r
-    if (r->m_type == 0)\r
-    {\r
-      TINFL_SKIP_BITS(5, num_bits & 7);\r
-      for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); }\r
-      if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); }\r
-      while ((counter) && (num_bits))\r
-      {\r
-        TINFL_GET_BITS(51, dist, 8);\r
-        while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); }\r
-        *pOut_buf_cur++ = (mz_uint8)dist;\r
-        counter--;\r
-      }\r
-      while (counter)\r
-      {\r
-        size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); }\r
-        while (pIn_buf_cur >= pIn_buf_end)\r
-        {\r
-          if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)\r
-          {\r
-            TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);\r
-          }\r
-          else\r
-          {\r
-            TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);\r
-          }\r
-        }\r
-        n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);\r
-        TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n;\r
-      }\r
-    }\r
-    else if (r->m_type == 3)\r
-    {\r
-      TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);\r
-    }\r
-    else\r
-    {\r
-      if (r->m_type == 1)\r
-      {\r
-        mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i;\r
-        r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);\r
-        for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8;\r
-      }\r
-      else\r
-      {\r
-        for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; }\r
-        MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; }\r
-        r->m_table_sizes[2] = 19;\r
-      }\r
-      for ( ; (int)r->m_type >= 0; r->m_type--)\r
-      {\r
-        int tree_next, tree_cur; tinfl_huff_table *pTable;\r
-        mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree);\r
-        for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++;\r
-        used_syms = 0, total = 0; next_code[0] = next_code[1] = 0;\r
-        for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); }\r
-        if ((65536 != total) && (used_syms > 1))\r
-        {\r
-          TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);\r
-        }\r
-        for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)\r
-        {\r
-          mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue;\r
-          cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1);\r
-          if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; }\r
-          if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }\r
-          rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);\r
-          for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)\r
-          {\r
-            tree_cur -= ((rev_code >>= 1) & 1);\r
-            if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1];\r
-          }\r
-          tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;\r
-        }\r
-        if (r->m_type == 2)\r
-        {\r
-          for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); )\r
-          {\r
-            mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; }\r
-            if ((dist == 16) && (!counter))\r
-            {\r
-              TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);\r
-            }\r
-            num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16];\r
-            TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s;\r
-          }\r
-          if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)\r
-          {\r
-            TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);\r
-          }\r
-          TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);\r
-        }\r
-      }\r
-      for ( ; ; )\r
-      {\r
-        mz_uint8 *pSrc;\r
-        for ( ; ; )\r
-        {\r
-          if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))\r
-          {\r
-            TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);\r
-            if (counter >= 256)\r
-              break;\r
-            while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); }\r
-            *pOut_buf_cur++ = (mz_uint8)counter;\r
-          }\r
-          else\r
-          {\r
-            int sym2; mz_uint code_len;\r
-#if TINFL_USE_64BIT_BITBUF\r
-            if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; }\r
-#else\r
-            if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }\r
-#endif\r
-            if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)\r
-              code_len = sym2 >> 9;\r
-            else\r
-            {\r
-              code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);\r
-            }\r
-            counter = sym2; bit_buf >>= code_len; num_bits -= code_len;\r
-            if (counter & 256)\r
-              break;\r
-\r
-#if !TINFL_USE_64BIT_BITBUF\r
-            if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }\r
-#endif\r
-            if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)\r
-              code_len = sym2 >> 9;\r
-            else\r
-            {\r
-              code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);\r
-            }\r
-            bit_buf >>= code_len; num_bits -= code_len;\r
-\r
-            pOut_buf_cur[0] = (mz_uint8)counter;\r
-            if (sym2 & 256)\r
-            {\r
-              pOut_buf_cur++;\r
-              counter = sym2;\r
-              break;\r
-            }\r
-            pOut_buf_cur[1] = (mz_uint8)sym2;\r
-            pOut_buf_cur += 2;\r
-          }\r
-        }\r
-        if ((counter &= 511) == 256) break;\r
-\r
-        num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257];\r
-        if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; }\r
-\r
-        TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);\r
-        num_extra = s_dist_extra[dist]; dist = s_dist_base[dist];\r
-        if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; }\r
-\r
-        dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;\r
-        if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))\r
-        {\r
-          TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);\r
-        }\r
-\r
-        pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);\r
-\r
-        if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)\r
-        {\r
-          while (counter--)\r
-          {\r
-            while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); }\r
-            *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];\r
-          }\r
-          continue;\r
-        }\r
-#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES\r
-        else if ((counter >= 9) && (counter <= dist))\r
-        {\r
-          const mz_uint8 *pSrc_end = pSrc + (counter & ~7);\r
-          do\r
-          {\r
-            ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];\r
-            ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];\r
-            pOut_buf_cur += 8;\r
-          } while ((pSrc += 8) < pSrc_end);\r
-          if ((counter &= 7) < 3)\r
-          {\r
-            if (counter)\r
-            {\r
-              pOut_buf_cur[0] = pSrc[0];\r
-              if (counter > 1)\r
-                pOut_buf_cur[1] = pSrc[1];\r
-              pOut_buf_cur += counter;\r
-            }\r
-            continue;\r
-          }\r
-        }\r
-#endif\r
-        do\r
-        {\r
-          pOut_buf_cur[0] = pSrc[0];\r
-          pOut_buf_cur[1] = pSrc[1];\r
-          pOut_buf_cur[2] = pSrc[2];\r
-          pOut_buf_cur += 3; pSrc += 3;\r
-        } while ((int)(counter -= 3) > 2);\r
-        if ((int)counter > 0)\r
-        {\r
-          pOut_buf_cur[0] = pSrc[0];\r
-          if ((int)counter > 1)\r
-            pOut_buf_cur[1] = pSrc[1];\r
-          pOut_buf_cur += counter;\r
-        }\r
-      }\r
-    }\r
-  } while (!(r->m_final & 1));\r
-  if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)\r
-  {\r
-    TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; }\r
-  }\r
-  TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);\r
-  TINFL_CR_FINISH\r
-\r
-common_exit:\r
-  r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start;\r
-  *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next;\r
-  if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))\r
-  {\r
-    const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size;\r
-    mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552;\r
-    while (buf_len)\r
-    {\r
-      for (i = 0; i + 7 < block_len; i += 8, ptr += 8)\r
-      {\r
-        s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;\r
-        s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;\r
-      }\r
-      for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;\r
-      s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;\r
-    }\r
-    r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH;\r
-  }\r
-  return status;\r
-}\r
-\r
-// Higher level helper functions.\r
-void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)\r
-{\r
-  tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0;\r
-  *pOut_len = 0;\r
-  tinfl_init(&decomp);\r
-  for ( ; ; )\r
-  {\r
-    size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;\r
-    tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size,\r
-      (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);\r
-    if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))\r
-    {\r
-      MZ_FREE(pBuf); *pOut_len = 0; return NULL;\r
-    }\r
-    src_buf_ofs += src_buf_size;\r
-    *pOut_len += dst_buf_size;\r
-    if (status == TINFL_STATUS_DONE) break;\r
-    new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;\r
-    pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);\r
-    if (!pNew_buf)\r
-    {\r
-      MZ_FREE(pBuf); *pOut_len = 0; return NULL;\r
-    }\r
-    pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity;\r
-  }\r
-  return pBuf;\r
-}\r
-\r
-size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)\r
-{\r
-  tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp);\r
-  status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);\r
-  return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;\r
-}\r
-\r
-int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)\r
-{\r
-  int result = 0;\r
-  tinfl_decompressor decomp;\r
-  mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0;\r
-  if (!pDict)\r
-    return TINFL_STATUS_FAILED;\r
-  tinfl_init(&decomp);\r
-  for ( ; ; )\r
-  {\r
-    size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;\r
-    tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,\r
-      (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));\r
-    in_buf_ofs += in_buf_size;\r
-    if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))\r
-      break;\r
-    if (status != TINFL_STATUS_HAS_MORE_OUTPUT)\r
-    {\r
-      result = (status == TINFL_STATUS_DONE);\r
-      break;\r
-    }\r
-    dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);\r
-  }\r
-  MZ_FREE(pDict);\r
-  *pIn_buf_size = in_buf_ofs;\r
-  return result;\r
-}\r
-\r
-// ------------------- Low-level Compression (independent from all decompression API's)\r
-\r
-// Purposely making these tables static for faster init and thread safety.\r
-static const mz_uint16 s_tdefl_len_sym[256] = {\r
-  257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272,\r
-  273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276,\r
-  277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,\r
-  279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,\r
-  281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,\r
-  282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,\r
-  283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,\r
-  284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 };\r
-\r
-static const mz_uint8 s_tdefl_len_extra[256] = {\r
-  0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,\r
-  4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,\r
-  5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,\r
-  5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 };\r
-\r
-static const mz_uint8 s_tdefl_small_dist_sym[512] = {\r
-  0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,\r
-  11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,\r
-  13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,\r
-  14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,\r
-  14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,\r
-  15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,\r
-  16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,\r
-  16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,\r
-  16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,\r
-  17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,\r
-  17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,\r
-  17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 };\r
-\r
-static const mz_uint8 s_tdefl_small_dist_extra[512] = {\r
-  0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,\r
-  5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\r
-  6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,\r
-  6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\r
-  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\r
-  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\r
-  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,\r
-  7,7,7,7,7,7,7,7 };\r
-\r
-static const mz_uint8 s_tdefl_large_dist_sym[128] = {\r
-  0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,\r
-  26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,\r
-  28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 };\r
-\r
-static const mz_uint8 s_tdefl_large_dist_extra[128] = {\r
-  0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,\r
-  12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,\r
-  13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 };\r
-\r
-// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.\r
-typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;\r
-static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1)\r
-{\r
-  mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist);\r
-  for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; }\r
-  while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;\r
-  for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)\r
-  {\r
-    const mz_uint32* pHist = &hist[pass << 8];\r
-    mz_uint offsets[256], cur_ofs = 0;\r
-    for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }\r
-    for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];\r
-    { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; }\r
-  }\r
-  return pCur_syms;\r
-}\r
-\r
-// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.\r
-static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n)\r
-{\r
-  int root, leaf, next, avbl, used, dpth;\r
-  if (n==0) return; else if (n==1) { A[0].m_key = 1; return; }\r
-  A[0].m_key += A[1].m_key; root = 0; leaf = 2;\r
-  for (next=1; next < n-1; next++)\r
-  {\r
-    if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key;\r
-    if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);\r
-  }\r
-  A[n-2].m_key = 0; for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;\r
-  avbl = 1; used = dpth = 0; root = n-2; next = n-1;\r
-  while (avbl>0)\r
-  {\r
-    while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; }\r
-    while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; }\r
-    avbl = 2*used; dpth++; used = 0;\r
-  }\r
-}\r
-\r
-// Limits canonical Huffman code table's max code size.\r
-enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };\r
-static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)\r
-{\r
-  int i; mz_uint32 total = 0; if (code_list_len <= 1) return;\r
-  for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];\r
-  for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));\r
-  while (total != (1UL << max_code_size))\r
-  {\r
-    pNum_codes[max_code_size]--;\r
-    for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }\r
-    total--;\r
-  }\r
-}\r
-\r
-static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table)\r
-{\r
-  int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes);\r
-  if (static_table)\r
-  {\r
-    for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++;\r
-  }\r
-  else\r
-  {\r
-    tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;\r
-    int num_used_syms = 0;\r
-    const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];\r
-    for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; }\r
-\r
-    pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);\r
-\r
-    for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;\r
-\r
-    tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit);\r
-\r
-    MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);\r
-    for (i = 1, j = num_used_syms; i <= code_size_limit; i++)\r
-      for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);\r
-  }\r
-\r
-  next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1);\r
-\r
-  for (i = 0; i < table_len; i++)\r
-  {\r
-    mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;\r
-    code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1);\r
-    d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;\r
-  }\r
-}\r
-\r
-#define TDEFL_PUT_BITS(b, l) do { \\r
-  mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \\r
-  d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \\r
-  while (d->m_bits_in >= 8) { \\r
-    if (d->m_pOutput_buf < d->m_pOutput_buf_end) \\r
-      *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \\r
-      d->m_bit_buffer >>= 8; \\r
-      d->m_bits_in -= 8; \\r
-  } \\r
-} MZ_MACRO_END\r
-\r
-#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \\r
-  if (rle_repeat_count < 3) { \\r
-    d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \\r
-    while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \\r
-  } else { \\r
-    d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \\r
-} rle_repeat_count = 0; } }\r
-\r
-#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \\r
-  if (rle_z_count < 3) { \\r
-    d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \\r
-  } else if (rle_z_count <= 10) { \\r
-    d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \\r
-  } else { \\r
-    d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \\r
-} rle_z_count = 0; } }\r
-\r
-static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };\r
-\r
-static void tdefl_start_dynamic_block(tdefl_compressor *d)\r
-{\r
-  int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;\r
-  mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;\r
-\r
-  d->m_huff_count[0][256] = 1;\r
-\r
-  tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);\r
-  tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);\r
-\r
-  for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;\r
-  for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;\r
-\r
-  memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);\r
-  memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes);\r
-  total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0;\r
-\r
-  memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);\r
-  for (i = 0; i < total_code_sizes_to_pack; i++)\r
-  {\r
-    mz_uint8 code_size = code_sizes_to_pack[i];\r
-    if (!code_size)\r
-    {\r
-      TDEFL_RLE_PREV_CODE_SIZE();\r
-      if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); }\r
-    }\r
-    else\r
-    {\r
-      TDEFL_RLE_ZERO_CODE_SIZE();\r
-      if (code_size != prev_code_size)\r
-      {\r
-        TDEFL_RLE_PREV_CODE_SIZE();\r
-        d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size;\r
-      }\r
-      else if (++rle_repeat_count == 6)\r
-      {\r
-        TDEFL_RLE_PREV_CODE_SIZE();\r
-      }\r
-    }\r
-    prev_code_size = code_size;\r
-  }\r
-  if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); }\r
-\r
-  tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);\r
-\r
-  TDEFL_PUT_BITS(2, 2);\r
-\r
-  TDEFL_PUT_BITS(num_lit_codes - 257, 5);\r
-  TDEFL_PUT_BITS(num_dist_codes - 1, 5);\r
-\r
-  for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break;\r
-  num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4);\r
-  for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);\r
-\r
-  for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )\r
-  {\r
-    mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);\r
-    TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);\r
-    if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]);\r
-  }\r
-}\r
-\r
-static void tdefl_start_static_block(tdefl_compressor *d)\r
-{\r
-  mz_uint i;\r
-  mz_uint8 *p = &d->m_huff_code_sizes[0][0];\r
-\r
-  for (i = 0; i <= 143; ++i) *p++ = 8;\r
-  for ( ; i <= 255; ++i) *p++ = 9;\r
-  for ( ; i <= 279; ++i) *p++ = 7;\r
-  for ( ; i <= 287; ++i) *p++ = 8;\r
-\r
-  memset(d->m_huff_code_sizes[1], 5, 32);\r
-\r
-  tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);\r
-  tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);\r
-\r
-  TDEFL_PUT_BITS(1, 2);\r
-}\r
-\r
-static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };\r
-\r
-#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS\r
-static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)\r
-{\r
-  mz_uint flags;\r
-  mz_uint8 *pLZ_codes;\r
-  mz_uint8 *pOutput_buf = d->m_pOutput_buf;\r
-  mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;\r
-  mz_uint64 bit_buffer = d->m_bit_buffer;\r
-  mz_uint bits_in = d->m_bits_in;\r
-\r
-#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); }\r
-\r
-  flags = 1;\r
-  for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1)\r
-  {\r
-    if (flags == 1)\r
-      flags = *pLZ_codes++ | 0x100;\r
-\r
-    if (flags & 1)\r
-    {\r
-      mz_uint s0, s1, n0, n1, sym, num_extra_bits;\r
-      mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3;\r
-\r
-      MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);\r
-      TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);\r
-      TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);\r
-\r
-      // This sequence coaxes MSVC into using cmov's vs. jmp's.\r
-      s0 = s_tdefl_small_dist_sym[match_dist & 511];\r
-      n0 = s_tdefl_small_dist_extra[match_dist & 511];\r
-      s1 = s_tdefl_large_dist_sym[match_dist >> 8];\r
-      n1 = s_tdefl_large_dist_extra[match_dist >> 8];\r
-      sym = (match_dist < 512) ? s0 : s1;\r
-      num_extra_bits = (match_dist < 512) ? n0 : n1;\r
-\r
-      MZ_ASSERT(d->m_huff_code_sizes[1][sym]);\r
-      TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);\r
-      TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);\r
-    }\r
-    else\r
-    {\r
-      mz_uint lit = *pLZ_codes++;\r
-      MZ_ASSERT(d->m_huff_code_sizes[0][lit]);\r
-      TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);\r
-\r
-      if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))\r
-      {\r
-        flags >>= 1;\r
-        lit = *pLZ_codes++;\r
-        MZ_ASSERT(d->m_huff_code_sizes[0][lit]);\r
-        TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);\r
-\r
-        if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))\r
-        {\r
-          flags >>= 1;\r
-          lit = *pLZ_codes++;\r
-          MZ_ASSERT(d->m_huff_code_sizes[0][lit]);\r
-          TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);\r
-        }\r
-      }\r
-    }\r
-\r
-    if (pOutput_buf >= d->m_pOutput_buf_end)\r
-      return MZ_FALSE;\r
-\r
-    *(mz_uint64*)pOutput_buf = bit_buffer;\r
-    pOutput_buf += (bits_in >> 3);\r
-    bit_buffer >>= (bits_in & ~7);\r
-    bits_in &= 7;\r
-  }\r
-\r
-#undef TDEFL_PUT_BITS_FAST\r
-\r
-  d->m_pOutput_buf = pOutput_buf;\r
-  d->m_bits_in = 0;\r
-  d->m_bit_buffer = 0;\r
-\r
-  while (bits_in)\r
-  {\r
-    mz_uint32 n = MZ_MIN(bits_in, 16);\r
-    TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);\r
-    bit_buffer >>= n;\r
-    bits_in -= n;\r
-  }\r
-\r
-  TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);\r
-\r
-  return (d->m_pOutput_buf < d->m_pOutput_buf_end);\r
-}\r
-#else\r
-static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)\r
-{\r
-  mz_uint flags;\r
-  mz_uint8 *pLZ_codes;\r
-\r
-  flags = 1;\r
-  for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1)\r
-  {\r
-    if (flags == 1)\r
-      flags = *pLZ_codes++ | 0x100;\r
-    if (flags & 1)\r
-    {\r
-      mz_uint sym, num_extra_bits;\r
-      mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3;\r
-\r
-      MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);\r
-      TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);\r
-      TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);\r
-\r
-      if (match_dist < 512)\r
-      {\r
-        sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist];\r
-      }\r
-      else\r
-      {\r
-        sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];\r
-      }\r
-      MZ_ASSERT(d->m_huff_code_sizes[1][sym]);\r
-      TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);\r
-      TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);\r
-    }\r
-    else\r
-    {\r
-      mz_uint lit = *pLZ_codes++;\r
-      MZ_ASSERT(d->m_huff_code_sizes[0][lit]);\r
-      TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);\r
-    }\r
-  }\r
-\r
-  TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);\r
-\r
-  return (d->m_pOutput_buf < d->m_pOutput_buf_end);\r
-}\r
-#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS\r
-\r
-static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block)\r
-{\r
-  if (static_block)\r
-    tdefl_start_static_block(d);\r
-  else\r
-    tdefl_start_dynamic_block(d);\r
-  return tdefl_compress_lz_codes(d);\r
-}\r
-\r
-static int tdefl_flush_block(tdefl_compressor *d, int flush)\r
-{\r
-  mz_uint saved_bit_buf, saved_bits_in;\r
-  mz_uint8 *pSaved_output_buf;\r
-  mz_bool comp_block_succeeded = MZ_FALSE;\r
-  int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;\r
-  mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf;\r
-\r
-  d->m_pOutput_buf = pOutput_buf_start;\r
-  d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;\r
-\r
-  MZ_ASSERT(!d->m_output_flush_remaining);\r
-  d->m_output_flush_ofs = 0;\r
-  d->m_output_flush_remaining = 0;\r
-\r
-  *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);\r
-  d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);\r
-\r
-  if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index))\r
-  {\r
-    TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8);\r
-  }\r
-\r
-  TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);\r
-\r
-  pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in;\r
-\r
-  if (!use_raw_block)\r
-    comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48));\r
-\r
-  // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.\r
-  if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) &&\r
-       ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) )\r
-  {\r
-    mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;\r
-    TDEFL_PUT_BITS(0, 2);\r
-    if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }\r
-    for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF)\r
-    {\r
-      TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);\r
-    }\r
-    for (i = 0; i < d->m_total_lz_bytes; ++i)\r
-    {\r
-      TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8);\r
-    }\r
-  }\r
-  // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.\r
-  else if (!comp_block_succeeded)\r
-  {\r
-    d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;\r
-    tdefl_compress_block(d, MZ_TRUE);\r
-  }\r
-\r
-  if (flush)\r
-  {\r
-    if (flush == TDEFL_FINISH)\r
-    {\r
-      if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }\r
-      if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } }\r
-    }\r
-    else\r
-    {\r
-      mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); }\r
-    }\r
-  }\r
-\r
-  MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);\r
-\r
-  memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);\r
-  memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);\r
-\r
-  d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++;\r
-\r
-  if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0)\r
-  {\r
-    if (d->m_pPut_buf_func)\r
-    {\r
-      *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;\r
-      if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))\r
-        return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);\r
-    }\r
-    else if (pOutput_buf_start == d->m_output_buf)\r
-    {\r
-      int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));\r
-      memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy);\r
-      d->m_out_buf_ofs += bytes_to_copy;\r
-      if ((n -= bytes_to_copy) != 0)\r
-      {\r
-        d->m_output_flush_ofs = bytes_to_copy;\r
-        d->m_output_flush_remaining = n;\r
-      }\r
-    }\r
-    else\r
-    {\r
-      d->m_out_buf_ofs += n;\r
-    }\r
-  }\r
-\r
-  return d->m_output_flush_remaining;\r
-}\r
-\r
-#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES\r
-#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p)\r
-static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)\r
-{\r
-  mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;\r
-  mz_uint num_probes_left = d->m_max_probes[match_len >= 32];\r
-  const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q;\r
-  mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s);\r
-  MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;\r
-  for ( ; ; )\r
-  {\r
-    for ( ; ; )\r
-    {\r
-      if (--num_probes_left == 0) return;\r
-      #define TDEFL_PROBE \\r
-        next_probe_pos = d->m_next[probe_pos]; \\r
-        if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \\r
-        probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \\r
-        if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break;\r
-      TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;\r
-    }\r
-    if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32;\r
-    do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&\r
-                   (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );\r
-    if (!probe_len)\r
-    {\r
-      *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break;\r
-    }\r
-    else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len)\r
-    {\r
-      *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break;\r
-      c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);\r
-    }\r
-  }\r
-}\r
-#else\r
-static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)\r
-{\r
-  mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;\r
-  mz_uint num_probes_left = d->m_max_probes[match_len >= 32];\r
-  const mz_uint8 *s = d->m_dict + pos, *p, *q;\r
-  mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];\r
-  MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;\r
-  for ( ; ; )\r
-  {\r
-    for ( ; ; )\r
-    {\r
-      if (--num_probes_left == 0) return;\r
-      #define TDEFL_PROBE \\r
-        next_probe_pos = d->m_next[probe_pos]; \\r
-        if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \\r
-        probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \\r
-        if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;\r
-      TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE;\r
-    }\r
-    if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break;\r
-    if (probe_len > match_len)\r
-    {\r
-      *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return;\r
-      c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1];\r
-    }\r
-  }\r
-}\r
-#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES\r
-\r
-#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN\r
-static mz_bool tdefl_compress_fast(tdefl_compressor *d)\r
-{\r
-  // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio.\r
-  mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left;\r
-  mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;\r
-  mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;\r
-\r
-  while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size)))\r
-  {\r
-    const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;\r
-    mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;\r
-    mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);\r
-    d->m_src_buf_left -= num_bytes_to_process;\r
-    lookahead_size += num_bytes_to_process;\r
-\r
-    while (num_bytes_to_process)\r
-    {\r
-      mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);\r
-      memcpy(d->m_dict + dst_pos, d->m_pSrc, n);\r
-      if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))\r
-        memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));\r
-      d->m_pSrc += n;\r
-      dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;\r
-      num_bytes_to_process -= n;\r
-    }\r
-\r
-    dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);\r
-    if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break;\r
-\r
-    while (lookahead_size >= 4)\r
-    {\r
-      mz_uint cur_match_dist, cur_match_len = 1;\r
-      mz_uint8 *pCur_dict = d->m_dict + cur_pos;\r
-      mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;\r
-      mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK;\r
-      mz_uint probe_pos = d->m_hash[hash];\r
-      d->m_hash[hash] = (mz_uint16)lookahead_pos;\r
-\r
-      if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram))\r
-      {\r
-        const mz_uint16 *p = (const mz_uint16 *)pCur_dict;\r
-        const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);\r
-        mz_uint32 probe_len = 32;\r
-        do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&\r
-          (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );\r
-        cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);\r
-        if (!probe_len)\r
-          cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;\r
-\r
-        if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)))\r
-        {\r
-          cur_match_len = 1;\r
-          *pLZ_code_buf++ = (mz_uint8)first_trigram;\r
-          *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);\r
-          d->m_huff_count[0][(mz_uint8)first_trigram]++;\r
-        }\r
-        else\r
-        {\r
-          mz_uint32 s0, s1;\r
-          cur_match_len = MZ_MIN(cur_match_len, lookahead_size);\r
-\r
-          MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE));\r
-\r
-          cur_match_dist--;\r
-\r
-          pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);\r
-          *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;\r
-          pLZ_code_buf += 3;\r
-          *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);\r
-\r
-          s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];\r
-          s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];\r
-          d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;\r
-\r
-          d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++;\r
-        }\r
-      }\r
-      else\r
-      {\r
-        *pLZ_code_buf++ = (mz_uint8)first_trigram;\r
-        *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);\r
-        d->m_huff_count[0][(mz_uint8)first_trigram]++;\r
-      }\r
-\r
-      if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }\r
-\r
-      total_lz_bytes += cur_match_len;\r
-      lookahead_pos += cur_match_len;\r
-      dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);\r
-      cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;\r
-      MZ_ASSERT(lookahead_size >= cur_match_len);\r
-      lookahead_size -= cur_match_len;\r
-\r
-      if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])\r
-      {\r
-        int n;\r
-        d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;\r
-        d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;\r
-        if ((n = tdefl_flush_block(d, 0)) != 0)\r
-          return (n < 0) ? MZ_FALSE : MZ_TRUE;\r
-        total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;\r
-      }\r
-    }\r
-\r
-    while (lookahead_size)\r
-    {\r
-      mz_uint8 lit = d->m_dict[cur_pos];\r
-\r
-      total_lz_bytes++;\r
-      *pLZ_code_buf++ = lit;\r
-      *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);\r
-      if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }\r
-\r
-      d->m_huff_count[0][lit]++;\r
-\r
-      lookahead_pos++;\r
-      dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);\r
-      cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;\r
-      lookahead_size--;\r
-\r
-      if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])\r
-      {\r
-        int n;\r
-        d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;\r
-        d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;\r
-        if ((n = tdefl_flush_block(d, 0)) != 0)\r
-          return (n < 0) ? MZ_FALSE : MZ_TRUE;\r
-        total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;\r
-      }\r
-    }\r
-  }\r
-\r
-  d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;\r
-  d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;\r
-  return MZ_TRUE;\r
-}\r
-#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN\r
-\r
-static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit)\r
-{\r
-  d->m_total_lz_bytes++;\r
-  *d->m_pLZ_code_buf++ = lit;\r
-  *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }\r
-  d->m_huff_count[0][lit]++;\r
-}\r
-\r
-static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist)\r
-{\r
-  mz_uint32 s0, s1;\r
-\r
-  MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE));\r
-\r
-  d->m_total_lz_bytes += match_len;\r
-\r
-  d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);\r
-\r
-  match_dist -= 1;\r
-  d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);\r
-  d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3;\r
-\r
-  *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }\r
-\r
-  s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];\r
-  d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;\r
-\r
-  if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;\r
-}\r
-\r
-static mz_bool tdefl_compress_normal(tdefl_compressor *d)\r
-{\r
-  const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left;\r
-  tdefl_flush flush = d->m_flush;\r
-\r
-  while ((src_buf_left) || ((flush) && (d->m_lookahead_size)))\r
-  {\r
-    mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;\r
-    // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.\r
-    if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1))\r
-    {\r
-      mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;\r
-      mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];\r
-      mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);\r
-      const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;\r
-      src_buf_left -= num_bytes_to_process;\r
-      d->m_lookahead_size += num_bytes_to_process;\r
-      while (pSrc != pSrc_end)\r
-      {\r
-        mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;\r
-        hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);\r
-        d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);\r
-        dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++;\r
-      }\r
-    }\r
-    else\r
-    {\r
-      while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))\r
-      {\r
-        mz_uint8 c = *pSrc++;\r
-        mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;\r
-        src_buf_left--;\r
-        d->m_dict[dst_pos] = c;\r
-        if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))\r
-          d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;\r
-        if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN)\r
-        {\r
-          mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;\r
-          mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);\r
-          d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);\r
-        }\r
-      }\r
-    }\r
-    d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);\r
-    if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))\r
-      break;\r
-\r
-    // Simple lazy/greedy parsing state machine.\r
-    len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;\r
-    if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS))\r
-    {\r
-      if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))\r
-      {\r
-        mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];\r
-        cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; }\r
-        if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1;\r
-      }\r
-    }\r
-    else\r
-    {\r
-      tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len);\r
-    }\r
-    if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5)))\r
-    {\r
-      cur_match_dist = cur_match_len = 0;\r
-    }\r
-    if (d->m_saved_match_len)\r
-    {\r
-      if (cur_match_len > d->m_saved_match_len)\r
-      {\r
-        tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);\r
-        if (cur_match_len >= 128)\r
-        {\r
-          tdefl_record_match(d, cur_match_len, cur_match_dist);\r
-          d->m_saved_match_len = 0; len_to_move = cur_match_len;\r
-        }\r
-        else\r
-        {\r
-          d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;\r
-        }\r
-      }\r
-      else\r
-      {\r
-        tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);\r
-        len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0;\r
-      }\r
-    }\r
-    else if (!cur_match_dist)\r
-      tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);\r
-    else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128))\r
-    {\r
-      tdefl_record_match(d, cur_match_len, cur_match_dist);\r
-      len_to_move = cur_match_len;\r
-    }\r
-    else\r
-    {\r
-      d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;\r
-    }\r
-    // Move the lookahead forward by len_to_move bytes.\r
-    d->m_lookahead_pos += len_to_move;\r
-    MZ_ASSERT(d->m_lookahead_size >= len_to_move);\r
-    d->m_lookahead_size -= len_to_move;\r
-    d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE);\r
-    // Check if it's time to flush the current LZ codes to the internal output buffer.\r
-    if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||\r
-         ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) )\r
-    {\r
-      int n;\r
-      d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;\r
-      if ((n = tdefl_flush_block(d, 0)) != 0)\r
-        return (n < 0) ? MZ_FALSE : MZ_TRUE;\r
-    }\r
-  }\r
-\r
-  d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;\r
-  return MZ_TRUE;\r
-}\r
-\r
-static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d)\r
-{\r
-  if (d->m_pIn_buf_size)\r
-  {\r
-    *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;\r
-  }\r
-\r
-  if (d->m_pOut_buf_size)\r
-  {\r
-    size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining);\r
-    memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n);\r
-    d->m_output_flush_ofs += (mz_uint)n;\r
-    d->m_output_flush_remaining -= (mz_uint)n;\r
-    d->m_out_buf_ofs += n;\r
-\r
-    *d->m_pOut_buf_size = d->m_out_buf_ofs;\r
-  }\r
-\r
-  return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;\r
-}\r
-\r
-tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush)\r
-{\r
-  if (!d)\r
-  {\r
-    if (pIn_buf_size) *pIn_buf_size = 0;\r
-    if (pOut_buf_size) *pOut_buf_size = 0;\r
-    return TDEFL_STATUS_BAD_PARAM;\r
-  }\r
-\r
-  d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size;\r
-  d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size;\r
-  d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;\r
-  d->m_out_buf_ofs = 0;\r
-  d->m_flush = flush;\r
-\r
-  if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||\r
-        (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) )\r
-  {\r
-    if (pIn_buf_size) *pIn_buf_size = 0;\r
-    if (pOut_buf_size) *pOut_buf_size = 0;\r
-    return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);\r
-  }\r
-  d->m_wants_to_finish |= (flush == TDEFL_FINISH);\r
-\r
-  if ((d->m_output_flush_remaining) || (d->m_finished))\r
-    return (d->m_prev_return_status = tdefl_flush_output_buffer(d));\r
-\r
-#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN\r
-  if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&\r
-      ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&\r
-      ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0))\r
-  {\r
-    if (!tdefl_compress_fast(d))\r
-      return d->m_prev_return_status;\r
-  }\r
-  else\r
-#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN\r
-  {\r
-    if (!tdefl_compress_normal(d))\r
-      return d->m_prev_return_status;\r
-  }\r
-\r
-  if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf))\r
-    d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf);\r
-\r
-  if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining))\r
-  {\r
-    if (tdefl_flush_block(d, flush) < 0)\r
-      return d->m_prev_return_status;\r
-    d->m_finished = (flush == TDEFL_FINISH);\r
-    if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; }\r
-  }\r
-\r
-  return (d->m_prev_return_status = tdefl_flush_output_buffer(d));\r
-}\r
-\r
-tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush)\r
-{\r
-  MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);\r
-}\r
-\r
-tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)\r
-{\r
-  d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user;\r
-  d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;\r
-  d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;\r
-  if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash);\r
-  d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;\r
-  d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;\r
-  d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8;\r
-  d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY;\r
-  d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1;\r
-  d->m_pIn_buf = NULL; d->m_pOut_buf = NULL;\r
-  d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL;\r
-  d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0;\r
-  memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);\r
-  memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);\r
-  return TDEFL_STATUS_OKAY;\r
-}\r
-\r
-tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d)\r
-{\r
-  return d->m_prev_return_status;\r
-}\r
-\r
-mz_uint32 tdefl_get_adler32(tdefl_compressor *d)\r
-{\r
-  return d->m_adler32;\r
-}\r
-\r
-mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)\r
-{\r
-  tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;\r
-  pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE;\r
-  succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY);\r
-  succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE);\r
-  MZ_FREE(pComp); return succeeded;\r
-}\r
-\r
-typedef struct\r
-{\r
-  size_t m_size, m_capacity;\r
-  mz_uint8 *m_pBuf;\r
-  mz_bool m_expandable;\r
-} tdefl_output_buffer;\r
-\r
-static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser)\r
-{\r
-  tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;\r
-  size_t new_size = p->m_size + len;\r
-  if (new_size > p->m_capacity)\r
-  {\r
-    size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE;\r
-    do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity);\r
-    pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE;\r
-    p->m_pBuf = pNew_buf; p->m_capacity = new_capacity;\r
-  }\r
-  memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size;\r
-  return MZ_TRUE;\r
-}\r
-\r
-void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)\r
-{\r
-  tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);\r
-  if (!pOut_len) return MZ_FALSE; else *pOut_len = 0;\r
-  out_buf.m_expandable = MZ_TRUE;\r
-  if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL;\r
-  *pOut_len = out_buf.m_size; return out_buf.m_pBuf;\r
-}\r
-\r
-size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)\r
-{\r
-  tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);\r
-  if (!pOut_buf) return 0;\r
-  out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len;\r
-  if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0;\r
-  return out_buf.m_size;\r
-}\r
-\r
-#ifndef MINIZ_NO_ZLIB_APIS\r
-static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32,  16, 32, 128, 256,  512, 768, 1500 };\r
-\r
-// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files).\r
-mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy)\r
-{\r
-  mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);\r
-  if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;\r
-\r
-  if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;\r
-  else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES;\r
-  else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK;\r
-  else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;\r
-  else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES;\r
-\r
-  return comp_flags;\r
-}\r
-#endif //MINIZ_NO_ZLIB_APIS\r
-\r
-#ifdef _MSC_VER\r
-#pragma warning (push)\r
-#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal)\r
-#endif\r
-\r
-// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at\r
-// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.\r
-// This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck.\r
-void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip)\r
-{\r
-  // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined.\r
-  static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32,  16, 32, 128, 256,  512, 768, 1500 };\r
-  tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0;\r
-  if (!pComp) return NULL;\r
-  MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; }\r
-  // write dummy header\r
-  for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf);\r
-  // compress image data\r
-  tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);\r
-  for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); }\r
-  if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }\r
-  // write real header\r
-  *pLen_out = out_buf.m_size-41;\r
-  {\r
-    static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};\r
-    mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,\r
-      0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,chans[num_chans],0,0,0,0,0,0,0,\r
-      (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54};\r
-    c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24);\r
-    memcpy(out_buf.m_pBuf, pnghdr, 41);\r
-  }\r
-  // write footer (IDAT CRC-32, followed by IEND chunk)\r
-  if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }\r
-  c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24);\r
-  // compute final size of file, grab compressed data buffer and return\r
-  *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf;\r
-}\r
-void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out)\r
-{\r
-  // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out)\r
-  return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE);\r
-}\r
-\r
-#ifdef _MSC_VER\r
-#pragma warning (pop)\r
-#endif\r
-\r
-// ------------------- .ZIP archive reading\r
-\r
-#ifndef MINIZ_NO_ARCHIVE_APIS\r
-\r
-#ifdef MINIZ_NO_STDIO\r
-  #define MZ_FILE void *\r
-#else\r
-  #include <stdio.h>\r
-  #include <sys/stat.h>\r
-\r
-  #if defined(_MSC_VER) || defined(__MINGW64__)\r
-    static FILE *mz_fopen(const char *pFilename, const char *pMode)\r
-    {\r
-      FILE* pFile = NULL;\r
-      fopen_s(&pFile, pFilename, pMode);\r
-      return pFile;\r
-    }\r
-    static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream)\r
-    {\r
-      FILE* pFile = NULL;\r
-      if (freopen_s(&pFile, pPath, pMode, pStream))\r
-        return NULL;\r
-      return pFile;\r
-    }\r
-    #ifndef MINIZ_NO_TIME\r
-      #include <sys/utime.h>\r
-    #endif\r
-    #define MZ_FILE FILE\r
-    #define MZ_FOPEN mz_fopen\r
-    #define MZ_FCLOSE fclose\r
-    #define MZ_FREAD fread\r
-    #define MZ_FWRITE fwrite\r
-    #define MZ_FTELL64 _ftelli64\r
-    #define MZ_FSEEK64 _fseeki64\r
-    #define MZ_FILE_STAT_STRUCT _stat\r
-    #define MZ_FILE_STAT _stat\r
-    #define MZ_FFLUSH fflush\r
-    #define MZ_FREOPEN mz_freopen\r
-    #define MZ_DELETE_FILE remove\r
-  #elif defined(__MINGW32__)\r
-    #ifndef MINIZ_NO_TIME\r
-      #include <sys/utime.h>\r
-    #endif\r
-    #define MZ_FILE FILE\r
-    #define MZ_FOPEN(f, m) fopen(f, m)\r
-    #define MZ_FCLOSE fclose\r
-    #define MZ_FREAD fread\r
-    #define MZ_FWRITE fwrite\r
-    #define MZ_FTELL64 ftello64\r
-    #define MZ_FSEEK64 fseeko64\r
-    #define MZ_FILE_STAT_STRUCT _stat\r
-    #define MZ_FILE_STAT _stat\r
-    #define MZ_FFLUSH fflush\r
-    #define MZ_FREOPEN(f, m, s) freopen(f, m, s)\r
-    #define MZ_DELETE_FILE remove\r
-  #elif defined(__TINYC__)\r
-    #ifndef MINIZ_NO_TIME\r
-      #include <sys/utime.h>\r
-    #endif\r
-    #define MZ_FILE FILE\r
-    #define MZ_FOPEN(f, m) fopen(f, m)\r
-    #define MZ_FCLOSE fclose\r
-    #define MZ_FREAD fread\r
-    #define MZ_FWRITE fwrite\r
-    #define MZ_FTELL64 ftell\r
-    #define MZ_FSEEK64 fseek\r
-    #define MZ_FILE_STAT_STRUCT stat\r
-    #define MZ_FILE_STAT stat\r
-    #define MZ_FFLUSH fflush\r
-    #define MZ_FREOPEN(f, m, s) freopen(f, m, s)\r
-    #define MZ_DELETE_FILE remove\r
-  #elif defined(__GNUC__) && _LARGEFILE64_SOURCE\r
-    #ifndef MINIZ_NO_TIME\r
-      #include <utime.h>\r
-    #endif\r
-    #define MZ_FILE FILE\r
-    #define MZ_FOPEN(f, m) fopen64(f, m)\r
-    #define MZ_FCLOSE fclose\r
-    #define MZ_FREAD fread\r
-    #define MZ_FWRITE fwrite\r
-    #define MZ_FTELL64 ftello64\r
-    #define MZ_FSEEK64 fseeko64\r
-    #define MZ_FILE_STAT_STRUCT stat64\r
-    #define MZ_FILE_STAT stat64\r
-    #define MZ_FFLUSH fflush\r
-    #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)\r
-    #define MZ_DELETE_FILE remove\r
-  #else\r
-    #ifndef MINIZ_NO_TIME\r
-      #include <utime.h>\r
-    #endif\r
-    #define MZ_FILE FILE\r
-    #define MZ_FOPEN(f, m) fopen(f, m)\r
-    #define MZ_FCLOSE fclose\r
-    #define MZ_FREAD fread\r
-    #define MZ_FWRITE fwrite\r
-    #define MZ_FTELL64 ftello\r
-    #define MZ_FSEEK64 fseeko\r
-    #define MZ_FILE_STAT_STRUCT stat\r
-    #define MZ_FILE_STAT stat\r
-    #define MZ_FFLUSH fflush\r
-    #define MZ_FREOPEN(f, m, s) freopen(f, m, s)\r
-    #define MZ_DELETE_FILE remove\r
-  #endif // #ifdef _MSC_VER\r
-#endif // #ifdef MINIZ_NO_STDIO\r
-\r
-#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))\r
-\r
-// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff.\r
-enum\r
-{\r
-  // ZIP archive identifiers and record sizes\r
-  MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,\r
-  MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,\r
-  // Central directory header record offsets\r
-  MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8,\r
-  MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16,\r
-  MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,\r
-  MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,\r
-  // Local directory header offsets\r
-  MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10,\r
-  MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,\r
-  MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,\r
-  // End of central directory offsets\r
-  MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,\r
-  MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,\r
-};\r
-\r
-typedef struct\r
-{\r
-  void *m_p;\r
-  size_t m_size, m_capacity;\r
-  mz_uint m_element_size;\r
-} mz_zip_array;\r
-\r
-struct mz_zip_internal_state_tag\r
-{\r
-  mz_zip_array m_central_dir;\r
-  mz_zip_array m_central_dir_offsets;\r
-  mz_zip_array m_sorted_central_dir_offsets;\r
-  MZ_FILE *m_pFile;\r
-  void *m_pMem;\r
-  size_t m_mem_size;\r
-  size_t m_mem_capacity;\r
-};\r
-\r
-#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size\r
-#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index]\r
-\r
-static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray)\r
-{\r
-  pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);\r
-  memset(pArray, 0, sizeof(mz_zip_array));\r
-}\r
-\r
-static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing)\r
-{\r
-  void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;\r
-  if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; }\r
-  if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE;\r
-  pArray->m_p = pNew_p; pArray->m_capacity = new_capacity;\r
-  return MZ_TRUE;\r
-}\r
-\r
-static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing)\r
-{\r
-  if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; }\r
-  return MZ_TRUE;\r
-}\r
-\r
-static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing)\r
-{\r
-  if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; }\r
-  pArray->m_size = new_size;\r
-  return MZ_TRUE;\r
-}\r
-\r
-static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n)\r
-{\r
-  return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);\r
-}\r
-\r
-static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n)\r
-{\r
-  size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE;\r
-  memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size);\r
-  return MZ_TRUE;\r
-}\r
-\r
-#ifndef MINIZ_NO_TIME\r
-static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date)\r
-{\r
-  struct tm tm;\r
-  memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1;\r
-  tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31;\r
-  tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62;\r
-  return mktime(&tm);\r
-}\r
-\r
-static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)\r
-{\r
-#ifdef _MSC_VER\r
-  struct tm tm_struct;\r
-  struct tm *tm = &tm_struct;\r
-  errno_t err = localtime_s(tm, &time);\r
-  if (err)\r
-  {\r
-    *pDOS_date = 0; *pDOS_time = 0;\r
-    return;\r
-  }\r
-#else\r
-  struct tm *tm = localtime(&time);\r
-#endif\r
-  *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1));\r
-  *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday);\r
-}\r
-#endif\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)\r
-{\r
-#ifdef MINIZ_NO_TIME\r
-  (void)pFilename; *pDOS_date = *pDOS_time = 0;\r
-#else\r
-  struct MZ_FILE_STAT_STRUCT file_stat;\r
-  // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.\r
-  if (MZ_FILE_STAT(pFilename, &file_stat) != 0)\r
-    return MZ_FALSE;\r
-  mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);\r
-#endif // #ifdef MINIZ_NO_TIME\r
-  return MZ_TRUE;\r
-}\r
-\r
-#ifndef MINIZ_NO_TIME\r
-static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time)\r
-{\r
-  struct utimbuf t; t.actime = access_time; t.modtime = modified_time;\r
-  return !utime(pFilename, &t);\r
-}\r
-#endif // #ifndef MINIZ_NO_TIME\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags)\r
-{\r
-  (void)flags;\r
-  if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))\r
-    return MZ_FALSE;\r
-\r
-  if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;\r
-  if (!pZip->m_pFree) pZip->m_pFree = def_free_func;\r
-  if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;\r
-\r
-  pZip->m_zip_mode = MZ_ZIP_MODE_READING;\r
-  pZip->m_archive_size = 0;\r
-  pZip->m_central_directory_file_ofs = 0;\r
-  pZip->m_total_files = 0;\r
-\r
-  if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))\r
-    return MZ_FALSE;\r
-  memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));\r
-  MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));\r
-  MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));\r
-  MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));\r
-  return MZ_TRUE;\r
-}\r
-\r
-static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index)\r
-{\r
-  const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;\r
-  const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));\r
-  mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);\r
-  mz_uint8 l = 0, r = 0;\r
-  pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;\r
-  pE = pL + MZ_MIN(l_len, r_len);\r
-  while (pL < pE)\r
-  {\r
-    if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))\r
-      break;\r
-    pL++; pR++;\r
-  }\r
-  return (pL == pE) ? (l_len < r_len) : (l < r);\r
-}\r
-\r
-#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END\r
-\r
-// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.)\r
-static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip)\r
-{\r
-  mz_zip_internal_state *pState = pZip->m_pState;\r
-  const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;\r
-  const mz_zip_array *pCentral_dir = &pState->m_central_dir;\r
-  mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);\r
-  const int size = pZip->m_total_files;\r
-  int start = (size - 2) >> 1, end;\r
-  while (start >= 0)\r
-  {\r
-    int child, root = start;\r
-    for ( ; ; )\r
-    {\r
-      if ((child = (root << 1) + 1) >= size)\r
-        break;\r
-      child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])));\r
-      if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))\r
-        break;\r
-      MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child;\r
-    }\r
-    start--;\r
-  }\r
-\r
-  end = size - 1;\r
-  while (end > 0)\r
-  {\r
-    int child, root = 0;\r
-    MZ_SWAP_UINT32(pIndices[end], pIndices[0]);\r
-    for ( ; ; )\r
-    {\r
-      if ((child = (root << 1) + 1) >= end)\r
-        break;\r
-      child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]));\r
-      if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))\r
-        break;\r
-      MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child;\r
-    }\r
-    end--;\r
-  }\r
-}\r
-\r
-static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags)\r
-{\r
-  mz_uint cdir_size, num_this_disk, cdir_disk_index;\r
-  mz_uint64 cdir_ofs;\r
-  mz_int64 cur_file_ofs;\r
-  const mz_uint8 *p;\r
-  mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32;\r
-  mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);\r
-  // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there.\r
-  if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)\r
-    return MZ_FALSE;\r
-  // Find the end of central directory record by scanning the file from the end towards the beginning.\r
-  cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);\r
-  for ( ; ; )\r
-  {\r
-    int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);\r
-    if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)\r
-      return MZ_FALSE;\r
-    for (i = n - 4; i >= 0; --i)\r
-      if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)\r
-        break;\r
-    if (i >= 0)\r
-    {\r
-      cur_file_ofs += i;\r
-      break;\r
-    }\r
-    if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))\r
-      return MZ_FALSE;\r
-    cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);\r
-  }\r
-  // Read and verify the end of central directory record.\r
-  if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)\r
-    return MZ_FALSE;\r
-  if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||\r
-      ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))\r
-    return MZ_FALSE;\r
-\r
-  num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);\r
-  cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);\r
-  if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1)))\r
-    return MZ_FALSE;\r
-\r
-  if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)\r
-    return MZ_FALSE;\r
-\r
-  cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);\r
-  if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)\r
-    return MZ_FALSE;\r
-\r
-  pZip->m_central_directory_file_ofs = cdir_ofs;\r
-\r
-  if (pZip->m_total_files)\r
-  {\r
-     mz_uint i, n;\r
-\r
-    // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices.\r
-    if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) ||\r
-        (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE)))\r
-      return MZ_FALSE;\r
-\r
-    if (sort_central_dir)\r
-    {\r
-      if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE))\r
-        return MZ_FALSE;\r
-    }\r
-\r
-    if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size)\r
-      return MZ_FALSE;\r
-\r
-    // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported).\r
-    p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;\r
-    for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i)\r
-    {\r
-      mz_uint total_header_size, comp_size, decomp_size, disk_index;\r
-      if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))\r
-        return MZ_FALSE;\r
-      MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);\r
-      if (sort_central_dir)\r
-        MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i;\r
-      comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);\r
-      decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);\r
-      if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF))\r
-        return MZ_FALSE;\r
-      disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);\r
-      if ((disk_index != num_this_disk) && (disk_index != 1))\r
-        return MZ_FALSE;\r
-      if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)\r
-        return MZ_FALSE;\r
-      if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n)\r
-        return MZ_FALSE;\r
-      n -= total_header_size; p += total_header_size;\r
-    }\r
-  }\r
-\r
-  if (sort_central_dir)\r
-    mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);\r
-\r
-  return MZ_TRUE;\r
-}\r
-\r
-mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags)\r
-{\r
-  if ((!pZip) || (!pZip->m_pRead))\r
-    return MZ_FALSE;\r
-  if (!mz_zip_reader_init_internal(pZip, flags))\r
-    return MZ_FALSE;\r
-  pZip->m_archive_size = size;\r
-  if (!mz_zip_reader_read_central_dir(pZip, flags))\r
-  {\r
-    mz_zip_reader_end(pZip);\r
-    return MZ_FALSE;\r
-  }\r
-  return MZ_TRUE;\r
-}\r
-\r
-static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)\r
-{\r
-  mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;\r
-  size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);\r
-  memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);\r
-  return s;\r
-}\r
-\r
-mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags)\r
-{\r
-  if (!mz_zip_reader_init_internal(pZip, flags))\r
-    return MZ_FALSE;\r
-  pZip->m_archive_size = size;\r
-  pZip->m_pRead = mz_zip_mem_read_func;\r
-  pZip->m_pIO_opaque = pZip;\r
-#ifdef __cplusplus\r
-  pZip->m_pState->m_pMem = const_cast<void *>(pMem);\r
-#else\r
-  pZip->m_pState->m_pMem = (void *)pMem;\r
-#endif\r
-  pZip->m_pState->m_mem_size = size;\r
-  if (!mz_zip_reader_read_central_dir(pZip, flags))\r
-  {\r
-    mz_zip_reader_end(pZip);\r
-    return MZ_FALSE;\r
-  }\r
-  return MZ_TRUE;\r
-}\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)\r
-{\r
-  mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;\r
-  mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);\r
-  if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))\r
-    return 0;\r
-  return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);\r
-}\r
-\r
-mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags)\r
-{\r
-  mz_uint64 file_size;\r
-  MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");\r
-  if (!pFile)\r
-    return MZ_FALSE;\r
-  if (MZ_FSEEK64(pFile, 0, SEEK_END))\r
-  {\r
-    MZ_FCLOSE(pFile);\r
-    return MZ_FALSE;\r
-  }\r
-  file_size = MZ_FTELL64(pFile);\r
-  if (!mz_zip_reader_init_internal(pZip, flags))\r
-  {\r
-    MZ_FCLOSE(pFile);\r
-    return MZ_FALSE;\r
-  }\r
-  pZip->m_pRead = mz_zip_file_read_func;\r
-  pZip->m_pIO_opaque = pZip;\r
-  pZip->m_pState->m_pFile = pFile;\r
-  pZip->m_archive_size = file_size;\r
-  if (!mz_zip_reader_read_central_dir(pZip, flags))\r
-  {\r
-    mz_zip_reader_end(pZip);\r
-    return MZ_FALSE;\r
-  }\r
-  return MZ_TRUE;\r
-}\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip)\r
-{\r
-  return pZip ? pZip->m_total_files : 0;\r
-}\r
-\r
-static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index)\r
-{\r
-  if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))\r
-    return NULL;\r
-  return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));\r
-}\r
-\r
-mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index)\r
-{\r
-  mz_uint m_bit_flag;\r
-  const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);\r
-  if (!p)\r
-    return MZ_FALSE;\r
-  m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);\r
-  return (m_bit_flag & 1);\r
-}\r
-\r
-mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index)\r
-{\r
-  mz_uint filename_len, external_attr;\r
-  const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);\r
-  if (!p)\r
-    return MZ_FALSE;\r
-\r
-  // First see if the filename ends with a '/' character.\r
-  filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);\r
-  if (filename_len)\r
-  {\r
-    if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')\r
-      return MZ_TRUE;\r
-  }\r
-\r
-  // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct.\r
-  // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field.\r
-  // FIXME: Remove this check? Is it necessary - we already check the filename.\r
-  external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);\r
-  if ((external_attr & 0x10) != 0)\r
-    return MZ_TRUE;\r
-\r
-  return MZ_FALSE;\r
-}\r
-\r
-mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat)\r
-{\r
-  mz_uint n;\r
-  const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);\r
-  if ((!p) || (!pStat))\r
-    return MZ_FALSE;\r
-\r
-  // Unpack the central directory record.\r
-  pStat->m_file_index = file_index;\r
-  pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);\r
-  pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);\r
-  pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);\r
-  pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);\r
-  pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);\r
-#ifndef MINIZ_NO_TIME\r
-  pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));\r
-#endif\r
-  pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);\r
-  pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);\r
-  pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);\r
-  pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);\r
-  pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);\r
-  pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);\r
-\r
-  // Copy as much of the filename and comment as possible.\r
-  n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);\r
-  memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0';\r
-\r
-  n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);\r
-  pStat->m_comment_size = n;\r
-  memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0';\r
-\r
-  return MZ_TRUE;\r
-}\r
-\r
-mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size)\r
-{\r
-  mz_uint n;\r
-  const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);\r
-  if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; }\r
-  n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);\r
-  if (filename_buf_size)\r
-  {\r
-    n = MZ_MIN(n, filename_buf_size - 1);\r
-    memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);\r
-    pFilename[n] = '\0';\r
-  }\r
-  return n + 1;\r
-}\r
-\r
-static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags)\r
-{\r
-  mz_uint i;\r
-  if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)\r
-    return 0 == memcmp(pA, pB, len);\r
-  for (i = 0; i < len; ++i)\r
-    if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))\r
-      return MZ_FALSE;\r
-  return MZ_TRUE;\r
-}\r
-\r
-static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len)\r
-{\r
-  const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;\r
-  mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);\r
-  mz_uint8 l = 0, r = 0;\r
-  pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;\r
-  pE = pL + MZ_MIN(l_len, r_len);\r
-  while (pL < pE)\r
-  {\r
-    if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))\r
-      break;\r
-    pL++; pR++;\r
-  }\r
-  return (pL == pE) ? (int)(l_len - r_len) : (l - r);\r
-}\r
-\r
-static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename)\r
-{\r
-  mz_zip_internal_state *pState = pZip->m_pState;\r
-  const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;\r
-  const mz_zip_array *pCentral_dir = &pState->m_central_dir;\r
-  mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);\r
-  const int size = pZip->m_total_files;\r
-  const mz_uint filename_len = (mz_uint)strlen(pFilename);\r
-  int l = 0, h = size - 1;\r
-  while (l <= h)\r
-  {\r
-    int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len);\r
-    if (!comp)\r
-      return file_index;\r
-    else if (comp < 0)\r
-      l = m + 1;\r
-    else\r
-      h = m - 1;\r
-  }\r
-  return -1;\r
-}\r
-\r
-int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags)\r
-{\r
-  mz_uint file_index; size_t name_len, comment_len;\r
-  if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))\r
-    return -1;\r
-  if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))\r
-    return mz_zip_reader_locate_file_binary_search(pZip, pName);\r
-  name_len = strlen(pName); if (name_len > 0xFFFF) return -1;\r
-  comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1;\r
-  for (file_index = 0; file_index < pZip->m_total_files; file_index++)\r
-  {\r
-    const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));\r
-    mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);\r
-    const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;\r
-    if (filename_len < name_len)\r
-      continue;\r
-    if (comment_len)\r
-    {\r
-      mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);\r
-      const char *pFile_comment = pFilename + filename_len + file_extra_len;\r
-      if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags)))\r
-        continue;\r
-    }\r
-    if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len))\r
-    {\r
-      int ofs = filename_len - 1;\r
-      do\r
-      {\r
-        if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':'))\r
-          break;\r
-      } while (--ofs >= 0);\r
-      ofs++;\r
-      pFilename += ofs; filename_len -= ofs;\r
-    }\r
-    if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))\r
-      return file_index;\r
-  }\r
-  return -1;\r
-}\r
-\r
-mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)\r
-{\r
-  int status = TINFL_STATUS_DONE;\r
-  mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;\r
-  mz_zip_archive_file_stat file_stat;\r
-  void *pRead_buf;\r
-  mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;\r
-  tinfl_decompressor inflator;\r
-\r
-  if ((buf_size) && (!pBuf))\r
-    return MZ_FALSE;\r
-\r
-  if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))\r
-    return MZ_FALSE;\r
-\r
-  // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes)\r
-  if (!file_stat.m_comp_size)\r
-    return MZ_TRUE;\r
-\r
-  // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers).\r
-  // I'm torn how to handle this case - should it fail instead?\r
-  if (mz_zip_reader_is_file_a_directory(pZip, file_index))\r
-    return MZ_TRUE;\r
-\r
-  // Encryption and patch files are not supported.\r
-  if (file_stat.m_bit_flag & (1 | 32))\r
-    return MZ_FALSE;\r
-\r
-  // This function only supports stored and deflate.\r
-  if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))\r
-    return MZ_FALSE;\r
-\r
-  // Ensure supplied output buffer is large enough.\r
-  needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size;\r
-  if (buf_size < needed_size)\r
-    return MZ_FALSE;\r
-\r
-  // Read and parse the local directory entry.\r
-  cur_file_ofs = file_stat.m_local_header_ofs;\r
-  if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)\r
-    return MZ_FALSE;\r
-  if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)\r
-    return MZ_FALSE;\r
-\r
-  cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);\r
-  if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)\r
-    return MZ_FALSE;\r
-\r
-  if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))\r
-  {\r
-    // The file is stored or the caller has requested the compressed data.\r
-    if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size)\r
-      return MZ_FALSE;\r
-    return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);\r
-  }\r
-\r
-  // Decompress the file either directly from memory or from a file input buffer.\r
-  tinfl_init(&inflator);\r
-\r
-  if (pZip->m_pState->m_pMem)\r
-  {\r
-    // Read directly from the archive in memory.\r
-    pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;\r
-    read_buf_size = read_buf_avail = file_stat.m_comp_size;\r
-    comp_remaining = 0;\r
-  }\r
-  else if (pUser_read_buf)\r
-  {\r
-    // Use a user provided read buffer.\r
-    if (!user_read_buf_size)\r
-      return MZ_FALSE;\r
-    pRead_buf = (mz_uint8 *)pUser_read_buf;\r
-    read_buf_size = user_read_buf_size;\r
-    read_buf_avail = 0;\r
-    comp_remaining = file_stat.m_comp_size;\r
-  }\r
-  else\r
-  {\r
-    // Temporarily allocate a read buffer.\r
-    read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE);\r
-#ifdef _MSC_VER\r
-    if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))\r
-#else\r
-    if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))\r
-#endif\r
-      return MZ_FALSE;\r
-    if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))\r
-      return MZ_FALSE;\r
-    read_buf_avail = 0;\r
-    comp_remaining = file_stat.m_comp_size;\r
-  }\r
-\r
-  do\r
-  {\r
-    size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);\r
-    if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))\r
-    {\r
-      read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);\r
-      if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)\r
-      {\r
-        status = TINFL_STATUS_FAILED;\r
-        break;\r
-      }\r
-      cur_file_ofs += read_buf_avail;\r
-      comp_remaining -= read_buf_avail;\r
-      read_buf_ofs = 0;\r
-    }\r
-    in_buf_size = (size_t)read_buf_avail;\r
-    status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));\r
-    read_buf_avail -= in_buf_size;\r
-    read_buf_ofs += in_buf_size;\r
-    out_buf_ofs += out_buf_size;\r
-  } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);\r
-\r
-  if (status == TINFL_STATUS_DONE)\r
-  {\r
-    // Make sure the entire file was decompressed, and check its CRC.\r
-    if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))\r
-      status = TINFL_STATUS_FAILED;\r
-  }\r
-\r
-  if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);\r
-\r
-  return status == TINFL_STATUS_DONE;\r
-}\r
-\r
-mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)\r
-{\r
-  int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);\r
-  if (file_index < 0)\r
-    return MZ_FALSE;\r
-  return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size);\r
-}\r
-\r
-mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags)\r
-{\r
-  return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0);\r
-}\r
-\r
-mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags)\r
-{\r
-  return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0);\r
-}\r
-\r
-void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags)\r
-{\r
-  mz_uint64 comp_size, uncomp_size, alloc_size;\r
-  const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);\r
-  void *pBuf;\r
-\r
-  if (pSize)\r
-    *pSize = 0;\r
-  if (!p)\r
-    return NULL;\r
-\r
-  comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);\r
-  uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);\r
-\r
-  alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;\r
-#ifdef _MSC_VER\r
-  if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))\r
-#else\r
-  if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))\r
-#endif\r
-    return NULL;\r
-  if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))\r
-    return NULL;\r
-\r
-  if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags))\r
-  {\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);\r
-    return NULL;\r
-  }\r
-\r
-  if (pSize) *pSize = (size_t)alloc_size;\r
-  return pBuf;\r
-}\r
-\r
-void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags)\r
-{\r
-  int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);\r
-  if (file_index < 0)\r
-  {\r
-    if (pSize) *pSize = 0;\r
-    return MZ_FALSE;\r
-  }\r
-  return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);\r
-}\r
-\r
-mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)\r
-{\r
-  int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT;\r
-  mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs;\r
-  mz_zip_archive_file_stat file_stat;\r
-  void *pRead_buf = NULL; void *pWrite_buf = NULL;\r
-  mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;\r
-\r
-  if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))\r
-    return MZ_FALSE;\r
-\r
-  // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes)\r
-  if (!file_stat.m_comp_size)\r
-    return MZ_TRUE;\r
-\r
-  // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers).\r
-  // I'm torn how to handle this case - should it fail instead?\r
-  if (mz_zip_reader_is_file_a_directory(pZip, file_index))\r
-    return MZ_TRUE;\r
-\r
-  // Encryption and patch files are not supported.\r
-  if (file_stat.m_bit_flag & (1 | 32))\r
-    return MZ_FALSE;\r
-\r
-  // This function only supports stored and deflate.\r
-  if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))\r
-    return MZ_FALSE;\r
-\r
-  // Read and parse the local directory entry.\r
-  cur_file_ofs = file_stat.m_local_header_ofs;\r
-  if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)\r
-    return MZ_FALSE;\r
-  if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)\r
-    return MZ_FALSE;\r
-\r
-  cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);\r
-  if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)\r
-    return MZ_FALSE;\r
-\r
-  // Decompress the file either directly from memory or from a file input buffer.\r
-  if (pZip->m_pState->m_pMem)\r
-  {\r
-    pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;\r
-    read_buf_size = read_buf_avail = file_stat.m_comp_size;\r
-    comp_remaining = 0;\r
-  }\r
-  else\r
-  {\r
-    read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE);\r
-    if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))\r
-      return MZ_FALSE;\r
-    read_buf_avail = 0;\r
-    comp_remaining = file_stat.m_comp_size;\r
-  }\r
-\r
-  if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))\r
-  {\r
-    // The file is stored or the caller has requested the compressed data.\r
-    if (pZip->m_pState->m_pMem)\r
-    {\r
-#ifdef _MSC_VER\r
-      if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF))\r
-#else\r
-      if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF))\r
-#endif\r
-        return MZ_FALSE;\r
-      if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)\r
-        status = TINFL_STATUS_FAILED;\r
-      else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))\r
-        file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size);\r
-      cur_file_ofs += file_stat.m_comp_size;\r
-      out_buf_ofs += file_stat.m_comp_size;\r
-      comp_remaining = 0;\r
-    }\r
-    else\r
-    {\r
-      while (comp_remaining)\r
-      {\r
-        read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);\r
-        if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)\r
-        {\r
-          status = TINFL_STATUS_FAILED;\r
-          break;\r
-        }\r
-\r
-        if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))\r
-          file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);\r
-\r
-        if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)\r
-        {\r
-          status = TINFL_STATUS_FAILED;\r
-          break;\r
-        }\r
-        cur_file_ofs += read_buf_avail;\r
-        out_buf_ofs += read_buf_avail;\r
-        comp_remaining -= read_buf_avail;\r
-      }\r
-    }\r
-  }\r
-  else\r
-  {\r
-    tinfl_decompressor inflator;\r
-    tinfl_init(&inflator);\r
-\r
-    if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE)))\r
-      status = TINFL_STATUS_FAILED;\r
-    else\r
-    {\r
-      do\r
-      {\r
-        mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));\r
-        size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));\r
-        if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))\r
-        {\r
-          read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);\r
-          if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)\r
-          {\r
-            status = TINFL_STATUS_FAILED;\r
-            break;\r
-          }\r
-          cur_file_ofs += read_buf_avail;\r
-          comp_remaining -= read_buf_avail;\r
-          read_buf_ofs = 0;\r
-        }\r
-\r
-        in_buf_size = (size_t)read_buf_avail;\r
-        status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);\r
-        read_buf_avail -= in_buf_size;\r
-        read_buf_ofs += in_buf_size;\r
-\r
-        if (out_buf_size)\r
-        {\r
-          if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size)\r
-          {\r
-            status = TINFL_STATUS_FAILED;\r
-            break;\r
-          }\r
-          file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);\r
-          if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size)\r
-          {\r
-            status = TINFL_STATUS_FAILED;\r
-            break;\r
-          }\r
-        }\r
-      } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT));\r
-    }\r
-  }\r
-\r
-  if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)))\r
-  {\r
-    // Make sure the entire file was decompressed, and check its CRC.\r
-    if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32))\r
-      status = TINFL_STATUS_FAILED;\r
-  }\r
-\r
-  if (!pZip->m_pState->m_pMem)\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);\r
-  if (pWrite_buf)\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);\r
-\r
-  return status == TINFL_STATUS_DONE;\r
-}\r
-\r
-mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)\r
-{\r
-  int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);\r
-  if (file_index < 0)\r
-    return MZ_FALSE;\r
-  return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags);\r
-}\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n)\r
-{\r
-  (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque);\r
-}\r
-\r
-mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags)\r
-{\r
-  mz_bool status;\r
-  mz_zip_archive_file_stat file_stat;\r
-  MZ_FILE *pFile;\r
-  if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))\r
-    return MZ_FALSE;\r
-  pFile = MZ_FOPEN(pDst_filename, "wb");\r
-  if (!pFile)\r
-    return MZ_FALSE;\r
-  status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags);\r
-  if (MZ_FCLOSE(pFile) == EOF)\r
-    return MZ_FALSE;\r
-#ifndef MINIZ_NO_TIME\r
-  if (status)\r
-    mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);\r
-#endif\r
-  return status;\r
-}\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-mz_bool mz_zip_reader_end(mz_zip_archive *pZip)\r
-{\r
-  if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))\r
-    return MZ_FALSE;\r
-\r
-  if (pZip->m_pState)\r
-  {\r
-    mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL;\r
-    mz_zip_array_clear(pZip, &pState->m_central_dir);\r
-    mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);\r
-    mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-    if (pState->m_pFile)\r
-    {\r
-      MZ_FCLOSE(pState->m_pFile);\r
-      pState->m_pFile = NULL;\r
-    }\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pState);\r
-  }\r
-  pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;\r
-\r
-  return MZ_TRUE;\r
-}\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags)\r
-{\r
-  int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);\r
-  if (file_index < 0)\r
-    return MZ_FALSE;\r
-  return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);\r
-}\r
-#endif\r
-\r
-// ------------------- .ZIP archive writing\r
-\r
-#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS\r
-\r
-static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); }\r
-static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); }\r
-#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))\r
-#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))\r
-\r
-mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size)\r
-{\r
-  if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))\r
-    return MZ_FALSE;\r
-\r
-  if (pZip->m_file_offset_alignment)\r
-  {\r
-    // Ensure user specified file offset alignment is a power of 2.\r
-    if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))\r
-      return MZ_FALSE;\r
-  }\r
-\r
-  if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;\r
-  if (!pZip->m_pFree) pZip->m_pFree = def_free_func;\r
-  if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;\r
-\r
-  pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;\r
-  pZip->m_archive_size = existing_size;\r
-  pZip->m_central_directory_file_ofs = 0;\r
-  pZip->m_total_files = 0;\r
-\r
-  if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))\r
-    return MZ_FALSE;\r
-  memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));\r
-  MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));\r
-  MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));\r
-  MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));\r
-  return MZ_TRUE;\r
-}\r
-\r
-static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)\r
-{\r
-  mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;\r
-  mz_zip_internal_state *pState = pZip->m_pState;\r
-  mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);\r
-#ifdef _MSC_VER\r
-  if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))\r
-#else\r
-  if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))\r
-#endif\r
-    return 0;\r
-  if (new_size > pState->m_mem_capacity)\r
-  {\r
-    void *pNew_block;\r
-    size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2;\r
-    if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))\r
-      return 0;\r
-    pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity;\r
-  }\r
-  memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);\r
-  pState->m_mem_size = (size_t)new_size;\r
-  return n;\r
-}\r
-\r
-mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size)\r
-{\r
-  pZip->m_pWrite = mz_zip_heap_write_func;\r
-  pZip->m_pIO_opaque = pZip;\r
-  if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))\r
-    return MZ_FALSE;\r
-  if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning)))\r
-  {\r
-    if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size)))\r
-    {\r
-      mz_zip_writer_end(pZip);\r
-      return MZ_FALSE;\r
-    }\r
-    pZip->m_pState->m_mem_capacity = initial_allocation_size;\r
-  }\r
-  return MZ_TRUE;\r
-}\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)\r
-{\r
-  mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;\r
-  mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);\r
-  if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))\r
-    return 0;\r
-  return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);\r
-}\r
-\r
-mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning)\r
-{\r
-  MZ_FILE *pFile;\r
-  pZip->m_pWrite = mz_zip_file_write_func;\r
-  pZip->m_pIO_opaque = pZip;\r
-  if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))\r
-    return MZ_FALSE;\r
-  if (NULL == (pFile = MZ_FOPEN(pFilename, "wb")))\r
-  {\r
-    mz_zip_writer_end(pZip);\r
-    return MZ_FALSE;\r
-  }\r
-  pZip->m_pState->m_pFile = pFile;\r
-  if (size_to_reserve_at_beginning)\r
-  {\r
-    mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf);\r
-    do\r
-    {\r
-      size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);\r
-      if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n)\r
-      {\r
-        mz_zip_writer_end(pZip);\r
-        return MZ_FALSE;\r
-      }\r
-      cur_ofs += n; size_to_reserve_at_beginning -= n;\r
-    } while (size_to_reserve_at_beginning);\r
-  }\r
-  return MZ_TRUE;\r
-}\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename)\r
-{\r
-  mz_zip_internal_state *pState;\r
-  if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))\r
-    return MZ_FALSE;\r
-  // No sense in trying to write to an archive that's already at the support max size\r
-  if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-\r
-  pState = pZip->m_pState;\r
-\r
-  if (pState->m_pFile)\r
-  {\r
-#ifdef MINIZ_NO_STDIO\r
-    pFilename; return MZ_FALSE;\r
-#else\r
-    // Archive is being read from stdio - try to reopen as writable.\r
-    if (pZip->m_pIO_opaque != pZip)\r
-      return MZ_FALSE;\r
-    if (!pFilename)\r
-      return MZ_FALSE;\r
-    pZip->m_pWrite = mz_zip_file_write_func;\r
-    if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile)))\r
-    {\r
-      // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it.\r
-      mz_zip_reader_end(pZip);\r
-      return MZ_FALSE;\r
-    }\r
-#endif // #ifdef MINIZ_NO_STDIO\r
-  }\r
-  else if (pState->m_pMem)\r
-  {\r
-    // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback.\r
-    if (pZip->m_pIO_opaque != pZip)\r
-      return MZ_FALSE;\r
-    pState->m_mem_capacity = pState->m_mem_size;\r
-    pZip->m_pWrite = mz_zip_heap_write_func;\r
-  }\r
-  // Archive is being read via a user provided read function - make sure the user has specified a write function too.\r
-  else if (!pZip->m_pWrite)\r
-    return MZ_FALSE;\r
-\r
-  // Start writing new files at the archive's current central directory location.\r
-  pZip->m_archive_size = pZip->m_central_directory_file_ofs;\r
-  pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;\r
-  pZip->m_central_directory_file_ofs = 0;\r
-\r
-  return MZ_TRUE;\r
-}\r
-\r
-mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags)\r
-{\r
-  return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0);\r
-}\r
-\r
-typedef struct\r
-{\r
-  mz_zip_archive *m_pZip;\r
-  mz_uint64 m_cur_archive_file_ofs;\r
-  mz_uint64 m_comp_size;\r
-} mz_zip_writer_add_state;\r
-\r
-static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser)\r
-{\r
-  mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;\r
-  if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len)\r
-    return MZ_FALSE;\r
-  pState->m_cur_archive_file_ofs += len;\r
-  pState->m_comp_size += len;\r
-  return MZ_TRUE;\r
-}\r
-\r
-static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date)\r
-{\r
-  (void)pZip;\r
-  memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);\r
-  return MZ_TRUE;\r
-}\r
-\r
-static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes)\r
-{\r
-  (void)pZip;\r
-  memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);\r
-  MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);\r
-  MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);\r
-  return MZ_TRUE;\r
-}\r
-\r
-static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes)\r
-{\r
-  mz_zip_internal_state *pState = pZip->m_pState;\r
-  mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;\r
-  size_t orig_central_dir_size = pState->m_central_dir.m_size;\r
-  mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];\r
-\r
-  // No zip64 support yet\r
-  if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-\r
-  if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes))\r
-    return MZ_FALSE;\r
-\r
-  if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||\r
-      (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) ||\r
-      (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) ||\r
-      (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) ||\r
-      (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1)))\r
-  {\r
-    // Try to push the central directory array back into its original state.\r
-    mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);\r
-    return MZ_FALSE;\r
-  }\r
-\r
-  return MZ_TRUE;\r
-}\r
-\r
-static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name)\r
-{\r
-  // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes.\r
-  if (*pArchive_name == '/')\r
-    return MZ_FALSE;\r
-  while (*pArchive_name)\r
-  {\r
-    if ((*pArchive_name == '\\') || (*pArchive_name == ':'))\r
-      return MZ_FALSE;\r
-    pArchive_name++;\r
-  }\r
-  return MZ_TRUE;\r
-}\r
-\r
-static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip)\r
-{\r
-  mz_uint32 n;\r
-  if (!pZip->m_file_offset_alignment)\r
-    return 0;\r
-  n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));\r
-  return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1);\r
-}\r
-\r
-static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n)\r
-{\r
-  char buf[4096];\r
-  memset(buf, 0, MZ_MIN(sizeof(buf), n));\r
-  while (n)\r
-  {\r
-    mz_uint32 s = MZ_MIN(sizeof(buf), n);\r
-    if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)\r
-      return MZ_FALSE;\r
-    cur_file_ofs += s; n -= s;\r
-  }\r
-  return MZ_TRUE;\r
-}\r
-\r
-mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32)\r
-{\r
-  mz_uint16 method = 0, dos_time = 0, dos_date = 0;\r
-  mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;\r
-  mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;\r
-  size_t archive_name_size;\r
-  mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];\r
-  tdefl_compressor *pComp = NULL;\r
-  mz_bool store_data_uncompressed;\r
-  mz_zip_internal_state *pState;\r
-\r
-  if ((int)level_and_flags < 0)\r
-    level_and_flags = MZ_DEFAULT_LEVEL;\r
-  level = level_and_flags & 0xF;\r
-  store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));\r
-\r
-  if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))\r
-    return MZ_FALSE;\r
-\r
-  pState = pZip->m_pState;\r
-\r
-  if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))\r
-    return MZ_FALSE;\r
-  // No zip64 support yet\r
-  if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-  if (!mz_zip_writer_validate_archive_name(pArchive_name))\r
-    return MZ_FALSE;\r
-\r
-#ifndef MINIZ_NO_TIME\r
-  {\r
-    time_t cur_time; time(&cur_time);\r
-    mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);\r
-  }\r
-#endif // #ifndef MINIZ_NO_TIME\r
-\r
-  archive_name_size = strlen(pArchive_name);\r
-  if (archive_name_size > 0xFFFF)\r
-    return MZ_FALSE;\r
-\r
-  num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);\r
-\r
-  // no zip64 support yet\r
-  if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-\r
-  if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/'))\r
-  {\r
-    // Set DOS Subdirectory attribute bit.\r
-    ext_attributes |= 0x10;\r
-    // Subdirectories cannot contain data.\r
-    if ((buf_size) || (uncomp_size))\r
-      return MZ_FALSE;\r
-  }\r
-\r
-  // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.)\r
-  if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))\r
-    return MZ_FALSE;\r
-\r
-  if ((!store_data_uncompressed) && (buf_size))\r
-  {\r
-    if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))\r
-      return MZ_FALSE;\r
-  }\r
-\r
-  if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header)))\r
-  {\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);\r
-    return MZ_FALSE;\r
-  }\r
-  local_dir_header_ofs += num_alignment_padding_bytes;\r
-  if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }\r
-  cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header);\r
-\r
-  MZ_CLEAR_OBJ(local_dir_header);\r
-  if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)\r
-  {\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);\r
-    return MZ_FALSE;\r
-  }\r
-  cur_archive_file_ofs += archive_name_size;\r
-\r
-  if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))\r
-  {\r
-    uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size);\r
-    uncomp_size = buf_size;\r
-    if (uncomp_size <= 3)\r
-    {\r
-      level = 0;\r
-      store_data_uncompressed = MZ_TRUE;\r
-    }\r
-  }\r
-\r
-  if (store_data_uncompressed)\r
-  {\r
-    if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size)\r
-    {\r
-      pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);\r
-      return MZ_FALSE;\r
-    }\r
-\r
-    cur_archive_file_ofs += buf_size;\r
-    comp_size = buf_size;\r
-\r
-    if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)\r
-      method = MZ_DEFLATED;\r
-  }\r
-  else if (buf_size)\r
-  {\r
-    mz_zip_writer_add_state state;\r
-\r
-    state.m_pZip = pZip;\r
-    state.m_cur_archive_file_ofs = cur_archive_file_ofs;\r
-    state.m_comp_size = 0;\r
-\r
-    if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) ||\r
-        (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE))\r
-    {\r
-      pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);\r
-      return MZ_FALSE;\r
-    }\r
-\r
-    comp_size = state.m_comp_size;\r
-    cur_archive_file_ofs = state.m_cur_archive_file_ofs;\r
-\r
-    method = MZ_DEFLATED;\r
-  }\r
-\r
-  pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);\r
-  pComp = NULL;\r
-\r
-  // no zip64 support yet\r
-  if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-\r
-  if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date))\r
-    return MZ_FALSE;\r
-\r
-  if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))\r
-    return MZ_FALSE;\r
-\r
-  if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes))\r
-    return MZ_FALSE;\r
-\r
-  pZip->m_total_files++;\r
-  pZip->m_archive_size = cur_archive_file_ofs;\r
-\r
-  return MZ_TRUE;\r
-}\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)\r
-{\r
-  mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;\r
-  mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;\r
-  mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0;\r
-  size_t archive_name_size;\r
-  mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];\r
-  MZ_FILE *pSrc_file = NULL;\r
-\r
-  if ((int)level_and_flags < 0)\r
-    level_and_flags = MZ_DEFAULT_LEVEL;\r
-  level = level_and_flags & 0xF;\r
-\r
-  if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))\r
-    return MZ_FALSE;\r
-  if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)\r
-    return MZ_FALSE;\r
-  if (!mz_zip_writer_validate_archive_name(pArchive_name))\r
-    return MZ_FALSE;\r
-\r
-  archive_name_size = strlen(pArchive_name);\r
-  if (archive_name_size > 0xFFFF)\r
-    return MZ_FALSE;\r
-\r
-  num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);\r
-\r
-  // no zip64 support yet\r
-  if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-\r
-  if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))\r
-    return MZ_FALSE;\r
-    \r
-  pSrc_file = MZ_FOPEN(pSrc_filename, "rb");\r
-  if (!pSrc_file)\r
-    return MZ_FALSE;\r
-  MZ_FSEEK64(pSrc_file, 0, SEEK_END);\r
-  uncomp_size = MZ_FTELL64(pSrc_file);\r
-  MZ_FSEEK64(pSrc_file, 0, SEEK_SET);\r
-\r
-  if (uncomp_size > 0xFFFFFFFF)\r
-  {\r
-    // No zip64 support yet\r
-    MZ_FCLOSE(pSrc_file);\r
-    return MZ_FALSE;\r
-  }\r
-  if (uncomp_size <= 3)\r
-    level = 0;\r
-\r
-  if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header)))\r
-  {\r
-    MZ_FCLOSE(pSrc_file);\r
-    return MZ_FALSE;\r
-  }\r
-  local_dir_header_ofs += num_alignment_padding_bytes;\r
-  if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }\r
-  cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header);\r
-\r
-  MZ_CLEAR_OBJ(local_dir_header);\r
-  if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)\r
-  {\r
-    MZ_FCLOSE(pSrc_file);\r
-    return MZ_FALSE;\r
-  }\r
-  cur_archive_file_ofs += archive_name_size;\r
-\r
-  if (uncomp_size)\r
-  {\r
-    mz_uint64 uncomp_remaining = uncomp_size;\r
-    void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);\r
-    if (!pRead_buf)\r
-    {\r
-      MZ_FCLOSE(pSrc_file);\r
-      return MZ_FALSE;\r
-    }\r
-\r
-    if (!level)\r
-    {\r
-      while (uncomp_remaining)\r
-      {\r
-        mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);\r
-        if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n))\r
-        {\r
-          pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);\r
-          MZ_FCLOSE(pSrc_file);\r
-          return MZ_FALSE;\r
-        }\r
-        uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);\r
-        uncomp_remaining -= n;\r
-        cur_archive_file_ofs += n;\r
-      }\r
-      comp_size = uncomp_size;\r
-    }\r
-    else\r
-    {\r
-      mz_bool result = MZ_FALSE;\r
-      mz_zip_writer_add_state state;\r
-      tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));\r
-      if (!pComp)\r
-      {\r
-        pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);\r
-        MZ_FCLOSE(pSrc_file);\r
-        return MZ_FALSE;\r
-      }\r
-\r
-      state.m_pZip = pZip;\r
-      state.m_cur_archive_file_ofs = cur_archive_file_ofs;\r
-      state.m_comp_size = 0;\r
-\r
-      if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY)\r
-      {\r
-        pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);\r
-        pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);\r
-        MZ_FCLOSE(pSrc_file);\r
-        return MZ_FALSE;\r
-      }\r
-\r
-      for ( ; ; )\r
-      {\r
-        size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE);\r
-        tdefl_status status;\r
-\r
-        if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)\r
-          break;\r
-\r
-        uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);\r
-        uncomp_remaining -= in_buf_size;\r
-\r
-        status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);\r
-        if (status == TDEFL_STATUS_DONE)\r
-        {\r
-          result = MZ_TRUE;\r
-          break;\r
-        }\r
-        else if (status != TDEFL_STATUS_OKAY)\r
-          break;\r
-      }\r
-\r
-      pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);\r
-\r
-      if (!result)\r
-      {\r
-        pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);\r
-        MZ_FCLOSE(pSrc_file);\r
-        return MZ_FALSE;\r
-      }\r
-\r
-      comp_size = state.m_comp_size;\r
-      cur_archive_file_ofs = state.m_cur_archive_file_ofs;\r
-\r
-      method = MZ_DEFLATED;\r
-    }\r
-\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);\r
-  }\r
-\r
-  MZ_FCLOSE(pSrc_file); pSrc_file = NULL;\r
-\r
-  // no zip64 support yet\r
-  if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-\r
-  if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date))\r
-    return MZ_FALSE;\r
-\r
-  if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))\r
-    return MZ_FALSE;\r
-\r
-  if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes))\r
-    return MZ_FALSE;\r
-\r
-  pZip->m_total_files++;\r
-  pZip->m_archive_size = cur_archive_file_ofs;\r
-\r
-  return MZ_TRUE;\r
-}\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index)\r
-{\r
-  mz_uint n, bit_flags, num_alignment_padding_bytes;\r
-  mz_uint64 comp_bytes_remaining, local_dir_header_ofs;\r
-  mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;\r
-  mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;\r
-  mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];\r
-  size_t orig_central_dir_size;\r
-  mz_zip_internal_state *pState;\r
-  void *pBuf; const mz_uint8 *pSrc_central_header;\r
-\r
-  if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))\r
-    return MZ_FALSE;\r
-  if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))\r
-    return MZ_FALSE;\r
-  pState = pZip->m_pState;\r
-\r
-  num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);\r
-\r
-  // no zip64 support yet\r
-  if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-\r
-  cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);\r
-  cur_dst_file_ofs = pZip->m_archive_size;\r
-\r
-  if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)\r
-    return MZ_FALSE;\r
-  if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)\r
-    return MZ_FALSE;\r
-  cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;\r
-\r
-  if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes))\r
-    return MZ_FALSE;\r
-  cur_dst_file_ofs += num_alignment_padding_bytes;\r
-  local_dir_header_ofs = cur_dst_file_ofs;\r
-  if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }\r
-\r
-  if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)\r
-    return MZ_FALSE;\r
-  cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;\r
-\r
-  n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);\r
-  comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);\r
-\r
-  if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining)))))\r
-    return MZ_FALSE;\r
-\r
-  while (comp_bytes_remaining)\r
-  {\r
-    n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);\r
-    if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n)\r
-    {\r
-      pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);\r
-      return MZ_FALSE;\r
-    }\r
-    cur_src_file_ofs += n;\r
-\r
-    if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)\r
-    {\r
-      pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);\r
-      return MZ_FALSE;\r
-    }\r
-    cur_dst_file_ofs += n;\r
-\r
-    comp_bytes_remaining -= n;\r
-  }\r
-\r
-  bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);\r
-  if (bit_flags & 8)\r
-  {\r
-    // Copy data descriptor\r
-    if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4)\r
-    {\r
-      pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);\r
-      return MZ_FALSE;\r
-    }\r
-\r
-    n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);\r
-    if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)\r
-    {\r
-      pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);\r
-      return MZ_FALSE;\r
-    }\r
-\r
-    cur_src_file_ofs += n;\r
-    cur_dst_file_ofs += n;\r
-  }\r
-  pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);\r
-\r
-  // no zip64 support yet\r
-  if (cur_dst_file_ofs > 0xFFFFFFFF)\r
-    return MZ_FALSE;\r
-\r
-  orig_central_dir_size = pState->m_central_dir.m_size;\r
-\r
-  memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);\r
-  MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs);\r
-  if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))\r
-    return MZ_FALSE;\r
-\r
-  n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);\r
-  if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n))\r
-  {\r
-    mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);\r
-    return MZ_FALSE;\r
-  }\r
-\r
-  if (pState->m_central_dir.m_size > 0xFFFFFFFF)\r
-    return MZ_FALSE;\r
-  n = (mz_uint32)orig_central_dir_size;\r
-  if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1))\r
-  {\r
-    mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);\r
-    return MZ_FALSE;\r
-  }\r
-\r
-  pZip->m_total_files++;\r
-  pZip->m_archive_size = cur_dst_file_ofs;\r
-\r
-  return MZ_TRUE;\r
-}\r
-\r
-mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip)\r
-{\r
-  mz_zip_internal_state *pState;\r
-  mz_uint64 central_dir_ofs, central_dir_size;\r
-  mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];\r
-\r
-  if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))\r
-    return MZ_FALSE;\r
-\r
-  pState = pZip->m_pState;\r
-\r
-  // no zip64 support yet\r
-  if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))\r
-    return MZ_FALSE;\r
-\r
-  central_dir_ofs = 0;\r
-  central_dir_size = 0;\r
-  if (pZip->m_total_files)\r
-  {\r
-    // Write central directory\r
-    central_dir_ofs = pZip->m_archive_size;\r
-    central_dir_size = pState->m_central_dir.m_size;\r
-    pZip->m_central_directory_file_ofs = central_dir_ofs;\r
-    if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size)\r
-      return MZ_FALSE;\r
-    pZip->m_archive_size += central_dir_size;\r
-  }\r
-\r
-  // Write end of central directory record\r
-  MZ_CLEAR_OBJ(hdr);\r
-  MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);\r
-  MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files);\r
-  MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);\r
-  MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);\r
-  MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);\r
-\r
-  if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr))\r
-    return MZ_FALSE;\r
-#ifndef MINIZ_NO_STDIO\r
-  if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))\r
-    return MZ_FALSE;\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-  pZip->m_archive_size += sizeof(hdr);\r
-\r
-  pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;\r
-  return MZ_TRUE;\r
-}\r
-\r
-mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize)\r
-{\r
-  if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize))\r
-    return MZ_FALSE;\r
-  if (pZip->m_pWrite != mz_zip_heap_write_func)\r
-    return MZ_FALSE;\r
-  if (!mz_zip_writer_finalize_archive(pZip))\r
-    return MZ_FALSE;\r
-\r
-  *pBuf = pZip->m_pState->m_pMem;\r
-  *pSize = pZip->m_pState->m_mem_size;\r
-  pZip->m_pState->m_pMem = NULL;\r
-  pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;\r
-  return MZ_TRUE;\r
-}\r
-\r
-mz_bool mz_zip_writer_end(mz_zip_archive *pZip)\r
-{\r
-  mz_zip_internal_state *pState;\r
-  mz_bool status = MZ_TRUE;\r
-  if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))\r
-    return MZ_FALSE;\r
-\r
-  pState = pZip->m_pState;\r
-  pZip->m_pState = NULL;\r
-  mz_zip_array_clear(pZip, &pState->m_central_dir);\r
-  mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);\r
-  mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-  if (pState->m_pFile)\r
-  {\r
-    MZ_FCLOSE(pState->m_pFile);\r
-    pState->m_pFile = NULL;\r
-  }\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-  if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem))\r
-  {\r
-    pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);\r
-    pState->m_pMem = NULL;\r
-  }\r
-\r
-  pZip->m_pFree(pZip->m_pAlloc_opaque, pState);\r
-  pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;\r
-  return status;\r
-}\r
-\r
-#ifndef MINIZ_NO_STDIO\r
-mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)\r
-{\r
-  mz_bool status, created_new_archive = MZ_FALSE;\r
-  mz_zip_archive zip_archive;\r
-  struct MZ_FILE_STAT_STRUCT file_stat;\r
-  MZ_CLEAR_OBJ(zip_archive);\r
-  if ((int)level_and_flags < 0)\r
-     level_and_flags = MZ_DEFAULT_LEVEL;\r
-  if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))\r
-    return MZ_FALSE;\r
-  if (!mz_zip_writer_validate_archive_name(pArchive_name))\r
-    return MZ_FALSE;\r
-  if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0)\r
-  {\r
-    // Create a new archive.\r
-    if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))\r
-      return MZ_FALSE;\r
-    created_new_archive = MZ_TRUE;\r
-  }\r
-  else\r
-  {\r
-    // Append to an existing archive.\r
-    if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))\r
-      return MZ_FALSE;\r
-    if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename))\r
-    {\r
-      mz_zip_reader_end(&zip_archive);\r
-      return MZ_FALSE;\r
-    }\r
-  }\r
-  status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0);\r
-  // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.)\r
-  if (!mz_zip_writer_finalize_archive(&zip_archive))\r
-    status = MZ_FALSE;\r
-  if (!mz_zip_writer_end(&zip_archive))\r
-    status = MZ_FALSE;\r
-  if ((!status) && (created_new_archive))\r
-  {\r
-    // It's a new archive and something went wrong, so just delete it.\r
-    int ignoredStatus = MZ_DELETE_FILE(pZip_filename);\r
-    (void)ignoredStatus;\r
-  }\r
-  return status;\r
-}\r
-\r
-void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags)\r
-{\r
-  int file_index;\r
-  mz_zip_archive zip_archive;\r
-  void *p = NULL;\r
-\r
-  if (pSize)\r
-    *pSize = 0;\r
-\r
-  if ((!pZip_filename) || (!pArchive_name))\r
-    return NULL;\r
-\r
-  MZ_CLEAR_OBJ(zip_archive);\r
-  if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))\r
-    return NULL;\r
-\r
-  if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0)\r
-    p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);\r
-\r
-  mz_zip_reader_end(&zip_archive);\r
-  return p;\r
-}\r
-\r
-#endif // #ifndef MINIZ_NO_STDIO\r
-\r
-#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS\r
-\r
-#endif // #ifndef MINIZ_NO_ARCHIVE_APIS\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-\r
-#endif // MINIZ_HEADER_FILE_ONLY\r
-\r
-/*\r
-  This is free and unencumbered software released into the public domain.\r
-\r
-  Anyone is free to copy, modify, publish, use, compile, sell, or\r
-  distribute this software, either in source code form or as a compiled\r
-  binary, for any purpose, commercial or non-commercial, and by any\r
-  means.\r
-\r
-  In jurisdictions that recognize copyright laws, the author or authors\r
-  of this software dedicate any and all copyright interest in the\r
-  software to the public domain. We make this dedication for the benefit\r
-  of the public at large and to the detriment of our heirs and\r
-  successors. We intend this dedication to be an overt act of\r
-  relinquishment in perpetuity of all present and future rights to this\r
-  software under copyright law.\r
-\r
-  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
-  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
-  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r
-  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\r
-  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\r
-  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r
-  OTHER DEALINGS IN THE SOFTWARE.\r
-\r
-  For more information, please refer to <http://unlicense.org/>\r
-*/\r
diff --git a/src/3rdparty/miniz/zlib.h b/src/3rdparty/miniz/zlib.h
deleted file mode 100644 (file)
index 304f3ce..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-#define MINIZ_NO_ARCHIVE_APIS 
-#define MINIZ_HEADER_FILE_ONLY
-
-#include "miniz.c"
diff --git a/src/core/arch/qatomic_macosx.h b/src/core/arch/qatomic_macosx.h
deleted file mode 100644 (file)
index c6a4481..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QATOMIC_MACOSX_H
-#define QATOMIC_MACOSX_H
-
-QT_BEGIN_HEADER
-
-#if defined(__x86_64__)
-#  include <QtCore/qatomic_x86_64.h>
-#elif defined(__i386__)
-#  include <QtCore/qatomic_i386.h>
-#else // !__x86_64 && !__i386__
-#  include <QtCore/qatomic_powerpc.h>
-#endif // !__x86_64__ && !__i386__
-
-QT_END_HEADER
-
-#endif // QATOMIC_MACOSX_H
index 622d9e1..96c6fbe 100644 (file)
 #include <CoreServices/CoreServices.h>
 #endif
 
-#ifdef QT_USE_SLOG2
-#include <slog2.h>
-#endif
-
-
 
 QT_BEGIN_NAMESPACE
 
@@ -2025,56 +2020,6 @@ static void mac_default_handler(const char *msg)
 }
 #endif // Q_CC_MWERKS && Q_OS_MACX
 
-#if defined(QT_USE_SLOG2)
-#ifndef QT_LOG_CODE
-#define QT_LOG_CODE 9000
-#endif
-
-extern char *__progname;
-
-static void slog2_default_handler(QtMsgType msgType, const char *message)
-{
-    if (slog2_set_default_buffer((slog2_buffer_t)-1) == 0) {
-        slog2_buffer_set_config_t buffer_config;
-        slog2_buffer_t buffer_handle;
-
-        buffer_config.buffer_set_name = __progname;
-        buffer_config.num_buffers = 1;
-        buffer_config.verbosity_level = SLOG2_INFO;
-        buffer_config.buffer_config[0].buffer_name = "default";
-        buffer_config.buffer_config[0].num_pages = 8;
-
-        if (slog2_register(&buffer_config, &buffer_handle, 0) == -1) {
-            fprintf(stderr, "Error registering slogger2 buffer!\n");
-            fprintf(stderr, "%s", message);
-            fflush(stderr);
-            return;
-        }
-
-        // Set as the default buffer
-        slog2_set_default_buffer(buffer_handle);
-    }
-    int severity;
-    //Determines the severity level
-    switch (msgType) {
-    case QtDebugMsg:
-        severity = SLOG2_INFO;
-        break;
-    case QtWarningMsg:
-        severity = SLOG2_NOTICE;
-        break;
-    case QtCriticalMsg:
-        severity = SLOG2_WARNING;
-        break;
-    case QtFatalMsg:
-        severity = SLOG2_ERROR;
-        break;
-    }
-    //writes to the slog2 buffer
-    slog2c(NULL, QT_LOG_CODE, severity, message);
-}
-#endif // QT_USE_SLOG2
-
 QString qt_error_string(int errorCode)
 {
     const char *s = 0;
@@ -2191,8 +2136,6 @@ void qt_message_output(QtMsgType msgType, const char *buf)
     } else {
 #if defined(Q_CC_MWERKS) && defined(Q_OS_MACX)
         mac_default_handler(buf);
-#elif defined(QT_USE_SLOG2)
-        slog2_default_handler(msgType, buf);
 #elif defined(Q_OS_WINCE)
         QString fstr = QString::fromLatin1(buf);
         fstr += QLatin1Char('\n');
diff --git a/src/core/io/qfilesystemengine_win.cpp b/src/core/io/qfilesystemengine_win.cpp
deleted file mode 100644 (file)
index 8b04926..0000000
+++ /dev/null
@@ -1,1254 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfilesystemengine_p.h"
-
-#define _POSIX_
-#include "qplatformdefs.h"
-#include "qabstractfileengine.h"
-#include "qfsfileengine_p.h"
-#include <qsystemlibrary_p.h>
-#include <qdebug.h>
-
-#include "qfile.h"
-#include "qdir.h"
-#include "qmutexpool_p.h"
-#include "qvarlengtharray.h"
-#include "qdatetime.h"
-#include "qt_windows.h"
-
-#if !defined(Q_OS_WINCE)
-#  include <sys/types.h>
-#  include <direct.h>
-#  include <winioctl.h>
-#else
-#  include <types.h>
-#endif
-#include <objbase.h>
-#include <shlobj.h>
-#include <initguid.h>
-#include <accctrl.h>
-#include <ctype.h>
-#include <limits.h>
-#define SECURITY_WIN32
-#include <security.h>
-
-#ifndef SPI_GETPLATFORMTYPE
-#define SPI_GETPLATFORMTYPE 257
-#endif
-
-#ifndef PATH_MAX
-#define PATH_MAX FILENAME_MAX
-#endif
-
-#ifndef _INTPTR_T_DEFINED
-#ifdef  _WIN64
-typedef __int64             intptr_t;
-#else
-#ifdef _W64
-typedef _W64 int            intptr_t;
-#else
-typedef INT_PTR intptr_t;
-#endif
-#endif
-#define _INTPTR_T_DEFINED
-#endif
-
-#ifndef INVALID_FILE_ATTRIBUTES
-#  define INVALID_FILE_ATTRIBUTES (DWORD (-1))
-#endif
-
-#if !defined(Q_OS_WINCE)
-#  if !defined(REPARSE_DATA_BUFFER_HEADER_SIZE)
-typedef struct _REPARSE_DATA_BUFFER {
-    ULONG  ReparseTag;
-    USHORT ReparseDataLength;
-    USHORT Reserved;
-    union {
-        struct {
-            USHORT SubstituteNameOffset;
-            USHORT SubstituteNameLength;
-            USHORT PrintNameOffset;
-            USHORT PrintNameLength;
-            ULONG  Flags;
-            WCHAR  PathBuffer[1];
-        } SymbolicLinkReparseBuffer;
-        struct {
-            USHORT SubstituteNameOffset;
-            USHORT SubstituteNameLength;
-            USHORT PrintNameOffset;
-            USHORT PrintNameLength;
-            WCHAR  PathBuffer[1];
-        } MountPointReparseBuffer;
-        struct {
-            UCHAR  DataBuffer[1];
-        } GenericReparseBuffer;
-    };
-} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
-#    define REPARSE_DATA_BUFFER_HEADER_SIZE  FIELD_OFFSET(REPARSE_DATA_BUFFER, GenericReparseBuffer)
-#  endif // !defined(REPARSE_DATA_BUFFER_HEADER_SIZE)
-
-#  ifndef MAXIMUM_REPARSE_DATA_BUFFER_SIZE
-#    define MAXIMUM_REPARSE_DATA_BUFFER_SIZE 16384
-#  endif
-#  ifndef IO_REPARSE_TAG_SYMLINK
-#    define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
-#  endif
-#  ifndef FSCTL_GET_REPARSE_POINT
-#    define FSCTL_GET_REPARSE_POINT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
-#  endif
-#endif // !defined(Q_OS_WINCE)
-
-QT_BEGIN_NAMESPACE
-
-Q_CORE_EXPORT int qt_ntfs_permission_lookup = 0;
-
-#if defined(Q_OS_WINCE)
-static QString qfsPrivateCurrentDir = QLatin1String("");
-// As none of the functions we try to resolve do exist on Windows CE
-// we use QT_NO_LIBRARY to shorten everything up a little bit.
-#define QT_NO_LIBRARY 1
-#endif
-
-#if !defined(QT_NO_LIBRARY)
-QT_BEGIN_INCLUDE_NAMESPACE
-typedef DWORD (WINAPI *PtrGetNamedSecurityInfoW)(LPWSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION, PSID*, PSID*, PACL*, PACL*, PSECURITY_DESCRIPTOR*);
-static PtrGetNamedSecurityInfoW ptrGetNamedSecurityInfoW = 0;
-typedef BOOL (WINAPI *PtrLookupAccountSidW)(LPCWSTR, PSID, LPWSTR, LPDWORD, LPWSTR, LPDWORD, PSID_NAME_USE);
-static PtrLookupAccountSidW ptrLookupAccountSidW = 0;
-typedef VOID (WINAPI *PtrBuildTrusteeWithSidW)(PTRUSTEE_W, PSID);
-static PtrBuildTrusteeWithSidW ptrBuildTrusteeWithSidW = 0;
-typedef DWORD (WINAPI *PtrGetEffectiveRightsFromAclW)(PACL, PTRUSTEE_W, OUT PACCESS_MASK);
-static PtrGetEffectiveRightsFromAclW ptrGetEffectiveRightsFromAclW = 0;
-typedef BOOL (WINAPI *PtrGetUserProfileDirectoryW)(HANDLE, LPWSTR, LPDWORD);
-static PtrGetUserProfileDirectoryW ptrGetUserProfileDirectoryW = 0;
-typedef BOOL (WINAPI *PtrGetVolumePathNamesForVolumeNameW)(LPCWSTR,LPWSTR,DWORD,PDWORD);
-static PtrGetVolumePathNamesForVolumeNameW ptrGetVolumePathNamesForVolumeNameW = 0;
-QT_END_INCLUDE_NAMESPACE
-
-static TRUSTEE_W currentUserTrusteeW;
-static TRUSTEE_W worldTrusteeW;
-static PSID currentUserSID = 0;
-static PSID worldSID = 0;
-
-/*
-    Deletes the allocated SIDs during global static cleanup
-*/
-class SidCleanup
-{
-public:
-    ~SidCleanup();
-};
-
-SidCleanup::~SidCleanup()
-{
-    free(currentUserSID);
-    currentUserSID = 0;
-
-    // worldSID was allocated with AllocateAndInitializeSid so it needs to be freed with FreeSid
-    if (worldSID) {
-        ::FreeSid(worldSID);
-        worldSID = 0;
-    }
-}
-
-Q_GLOBAL_STATIC(SidCleanup, initSidCleanup)
-
-static void resolveLibs()
-{
-    static bool triedResolve = false;
-    if (!triedResolve) {
-        // need to resolve the security info functions
-
-        // protect initialization
-#ifndef QT_NO_THREAD
-        QMutexLocker locker(QMutexPool::globalInstanceGet(&triedResolve));
-        // check triedResolve again, since another thread may have already
-        // done the initialization
-        if (triedResolve) {
-            // another thread did initialize the security function pointers,
-            // so we shouldn't do it again.
-            return;
-        }
-#endif
-
-#if !defined(Q_OS_WINCE)
-        QSystemLibrary advapi32(QLatin1String("advapi32"));
-        if (advapi32.load()) {
-            ptrGetNamedSecurityInfoW = (PtrGetNamedSecurityInfoW)advapi32.resolve("GetNamedSecurityInfoW");
-            ptrLookupAccountSidW = (PtrLookupAccountSidW)advapi32.resolve("LookupAccountSidW");
-            ptrBuildTrusteeWithSidW = (PtrBuildTrusteeWithSidW)advapi32.resolve("BuildTrusteeWithSidW");
-            ptrGetEffectiveRightsFromAclW = (PtrGetEffectiveRightsFromAclW)advapi32.resolve("GetEffectiveRightsFromAclW");
-        }
-        if (ptrBuildTrusteeWithSidW) {
-            // Create TRUSTEE for current user
-            HANDLE hnd = ::GetCurrentProcess();
-            HANDLE token = 0;
-            initSidCleanup();
-            if (::OpenProcessToken(hnd, TOKEN_QUERY, &token)) {
-                DWORD retsize = 0;
-                // GetTokenInformation requires a buffer big enough for the TOKEN_USER struct and
-                // the SID struct. Since the SID struct can have variable number of subauthorities
-                // tacked at the end, its size is variable. Obtain the required size by first
-                // doing a dummy GetTokenInformation call.
-                ::GetTokenInformation(token, TokenUser, 0, 0, &retsize);
-                if (retsize) {
-                    void *tokenBuffer = malloc(retsize);
-                    if (::GetTokenInformation(token, TokenUser, tokenBuffer, retsize, &retsize)) {
-                        PSID tokenSid = reinterpret_cast<PTOKEN_USER>(tokenBuffer)->User.Sid;
-                        DWORD sidLen = ::GetLengthSid(tokenSid);
-                        currentUserSID = reinterpret_cast<PSID>(malloc(sidLen));
-                        if (::CopySid(sidLen, currentUserSID, tokenSid))
-                            ptrBuildTrusteeWithSidW(&currentUserTrusteeW, currentUserSID);
-                    }
-                    free(tokenBuffer);
-                }
-                ::CloseHandle(token);
-            }
-
-            typedef BOOL (WINAPI *PtrAllocateAndInitializeSid)(PSID_IDENTIFIER_AUTHORITY, BYTE, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, PSID*);
-            PtrAllocateAndInitializeSid ptrAllocateAndInitializeSid = (PtrAllocateAndInitializeSid)advapi32.resolve("AllocateAndInitializeSid");
-            if (ptrAllocateAndInitializeSid) {
-                // Create TRUSTEE for Everyone (World)
-                SID_IDENTIFIER_AUTHORITY worldAuth = { SECURITY_WORLD_SID_AUTHORITY };
-                if (ptrAllocateAndInitializeSid(&worldAuth, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &worldSID))
-                    ptrBuildTrusteeWithSidW(&worldTrusteeW, worldSID);
-            }
-        }
-
-        QSystemLibrary userenv(QLatin1String("userenv"));
-        if (userenv.load())
-            ptrGetUserProfileDirectoryW = (PtrGetUserProfileDirectoryW)userenv.resolve("GetUserProfileDirectoryW");
-
-        QSystemLibrary kernel32(QLatin1String("kernel32"));
-        if (kernel32.load())
-            ptrGetVolumePathNamesForVolumeNameW = (PtrGetVolumePathNamesForVolumeNameW)kernel32.resolve("GetVolumePathNamesForVolumeNameW");
-#endif
-        triedResolve = true;
-    }
-}
-#endif // QT_NO_LIBRARY
-
-typedef DWORD (WINAPI *PtrNetShareEnum)(LPWSTR, DWORD, LPBYTE*, DWORD, LPDWORD, LPDWORD, LPDWORD);
-static PtrNetShareEnum ptrNetShareEnum = 0;
-typedef DWORD (WINAPI *PtrNetApiBufferFree)(LPVOID);
-static PtrNetApiBufferFree ptrNetApiBufferFree = 0;
-typedef struct _SHARE_INFO_1 {
-    LPWSTR shi1_netname;
-    DWORD shi1_type;
-    LPWSTR shi1_remark;
-} SHARE_INFO_1;
-
-
-static bool resolveUNCLibs()
-{
-    static bool triedResolve = false;
-    if (!triedResolve) {
-#ifndef QT_NO_THREAD
-        QMutexLocker locker(QMutexPool::globalInstanceGet(&triedResolve));
-        if (triedResolve) {
-            return ptrNetShareEnum && ptrNetApiBufferFree;
-        }
-#endif
-
-#if !defined(Q_OS_WINCE)
-        QSystemLibrary netapi32(QLatin1String("Netapi32"));
-        if (netapi32.load()) {
-            ptrNetShareEnum = (PtrNetShareEnum)netapi32.resolve("NetShareEnum");
-            ptrNetApiBufferFree = (PtrNetApiBufferFree)netapi32.resolve("NetApiBufferFree");
-        }
-#endif
-        triedResolve = true;
-    }
-    return ptrNetShareEnum && ptrNetApiBufferFree;
-}
-
-static QString readSymLink(const QFileSystemEntry &link)
-{
-    QString result;
-#if !defined(Q_OS_WINCE)
-    HANDLE handle = CreateFile((wchar_t*)link.nativeFilePath().utf16(),
-                               FILE_READ_EA,
-                               FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
-                               0,
-                               OPEN_EXISTING,
-                               FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
-                               0);
-    if (handle != INVALID_HANDLE_VALUE) {
-        DWORD bufsize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
-        REPARSE_DATA_BUFFER *rdb = (REPARSE_DATA_BUFFER*)malloc(bufsize);
-        DWORD retsize = 0;
-        if (::DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, 0, 0, rdb, bufsize, &retsize, 0)) {
-            if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
-                int length = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
-                int offset = rdb->MountPointReparseBuffer.SubstituteNameOffset / sizeof(wchar_t);
-                const wchar_t* PathBuffer = &rdb->MountPointReparseBuffer.PathBuffer[offset];
-                result = QString::fromWCharArray(PathBuffer, length);
-            } else if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
-                int length = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
-                int offset = rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset / sizeof(wchar_t);
-                const wchar_t* PathBuffer = &rdb->SymbolicLinkReparseBuffer.PathBuffer[offset];
-                result = QString::fromWCharArray(PathBuffer, length);
-            }
-            // cut-off "//?/" and "/??/"
-            if (result.size() > 4 && result.at(0) == QLatin1Char('\\') && result.at(2) == QLatin1Char('?') && result.at(3) == QLatin1Char('\\'))
-                result = result.mid(4);
-        }
-        free(rdb);
-        CloseHandle(handle);
-
-#if !defined(QT_NO_LIBRARY)
-        resolveLibs();
-        if (ptrGetVolumePathNamesForVolumeNameW) {
-            QRegExp matchVolName(QLatin1String("^Volume\\{([a-z]|[0-9]|-)+\\}\\\\"), Qt::CaseInsensitive);
-            if(matchVolName.indexIn(result) == 0) {
-                DWORD len;
-                wchar_t buffer[MAX_PATH];
-                QString volumeName = result.mid(0, matchVolName.matchedLength()).prepend(QLatin1String("\\\\?\\"));
-                if(ptrGetVolumePathNamesForVolumeNameW((wchar_t*)volumeName.utf16(), buffer, MAX_PATH, &len) != 0)
-                    result.replace(0,matchVolName.matchedLength(), QString::fromWCharArray(buffer));
-            }
-        }
-#endif
-    }
-#else
-    Q_UNUSED(link);
-#endif // Q_OS_WINCE
-    return result;
-}
-
-static QString readLink(const QFileSystemEntry &link)
-{
-#if !defined(Q_OS_WINCE)
-#if !defined(QT_NO_LIBRARY) && !defined(Q_CC_MWERKS)
-    QString ret;
-
-    bool neededCoInit = false;
-    IShellLink *psl;                            // pointer to IShellLink i/f
-    WIN32_FIND_DATA wfd;
-    wchar_t szGotPath[MAX_PATH];
-
-    // Get pointer to the IShellLink interface.
-    HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID *)&psl);
-
-    if (hres == CO_E_NOTINITIALIZED) { // COM was not initialized
-        neededCoInit = true;
-        CoInitialize(NULL);
-        hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
-                                    IID_IShellLink, (LPVOID *)&psl);
-    }
-    if (SUCCEEDED(hres)) {    // Get pointer to the IPersistFile interface.
-        IPersistFile *ppf;
-        hres = psl->QueryInterface(IID_IPersistFile, (LPVOID *)&ppf);
-        if (SUCCEEDED(hres))  {
-            hres = ppf->Load((LPOLESTR)link.nativeFilePath().utf16(), STGM_READ);
-            //The original path of the link is retrieved. If the file/folder
-            //was moved, the return value still have the old path.
-            if (SUCCEEDED(hres)) {
-                if (psl->GetPath(szGotPath, MAX_PATH, &wfd, SLGP_UNCPRIORITY) == NOERROR)
-                    ret = QString::fromWCharArray(szGotPath);
-            }
-            ppf->Release();
-        }
-        psl->Release();
-    }
-    if (neededCoInit)
-        CoUninitialize();
-
-    return ret;
-#else
-    Q_UNUSED(link);
-    return QString();
-#endif // QT_NO_LIBRARY
-#else
-    wchar_t target[MAX_PATH];
-    QString result;
-    if (SHGetShortcutTarget((wchar_t*)QFileInfo(link.filePath()).absoluteFilePath().replace(QLatin1Char('/'),QLatin1Char('\\')).utf16(), target, MAX_PATH)) {
-        result = QString::fromWCharArray(target);
-        if (result.startsWith(QLatin1Char('"')))
-            result.remove(0,1);
-        if (result.endsWith(QLatin1Char('"')))
-            result.remove(result.size()-1,1);
-    }
-    return result;
-#endif // Q_OS_WINCE
-}
-
-static bool uncShareExists(const QString &server)
-{
-    // This code assumes the UNC path is always like \\?\UNC\server...
-    QStringList parts = server.split(QLatin1Char('\\'), QString::SkipEmptyParts);
-    if (parts.count() >= 3) {
-        QStringList shares;
-        if (QFileSystemEngine::uncListSharesOnServer(QLatin1String("\\\\") + parts.at(2), &shares))
-            return parts.count() >= 4 ? shares.contains(parts.at(3), Qt::CaseInsensitive) : true;
-    }
-    return false;
-}
-
-static inline bool getFindData(QString path, WIN32_FIND_DATA &findData)
-{
-    // path should not end with a trailing slash
-    while (path.endsWith(QLatin1Char('\\')))
-        path.chop(1);
-
-    // can't handle drives
-    if (!path.endsWith(QLatin1Char(':'))) {
-        HANDLE hFind = ::FindFirstFile((wchar_t*)path.utf16(), &findData);
-        if (hFind != INVALID_HANDLE_VALUE) {
-            ::FindClose(hFind);
-            return true;
-        }
-    }
-
-    return false;
-}
-
-bool QFileSystemEngine::uncListSharesOnServer(const QString &server, QStringList *list)
-{
-    if (resolveUNCLibs()) {
-        SHARE_INFO_1 *BufPtr, *p;
-        DWORD res;
-        DWORD er = 0, tr = 0, resume = 0, i;
-        do {
-            res = ptrNetShareEnum((wchar_t*)server.utf16(), 1, (LPBYTE *)&BufPtr, DWORD(-1), &er, &tr, &resume);
-            if (res == ERROR_SUCCESS || res == ERROR_MORE_DATA) {
-                p = BufPtr;
-                for (i = 1; i <= er; ++i) {
-                    if (list && p->shi1_type == 0)
-                        list->append(QString::fromWCharArray(p->shi1_netname));
-                    p++;
-                }
-            }
-            ptrNetApiBufferFree(BufPtr);
-        } while (res == ERROR_MORE_DATA);
-        return res == ERROR_SUCCESS;
-    }
-    return false;
-}
-
-void QFileSystemEngine::clearWinStatData(QFileSystemMetaData &data)
-{
-    data.size_ = 0;
-    data.fileAttribute_ =  0;
-    data.creationTime_ = FILETIME();
-    data.lastAccessTime_ = FILETIME();
-    data.lastWriteTime_ = FILETIME();
-}
-
-bool QFileSystemEngine::isCaseSensitive()
-{
-    return false;
-}
-
-//static
-QFileSystemEntry QFileSystemEngine::getLinkTarget(const QFileSystemEntry &link,
-                                                  QFileSystemMetaData &data)
-{
-   if (data.missingFlags(QFileSystemMetaData::LinkType))
-       QFileSystemEngine::fillMetaData(link, data, QFileSystemMetaData::LinkType);
-
-    QString ret;
-    if (data.isLnkFile())
-        ret = readLink(link);
-    else if (data.isLink())
-        ret = readSymLink(link);
-    return QFileSystemEntry(ret);
-}
-
-//static
-QFileSystemEntry QFileSystemEngine::canonicalName(const QFileSystemEntry &entry, QFileSystemMetaData &data)
-{
-    if (data.missingFlags(QFileSystemMetaData::ExistsAttribute))
-       QFileSystemEngine::fillMetaData(entry, data, QFileSystemMetaData::ExistsAttribute);
-
-    if (data.exists())
-        return QFileSystemEntry(slowCanonicalized(absoluteName(entry).filePath()));
-    else
-        return QFileSystemEntry();
-}
-
-//static
-QString QFileSystemEngine::nativeAbsoluteFilePath(const QString &path)
-{
-    // can be //server or //server/share
-    QString absPath;
-#if !defined(Q_OS_WINCE)
-    QVarLengthArray<wchar_t, MAX_PATH> buf(qMax(MAX_PATH, path.size() + 1));
-    wchar_t *fileName = 0;
-    DWORD retLen = GetFullPathName((wchar_t*)path.utf16(), buf.size(), buf.data(), &fileName);
-    if (retLen > (DWORD)buf.size()) {
-        buf.resize(retLen);
-        retLen = GetFullPathName((wchar_t*)path.utf16(), buf.size(), buf.data(), &fileName);
-    }
-    if (retLen != 0)
-        absPath = QString::fromWCharArray(buf.data(), retLen);
-#else
-    if (path.startsWith(QLatin1Char('/')) || path.startsWith(QLatin1Char('\\')))
-        absPath = QDir::toNativeSeparators(path);
-    else
-        absPath = QDir::toNativeSeparators(QDir::cleanPath(qfsPrivateCurrentDir + QLatin1Char('/') + path));
-#endif
-    // This is really ugly, but GetFullPathName strips off whitespace at the end.
-    // If you for instance write ". " in the lineedit of QFileDialog,
-    // (which is an invalid filename) this function will strip the space off and viola,
-    // the file is later reported as existing. Therefore, we re-add the whitespace that
-    // was at the end of path in order to keep the filename invalid.
-    if (!path.isEmpty() && path.at(path.size() - 1) == QLatin1Char(' '))
-        absPath.append(QLatin1Char(' '));
-    return absPath;
-}
-
-//static
-QFileSystemEntry QFileSystemEngine::absoluteName(const QFileSystemEntry &entry)
-{
-    QString ret;
-
-    if (!entry.isRelative()) {
-#if !defined(Q_OS_WINCE)
-        if (entry.isAbsolute() && entry.isClean()) {
-            ret = entry.filePath();
-        }  else {
-            ret = QDir::fromNativeSeparators(nativeAbsoluteFilePath(entry.filePath()));
-        }
-#else
-        ret = entry.filePath();
-#endif
-    } else {
-        ret = QDir::cleanPath(QDir::currentPath() + QLatin1Char('/') + entry.filePath());
-    }
-
-    // The path should be absolute at this point.
-    // From the docs :
-    // Absolute paths begin with the directory separator "/"
-    // (optionally preceded by a drive specification under Windows).
-    if (ret.at(0) != QLatin1Char('/')) {
-        Q_ASSERT(ret.length() >= 2);
-        Q_ASSERT(ret.at(0).isLetter());
-        Q_ASSERT(ret.at(1) == QLatin1Char(':'));
-
-        // Force uppercase drive letters.
-        ret[0] = ret.at(0).toUpper();
-    }
-    return QFileSystemEntry(ret, QFileSystemEntry::FromInternalPath());
-}
-
-//static
-QString QFileSystemEngine::owner(const QFileSystemEntry &entry, QAbstractFileEngine::FileOwner own)
-{
-    QString name;
-#if !defined(QT_NO_LIBRARY)
-    extern int qt_ntfs_permission_lookup;
-    if((qt_ntfs_permission_lookup > 0) && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) {
-        resolveLibs();
-        if (ptrGetNamedSecurityInfoW && ptrLookupAccountSidW) {
-            PSID pOwner = 0;
-            PSECURITY_DESCRIPTOR pSD;
-            if (ptrGetNamedSecurityInfoW((wchar_t*)entry.nativeFilePath().utf16(), SE_FILE_OBJECT,
-                                         own == QAbstractFileEngine::OwnerGroup ? GROUP_SECURITY_INFORMATION : OWNER_SECURITY_INFORMATION,
-                                         own == QAbstractFileEngine::OwnerUser ? &pOwner : 0, own == QAbstractFileEngine::OwnerGroup ? &pOwner : 0,
-                                         0, 0, &pSD) == ERROR_SUCCESS) {
-                DWORD lowner = 64;
-                DWORD ldomain = 64;
-                QVarLengthArray<wchar_t, 64> owner(lowner);
-                QVarLengthArray<wchar_t, 64> domain(ldomain);
-                SID_NAME_USE use = SidTypeUnknown;
-                // First call, to determine size of the strings (with '\0').
-                if (!ptrLookupAccountSidW(NULL, pOwner, (LPWSTR)owner.data(), &lowner,
-                                          (LPWSTR)domain.data(), &ldomain, (SID_NAME_USE*)&use)) {
-                    if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
-                        if (lowner > (DWORD)owner.size())
-                            owner.resize(lowner);
-                        if (ldomain > (DWORD)domain.size())
-                            domain.resize(ldomain);
-                        // Second call, try on resized buf-s
-                        if (!ptrLookupAccountSidW(NULL, pOwner, (LPWSTR)owner.data(), &lowner,
-                                                  (LPWSTR)domain.data(), &ldomain, (SID_NAME_USE*)&use)) {
-                            lowner = 0;
-                        }
-                    } else {
-                        lowner = 0;
-                    }
-                }
-                if (lowner != 0)
-                    name = QString::fromWCharArray(owner.data());
-                LocalFree(pSD);
-            }
-        }
-    }
-#else
-    Q_UNUSED(entry);
-    Q_UNUSED(own);
-#endif
-    return name;
-}
-
-//static
-bool QFileSystemEngine::fillPermissions(const QFileSystemEntry &entry, QFileSystemMetaData &data,
-                                        QFileSystemMetaData::MetaDataFlags what)
-{
-#if !defined(QT_NO_LIBRARY)
-    if((qt_ntfs_permission_lookup > 0) && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) {
-        resolveLibs();
-        if(ptrGetNamedSecurityInfoW && ptrBuildTrusteeWithSidW && ptrGetEffectiveRightsFromAclW) {
-            enum { ReadMask = 0x00000001, WriteMask = 0x00000002, ExecMask = 0x00000020 };
-
-            QString fname = entry.filePath();
-            PSID pOwner = 0;
-            PSID pGroup = 0;
-            PACL pDacl;
-            PSECURITY_DESCRIPTOR pSD;
-            DWORD res = ptrGetNamedSecurityInfoW((wchar_t*)fname.utf16(), SE_FILE_OBJECT,
-                                                 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
-                                                 &pOwner, &pGroup, &pDacl, 0, &pSD);
-            if(res == ERROR_SUCCESS) {
-                ACCESS_MASK access_mask;
-                TRUSTEE_W trustee;
-                if (what & QFileSystemMetaData::UserPermissions) { // user
-                    data.knownFlagsMask |= QFileSystemMetaData::UserPermissions;
-                    if(ptrGetEffectiveRightsFromAclW(pDacl, &currentUserTrusteeW, &access_mask) != ERROR_SUCCESS)
-                        access_mask = (ACCESS_MASK)-1;
-                    if(access_mask & ReadMask)
-                        data.entryFlags |= QFileSystemMetaData::UserReadPermission;
-                    if(access_mask & WriteMask)
-                        data.entryFlags|= QFileSystemMetaData::UserWritePermission;
-                    if(access_mask & ExecMask)
-                        data.entryFlags|= QFileSystemMetaData::UserExecutePermission;
-                }
-                if (what & QFileSystemMetaData::OwnerPermissions) { // owner
-                    data.knownFlagsMask |= QFileSystemMetaData::OwnerPermissions;
-                    ptrBuildTrusteeWithSidW(&trustee, pOwner);
-                    if(ptrGetEffectiveRightsFromAclW(pDacl, &trustee, &access_mask) != ERROR_SUCCESS)
-                        access_mask = (ACCESS_MASK)-1;
-                    if(access_mask & ReadMask)
-                        data.entryFlags |= QFileSystemMetaData::OwnerReadPermission;
-                    if(access_mask & WriteMask)
-                        data.entryFlags |= QFileSystemMetaData::OwnerWritePermission;
-                    if(access_mask & ExecMask)
-                        data.entryFlags |= QFileSystemMetaData::OwnerExecutePermission;
-                }
-                if (what & QFileSystemMetaData::GroupPermissions) { // group
-                    data.knownFlagsMask |= QFileSystemMetaData::GroupPermissions;
-                    ptrBuildTrusteeWithSidW(&trustee, pGroup);
-                    if(ptrGetEffectiveRightsFromAclW(pDacl, &trustee, &access_mask) != ERROR_SUCCESS)
-                        access_mask = (ACCESS_MASK)-1;
-                    if(access_mask & ReadMask)
-                        data.entryFlags |= QFileSystemMetaData::GroupReadPermission;
-                    if(access_mask & WriteMask)
-                        data.entryFlags |= QFileSystemMetaData::GroupWritePermission;
-                    if(access_mask & ExecMask)
-                        data.entryFlags |= QFileSystemMetaData::GroupExecutePermission;
-                }
-                if (what & QFileSystemMetaData::OtherPermissions) { // other (world)
-                    data.knownFlagsMask |= QFileSystemMetaData::OtherPermissions;
-                    if(ptrGetEffectiveRightsFromAclW(pDacl, &worldTrusteeW, &access_mask) != ERROR_SUCCESS)
-                        access_mask = (ACCESS_MASK)-1; // ###
-                    if(access_mask & ReadMask)
-                        data.entryFlags |= QFileSystemMetaData::OtherReadPermission;
-                    if(access_mask & WriteMask)
-                        data.entryFlags |= QFileSystemMetaData::OtherWritePermission;
-                    if(access_mask & ExecMask)
-                        data.entryFlags |= QFileSystemMetaData::OwnerExecutePermission;
-                }
-                LocalFree(pSD);
-            }
-        }
-    } else
-#endif
-    {
-        //### what to do with permissions if we don't use NTFS
-        // for now just add all permissions and what about exe missions ??
-        // also qt_ntfs_permission_lookup is now not set by default ... should it ?
-        data.entryFlags |= QFileSystemMetaData::OwnerReadPermission
-                           | QFileSystemMetaData::GroupReadPermission
-                           | QFileSystemMetaData::OtherReadPermission;
-
-        if (!(data.fileAttribute_ & FILE_ATTRIBUTE_READONLY)) {
-            data.entryFlags |= QFileSystemMetaData::OwnerWritePermission
-                   | QFileSystemMetaData::GroupWritePermission
-                   | QFileSystemMetaData::OtherWritePermission;
-        }
-
-        QString fname = entry.filePath();
-        QString ext = fname.right(4).toLower();
-        if (data.isDirectory() ||
-            ext == QLatin1String(".exe") || ext == QLatin1String(".com") || ext == QLatin1String(".bat") ||
-            ext == QLatin1String(".pif") || ext == QLatin1String(".cmd")) {
-            data.entryFlags |= QFileSystemMetaData::OwnerExecutePermission | QFileSystemMetaData::GroupExecutePermission
-                               | QFileSystemMetaData::OtherExecutePermission | QFileSystemMetaData::UserExecutePermission;
-        }
-        data.knownFlagsMask |= QFileSystemMetaData::OwnerPermissions | QFileSystemMetaData::GroupPermissions
-                                | QFileSystemMetaData::OtherPermissions | QFileSystemMetaData::UserExecutePermission;
-        // calculate user permissions
-        if (what & QFileSystemMetaData::UserReadPermission) {
-            if (::_waccess((wchar_t*)entry.nativeFilePath().utf16(), R_OK) == 0)
-                data.entryFlags |= QFileSystemMetaData::UserReadPermission;
-            data.knownFlagsMask |= QFileSystemMetaData::UserReadPermission;
-        }
-        if (what & QFileSystemMetaData::UserWritePermission) {
-            if (::_waccess((wchar_t*)entry.nativeFilePath().utf16(), W_OK) == 0)
-                data.entryFlags |= QFileSystemMetaData::UserWritePermission;
-            data.knownFlagsMask |= QFileSystemMetaData::UserWritePermission;
-        }
-    }
-
-    return data.hasFlags(what);
-}
-
-static bool tryDriveUNCFallback(const QFileSystemEntry &fname, QFileSystemMetaData &data)
-{
-    bool entryExists = false;
-    DWORD fileAttrib = 0;
-#if !defined(Q_OS_WINCE)
-    if (fname.isDriveRoot()) {
-        // a valid drive ??
-        DWORD drivesBitmask = ::GetLogicalDrives();
-        int drivebit = 1 << (fname.filePath().at(0).toUpper().unicode() - QLatin1Char('A').unicode());
-        if (drivesBitmask & drivebit) {
-            fileAttrib = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM;
-            entryExists = true;
-        }
-    } else {
-#endif
-        const QString &path = fname.nativeFilePath();
-        bool is_dir = false;
-        if (path.startsWith(QLatin1String("\\\\?\\UNC"))) {
-            // UNC - stat doesn't work for all cases (Windows bug)
-            int s = path.indexOf(path.at(0),7);
-            if (s > 0) {
-                // "\\?\UNC\server\..."
-                s = path.indexOf(path.at(0),s+1);
-                if (s > 0) {
-                    // "\\?\UNC\server\share\..."
-                    if (s == path.size() - 1) {
-                        // "\\?\UNC\server\share\"
-                        is_dir = true;
-                    } else {
-                        // "\\?\UNC\server\share\notfound"
-                    }
-                } else {
-                    // "\\?\UNC\server\share"
-                    is_dir = true;
-                }
-            } else {
-                // "\\?\UNC\server"
-                is_dir = true;
-            }
-        }
-        if (is_dir && uncShareExists(path)) {
-            // looks like a UNC dir, is a dir.
-            fileAttrib = FILE_ATTRIBUTE_DIRECTORY;
-            entryExists = true;
-        }
-#if !defined(Q_OS_WINCE)
-    }
-#endif
-    if (entryExists)
-        data.fillFromFileAttribute(fileAttrib);
-    return entryExists;
-}
-
-static bool tryFindFallback(const QFileSystemEntry &fname, QFileSystemMetaData &data)
-{
-    bool filledData = false;
-    // This assumes the last call to a Windows API failed.
-    int errorCode = GetLastError();
-    if (errorCode == ERROR_ACCESS_DENIED || errorCode == ERROR_SHARING_VIOLATION) {
-        WIN32_FIND_DATA findData;
-        if (getFindData(fname.nativeFilePath(), findData)
-            && findData.dwFileAttributes != INVALID_FILE_ATTRIBUTES) {
-            data.fillFromFindData(findData, true, fname.isDriveRoot());
-            filledData = true;
-        }
-    }
-    return filledData;
-}
-
-#if !defined(Q_OS_WINCE)
-//static
-bool QFileSystemEngine::fillMetaData(int fd, QFileSystemMetaData &data,
-                                     QFileSystemMetaData::MetaDataFlags what)
-{
-    HANDLE fHandle = (HANDLE)_get_osfhandle(fd);
-    if (fHandle  != INVALID_HANDLE_VALUE) {
-        return fillMetaData(fHandle, data, what);
-    }
-    return false;
-}
-#endif
-
-//static
-bool QFileSystemEngine::fillMetaData(HANDLE fHandle, QFileSystemMetaData &data,
-                                     QFileSystemMetaData::MetaDataFlags what)
-{
-    data.entryFlags &= ~what;
-    clearWinStatData(data);
-    BY_HANDLE_FILE_INFORMATION fileInfo;
-    UINT oldmode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
-    if (GetFileInformationByHandle(fHandle , &fileInfo)) {
-        data.fillFromFindInfo(fileInfo);
-    }
-    SetErrorMode(oldmode);
-    return data.hasFlags(what);
-}
-
-static bool isDirPath(const QString &dirPath, bool *existed);
-
-//static
-bool QFileSystemEngine::fillMetaData(const QFileSystemEntry &entry, QFileSystemMetaData &data,
-                                     QFileSystemMetaData::MetaDataFlags what)
-{
-    what |= QFileSystemMetaData::WinLnkType | QFileSystemMetaData::WinStatFlags;
-    data.entryFlags &= ~what;
-
-    QFileSystemEntry fname;
-    data.knownFlagsMask |= QFileSystemMetaData::WinLnkType;
-    // Check for ".lnk": Directories named ".lnk" should be skipped, corrupted
-    // link files should still be detected as links.
-    const QString origFilePath = entry.filePath();
-    if (origFilePath.endsWith(QLatin1String(".lnk")) && !isDirPath(origFilePath, 0)) {
-        data.entryFlags |= QFileSystemMetaData::WinLnkType;
-        fname = QFileSystemEntry(readLink(entry));
-    } else {
-        fname = entry;
-    }
-
-    if (fname.isEmpty()) {
-        data.knownFlagsMask |= what;
-        clearWinStatData(data);
-        return false;
-    }
-
-    if (what & QFileSystemMetaData::WinStatFlags) {
-        UINT oldmode = SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
-        clearWinStatData(data);
-        WIN32_FIND_DATA findData;
-        // The memory structure for WIN32_FIND_DATA is same as WIN32_FILE_ATTRIBUTE_DATA
-        // for all members used by fillFindData().
-        bool ok = ::GetFileAttributesEx((wchar_t*)fname.nativeFilePath().utf16(), GetFileExInfoStandard,
-                                        reinterpret_cast<WIN32_FILE_ATTRIBUTE_DATA *>(&findData));
-        if (ok) {
-            data.fillFromFindData(findData, false, fname.isDriveRoot());
-        } else {
-            if (!tryFindFallback(fname, data))
-                tryDriveUNCFallback(fname, data);
-        }
-        SetErrorMode(oldmode);
-    }
-
-    if (what & QFileSystemMetaData::Permissions)
-        fillPermissions(fname, data, what);
-    if ((what & QFileSystemMetaData::LinkType)
-        && data.missingFlags(QFileSystemMetaData::LinkType)) {
-        data.knownFlagsMask |= QFileSystemMetaData::LinkType;
-        if (data.fileAttribute_ & FILE_ATTRIBUTE_REPARSE_POINT) {
-            WIN32_FIND_DATA findData;
-            if (getFindData(fname.nativeFilePath(), findData))
-                data.fillFromFindData(findData, true);
-        }
-    }
-    data.knownFlagsMask |= what;
-    return data.hasFlags(what);
-}
-
-static inline bool mkDir(const QString &path)
-{
-#if defined(Q_OS_WINCE)
-    // Unfortunately CreateDirectory returns true for paths longer than
-    // 256, but does not create a directory. It starts to fail, when
-    // path length > MAX_PATH, which is 260 usually on CE.
-    // This only happens on a Windows Mobile device. Windows CE seems
-    // not to be affected by this.
-    static int platformId = 0;
-    if (platformId == 0) {
-        wchar_t platformString[64];
-        if (SystemParametersInfo(SPI_GETPLATFORMTYPE, sizeof(platformString)/sizeof(*platformString),platformString,0)) {
-            if (0 == wcscmp(platformString, L"PocketPC") || 0 == wcscmp(platformString, L"Smartphone"))
-                platformId = 1;
-            else
-                platformId = 2;
-        }
-    }
-    if (platformId == 1 && QFSFileEnginePrivate::longFileName(path).size() > 256)
-        return false;
-#endif
-    return ::CreateDirectory((wchar_t*)QFSFileEnginePrivate::longFileName(path).utf16(), 0);
-}
-
-static inline bool rmDir(const QString &path)
-{
-    return ::RemoveDirectory((wchar_t*)QFSFileEnginePrivate::longFileName(path).utf16());
-}
-
-static bool isDirPath(const QString &dirPath, bool *existed)
-{
-    QString path = dirPath;
-    if (path.length() == 2 && path.at(1) == QLatin1Char(':'))
-        path += QLatin1Char('\\');
-
-    DWORD fileAttrib = ::GetFileAttributes((wchar_t*)QFSFileEnginePrivate::longFileName(path).utf16());
-    if (fileAttrib == INVALID_FILE_ATTRIBUTES) {
-        int errorCode = GetLastError();
-        if (errorCode == ERROR_ACCESS_DENIED || errorCode == ERROR_SHARING_VIOLATION) {
-            WIN32_FIND_DATA findData;
-            if (getFindData(QFSFileEnginePrivate::longFileName(path), findData))
-                fileAttrib = findData.dwFileAttributes;
-        }
-    }
-
-    if (existed)
-        *existed = fileAttrib != INVALID_FILE_ATTRIBUTES;
-
-    if (fileAttrib == INVALID_FILE_ATTRIBUTES)
-        return false;
-
-    return fileAttrib & FILE_ATTRIBUTE_DIRECTORY;
-}
-
-//static
-bool QFileSystemEngine::createDirectory(const QFileSystemEntry &entry, bool createParents)
-{
-    QString dirName = entry.filePath();
-    if (createParents) {
-        dirName = QDir::toNativeSeparators(QDir::cleanPath(dirName));
-        // We spefically search for / so \ would break it..
-        int oldslash = -1;
-        if (dirName.startsWith(QLatin1String("\\\\"))) {
-            // Don't try to create the root path of a UNC path;
-            // CreateDirectory() will just return ERROR_INVALID_NAME.
-            for (int i = 0; i < dirName.size(); ++i) {
-                if (dirName.at(i) != QDir::separator()) {
-                    oldslash = i;
-                    break;
-                }
-            }
-            if (oldslash != -1)
-                oldslash = dirName.indexOf(QDir::separator(), oldslash);
-        }
-        for (int slash=0; slash != -1; oldslash = slash) {
-            slash = dirName.indexOf(QDir::separator(), oldslash+1);
-            if (slash == -1) {
-                if (oldslash == dirName.length())
-                    break;
-                slash = dirName.length();
-            }
-            if (slash) {
-                QString chunk = dirName.left(slash);
-                bool existed = false;
-                if (!isDirPath(chunk, &existed)) {
-                    if (!existed) {
-                        if (!mkDir(chunk))
-                            return false;
-                    } else {
-                        return false;
-                    }
-                }
-            }
-        }
-        return true;
-    }
-    return mkDir(entry.filePath());
-}
-
-//static
-bool QFileSystemEngine::removeDirectory(const QFileSystemEntry &entry, bool removeEmptyParents)
-{
-    QString dirName = entry.filePath();
-    if (removeEmptyParents) {
-        dirName = QDir::toNativeSeparators(QDir::cleanPath(dirName));
-        for (int oldslash = 0, slash=dirName.length(); slash > 0; oldslash = slash) {
-            QString chunk = dirName.left(slash);
-            if (chunk.length() == 2 && chunk.at(0).isLetter() && chunk.at(1) == QLatin1Char(':'))
-                break;
-            if (!isDirPath(chunk, 0))
-                return false;
-            if (!rmDir(chunk))
-                return oldslash != 0;
-            slash = dirName.lastIndexOf(QDir::separator(), oldslash-1);
-        }
-        return true;
-    }
-    return rmDir(entry.filePath());
-}
-
-//static
-QString QFileSystemEngine::rootPath()
-{
-#if defined(Q_OS_WINCE)
-    QString ret = QLatin1String("/");
-#elif defined(Q_FS_FAT)
-    QString ret = QString::fromLatin1(qgetenv("SystemDrive").constData());
-    if (ret.isEmpty())
-        ret = QLatin1String("c:");
-    ret.append(QLatin1Char('/'));
-#elif defined(Q_OS_OS2EMX)
-    char dir[4];
-    _abspath(dir, QLatin1String("/"), _MAX_PATH);
-    QString ret(dir);
-#endif
-    return ret;
-}
-
-//static
-QString QFileSystemEngine::homePath()
-{
-    QString ret;
-#if !defined(QT_NO_LIBRARY)
-    resolveLibs();
-    if (ptrGetUserProfileDirectoryW) {
-        HANDLE hnd = ::GetCurrentProcess();
-        HANDLE token = 0;
-        BOOL ok = ::OpenProcessToken(hnd, TOKEN_QUERY, &token);
-        if (ok) {
-            DWORD dwBufferSize = 0;
-            // First call, to determine size of the strings (with '\0').
-            ok = ptrGetUserProfileDirectoryW(token, NULL, &dwBufferSize);
-            if (!ok && dwBufferSize != 0) {        // We got the required buffer size
-                wchar_t *userDirectory = new wchar_t[dwBufferSize];
-                // Second call, now we can fill the allocated buffer.
-                ok = ptrGetUserProfileDirectoryW(token, userDirectory, &dwBufferSize);
-                if (ok)
-                    ret = QString::fromWCharArray(userDirectory);
-                delete [] userDirectory;
-            }
-            ::CloseHandle(token);
-        }
-    }
-#endif
-    if (ret.isEmpty() || !QFile::exists(ret)) {
-        ret = QString::fromLocal8Bit(qgetenv("USERPROFILE").constData());
-        if (ret.isEmpty() || !QFile::exists(ret)) {
-            ret = QString::fromLocal8Bit(qgetenv("HOMEDRIVE").constData())
-                  + QString::fromLocal8Bit(qgetenv("HOMEPATH").constData());
-            if (ret.isEmpty() || !QFile::exists(ret)) {
-                ret = QString::fromLocal8Bit(qgetenv("HOME").constData());
-                if (ret.isEmpty() || !QFile::exists(ret)) {
-#if defined(Q_OS_WINCE)
-                    ret = QLatin1String("\\My Documents");
-                    if (!QFile::exists(ret))
-#endif
-                        ret = rootPath();
-                }
-            }
-        }
-    }
-    return QDir::fromNativeSeparators(ret);
-}
-
-QString QFileSystemEngine::tempPath()
-{
-    QString ret;
-    wchar_t tempPath[MAX_PATH];
-    DWORD len = GetTempPath(MAX_PATH, tempPath);
-    if (len)
-        ret = QString::fromWCharArray(tempPath, len);
-    if (!ret.isEmpty()) {
-        while (ret.endsWith(QLatin1Char('\\')))
-            ret.chop(1);
-        ret = QDir::fromNativeSeparators(ret);
-    }
-    if (ret.isEmpty()) {
-#if !defined(Q_OS_WINCE)
-        ret = QLatin1String("C:/tmp");
-#else
-        ret = QLatin1String("/Temp");
-#endif
-    } else if (ret.length() >= 2 && ret[1] == QLatin1Char(':'))
-        ret[0] = ret.at(0).toUpper(); // Force uppercase drive letters.
-    return ret;
-}
-
-bool QFileSystemEngine::setCurrentPath(const QFileSystemEntry &entry)
-{
-    QFileSystemMetaData meta;
-    fillMetaData(entry, meta, QFileSystemMetaData::ExistsAttribute | QFileSystemMetaData::DirectoryType);
-    if(!(meta.exists() && meta.isDirectory()))
-        return false;
-
-#if !defined(Q_OS_WINCE)
-    //TODO: this should really be using nativeFilePath(), but that returns a path in long format \\?\c:\foo
-    //which causes many problems later on when it's returned through currentPath()
-    return ::SetCurrentDirectory(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(entry.filePath()).utf16())) != 0;
-#else
-    qfsPrivateCurrentDir = entry.filePath();
-    return true;
-#endif
-}
-
-QFileSystemEntry QFileSystemEngine::currentPath()
-{
-    QString ret;
-#if !defined(Q_OS_WINCE)
-    DWORD size = 0;
-    wchar_t currentName[PATH_MAX];
-    size = ::GetCurrentDirectory(PATH_MAX, currentName);
-    if (size != 0) {
-        if (size > PATH_MAX) {
-            wchar_t *newCurrentName = new wchar_t[size];
-            if (::GetCurrentDirectory(PATH_MAX, newCurrentName) != 0)
-                ret = QString::fromWCharArray(newCurrentName, size);
-            delete [] newCurrentName;
-        } else {
-            ret = QString::fromWCharArray(currentName, size);
-        }
-    }
-    if (ret.length() >= 2 && ret[1] == QLatin1Char(':'))
-        ret[0] = ret.at(0).toUpper(); // Force uppercase drive letters.
-#else
-    //TODO - a race condition exists when using currentPath / setCurrentPath from multiple threads
-    if (qfsPrivateCurrentDir.isEmpty())
-        qfsPrivateCurrentDir = QCoreApplication::applicationDirPath();
-
-    ret = qfsPrivateCurrentDir;
-#endif
-    return QFileSystemEntry(ret, QFileSystemEntry::FromNativePath());
-}
-
-//static
-bool QFileSystemEngine::createLink(const QFileSystemEntry &source, const QFileSystemEntry &target, QSystemError &error)
-{
-    Q_ASSERT(false);
-    Q_UNUSED(source)
-    Q_UNUSED(target)
-    Q_UNUSED(error)
-
-    return false; // TODO implement; - code needs to be moved from qfsfileengine_win.cpp
-}
-
-//static
-bool QFileSystemEngine::copyFile(const QFileSystemEntry &source, const QFileSystemEntry &target, QSystemError &error)
-{
-    bool ret = ::CopyFile((wchar_t*)source.nativeFilePath().utf16(),
-                          (wchar_t*)target.nativeFilePath().utf16(), true) != 0;
-    if(!ret)
-        error = QSystemError(::GetLastError(), QSystemError::NativeError);
-    return ret;
-}
-
-//static
-bool QFileSystemEngine::renameFile(const QFileSystemEntry &source, const QFileSystemEntry &target, QSystemError &error)
-{
-    bool ret = ::MoveFile((wchar_t*)source.nativeFilePath().utf16(),
-                          (wchar_t*)target.nativeFilePath().utf16()) != 0;
-    if(!ret)
-        error = QSystemError(::GetLastError(), QSystemError::NativeError);
-    return ret;
-}
-
-//static
-bool QFileSystemEngine::removeFile(const QFileSystemEntry &entry, QSystemError &error)
-{
-    bool ret = ::DeleteFile((wchar_t*)entry.nativeFilePath().utf16()) != 0;
-    if(!ret)
-        error = QSystemError(::GetLastError(), QSystemError::NativeError);
-    return ret;
-}
-
-//static
-bool QFileSystemEngine::setPermissions(const QFileSystemEntry &entry, QFile::Permissions permissions, QSystemError &error,
-                                       QFileSystemMetaData *data)
-{
-    Q_UNUSED(data);
-    int mode = 0;
-
-    if (permissions & QFile::ReadOwner || permissions & QFile::ReadUser
-        || permissions & QFile::ReadGroup || permissions & QFile::ReadOther)
-        mode |= _S_IREAD;
-    if (permissions & QFile::WriteOwner || permissions & QFile::WriteUser
-        || permissions & QFile::WriteGroup || permissions & QFile::WriteOther)
-        mode |= _S_IWRITE;
-
-    if (mode == 0) // not supported
-        return false;
-
-    bool ret = (::_wchmod((wchar_t*)entry.nativeFilePath().utf16(), mode) == 0);
-    if(!ret)
-        error = QSystemError(errno, QSystemError::StandardLibraryError);
-    return ret;
-}
-
-static inline QDateTime fileTimeToQDateTime(const FILETIME *time)
-{
-    QDateTime ret;
-
-#if defined(Q_OS_WINCE)
-    SYSTEMTIME systime;
-    FILETIME ftime;
-    systime.wYear = 1970;
-    systime.wMonth = 1;
-    systime.wDay = 1;
-    systime.wHour = 0;
-    systime.wMinute = 0;
-    systime.wSecond = 0;
-    systime.wMilliseconds = 0;
-    systime.wDayOfWeek = 4;
-    SystemTimeToFileTime(&systime, &ftime);
-    unsigned __int64 acttime = (unsigned __int64)time->dwHighDateTime << 32 | time->dwLowDateTime;
-    FileTimeToSystemTime(time, &systime);
-    unsigned __int64 time1970 = (unsigned __int64)ftime.dwHighDateTime << 32 | ftime.dwLowDateTime;
-    unsigned __int64 difftime = acttime - time1970;
-    difftime /= 10000000;
-    ret.setTime_t((unsigned int)difftime);
-#else
-    SYSTEMTIME sTime, lTime;
-    FileTimeToSystemTime(time, &sTime);
-    SystemTimeToTzSpecificLocalTime(0, &sTime, &lTime);
-    ret.setDate(QDate(lTime.wYear, lTime.wMonth, lTime.wDay));
-    ret.setTime(QTime(lTime.wHour, lTime.wMinute, lTime.wSecond, lTime.wMilliseconds));
-#endif
-
-    return ret;
-}
-
-QDateTime QFileSystemMetaData::creationTime() const
-{
-    return fileTimeToQDateTime(&creationTime_);
-}
-QDateTime QFileSystemMetaData::modificationTime() const
-{
-    return fileTimeToQDateTime(&lastWriteTime_);
-}
-QDateTime QFileSystemMetaData::accessTime() const
-{
-    return fileTimeToQDateTime(&lastAccessTime_);
-}
-
-QT_END_NAMESPACE
diff --git a/src/core/io/qfilesystemiterator_win.cpp b/src/core/io/qfilesystemiterator_win.cpp
deleted file mode 100644 (file)
index eb44d15..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#if _WIN32_WINNT < 0x0500
-#undef _WIN32_WINNT
-#define _WIN32_WINNT 0x0500
-#endif
-
-#include "qfilesystemiterator_p.h"
-#include "qfilesystemengine_p.h"
-#include "qplatformdefs.h"
-
-#include <QtCore/qt_windows.h>
-
-QT_BEGIN_NAMESPACE
-#ifndef  QT_NO_FILESYSTEMITERATOR
-
-bool done = true;
-
-QFileSystemIterator::QFileSystemIterator(const QFileSystemEntry &entry, QDir::Filters filters,
-                                         const QStringList &nameFilters, QDirIterator::IteratorFlags flags)
-    : nativePath(entry.nativeFilePath())
-    , dirPath(entry.filePath())
-    , findFileHandle(INVALID_HANDLE_VALUE)
-    , uncFallback(false)
-    , uncShareIndex(0)
-    , onlyDirs(false)
-{
-    Q_UNUSED(nameFilters)
-    Q_UNUSED(flags)
-    if (nativePath.endsWith(QLatin1String(".lnk"))) {
-        QFileSystemMetaData metaData;
-        QFileSystemEntry link = QFileSystemEngine::getLinkTarget(entry, metaData);
-        nativePath = link.nativeFilePath();
-    }
-    if (!nativePath.endsWith(QLatin1Char('\\')))
-        nativePath.append(QLatin1Char('\\'));
-    nativePath.append(QLatin1Char('*'));
-    if (!dirPath.endsWith(QLatin1Char('/')))
-        dirPath.append(QLatin1Char('/'));
-    if ((filters & (QDir::Dirs|QDir::Drives)) && (!(filters & (QDir::Files))))
-        onlyDirs = true;
-}
-
-QFileSystemIterator::~QFileSystemIterator()
-{
-   if (findFileHandle != INVALID_HANDLE_VALUE)
-        FindClose(findFileHandle);
-}
-
-bool QFileSystemIterator::advance(QFileSystemEntry &fileEntry, QFileSystemMetaData &metaData)
-{
-    bool haveData = false;
-    WIN32_FIND_DATA findData;
-
-    if (findFileHandle == INVALID_HANDLE_VALUE && !uncFallback) {
-        haveData = true;
-        int infoLevel = 0 ;         // FindExInfoStandard;
-        DWORD dwAdditionalFlags  = 0;
-#ifndef Q_OS_WINCE
-        if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7) {
-            dwAdditionalFlags = 2;  // FIND_FIRST_EX_LARGE_FETCH
-            infoLevel = 1 ;         // FindExInfoBasic;
-        }
-#endif
-        int searchOps =  0;         // FindExSearchNameMatch
-        if (onlyDirs)
-            searchOps = 1 ;         // FindExSearchLimitToDirectories
-        findFileHandle = FindFirstFileEx((const wchar_t *)nativePath.utf16(), FINDEX_INFO_LEVELS(infoLevel), &findData,
-                                         FINDEX_SEARCH_OPS(searchOps), 0, dwAdditionalFlags);
-        if (findFileHandle == INVALID_HANDLE_VALUE) {
-            if (nativePath.startsWith(QLatin1String("\\\\?\\UNC\\"))) {
-                QStringList parts = nativePath.split(QLatin1Char('\\'), QString::SkipEmptyParts);
-                if (parts.count() == 4 && QFileSystemEngine::uncListSharesOnServer(
-                        QLatin1String("\\\\") + parts.at(2), &uncShares)) {
-                    if (uncShares.isEmpty())
-                        return false; // No shares found in the server
-                    else
-                        uncFallback = true;
-                }
-            }
-        }
-    }
-    if (findFileHandle == INVALID_HANDLE_VALUE && !uncFallback)
-        return false;
-    // Retrieve the new file information.
-    if (!haveData) {
-        if (uncFallback) {
-            if (++uncShareIndex >= uncShares.count())
-                return false;
-        } else {
-            if (!FindNextFile(findFileHandle, &findData))
-                return false;
-        }
-    }
-    // Create the new file system entry & meta data.
-    if (uncFallback) {
-        fileEntry = QFileSystemEntry(dirPath + uncShares.at(uncShareIndex));
-        metaData.fillFromFileAttribute(FILE_ATTRIBUTE_DIRECTORY);
-        return true;
-    } else {
-        QString fileName = QString::fromWCharArray(findData.cFileName);
-        fileEntry = QFileSystemEntry(dirPath + fileName);
-        metaData = QFileSystemMetaData();
-        if (!fileName.endsWith(QLatin1String(".lnk"))) {
-            metaData.fillFromFindData(findData, true);
-        }
-        return true;
-    }
-    return false;
-}
-
-#endif //  QT_NO_FILESYSTEMITERATOR
-QT_END_NAMESPACE
diff --git a/src/core/io/qfilesystemwatcher_win.cpp b/src/core/io/qfilesystemwatcher_win.cpp
deleted file mode 100644 (file)
index d36619e..0000000
+++ /dev/null
@@ -1,426 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfilesystemwatcher.h"
-#include "qfilesystemwatcher_win_p.h"
-
-#ifndef QT_NO_FILESYSTEMWATCHER
-
-#include <qdebug.h>
-#include <qfileinfo.h>
-#include <qstringlist.h>
-#include <qset.h>
-#include <qdatetime.h>
-#include <qdir.h>
-
-QT_BEGIN_NAMESPACE
-
-void QWindowsFileSystemWatcherEngine::stop()
-{
-    foreach(QWindowsFileSystemWatcherEngineThread *thread, threads)
-        thread->stop();
-}
-
-QWindowsFileSystemWatcherEngine::QWindowsFileSystemWatcherEngine()
-    : QFileSystemWatcherEngine(false)
-{
-}
-
-QWindowsFileSystemWatcherEngine::~QWindowsFileSystemWatcherEngine()
-{
-    if (threads.isEmpty())
-        return;
-
-    foreach(QWindowsFileSystemWatcherEngineThread *thread, threads) {
-        thread->stop();
-        thread->wait();
-        delete thread;
-    }
-}
-
-QStringList QWindowsFileSystemWatcherEngine::addPaths(const QStringList &paths,
-                                                       QStringList *files,
-                                                       QStringList *directories)
-{
-    // qDebug()<<"Adding"<<paths.count()<<"to existing"<<(files->count() + directories->count())<<"watchers";
-    QStringList p = paths;
-    QMutableListIterator<QString> it(p);
-    while (it.hasNext()) {
-        QString path = it.next();
-        QString normalPath = path;
-        if ((normalPath.endsWith(QLatin1Char('/')) && !normalPath.endsWith(QLatin1String(":/")))
-            || (normalPath.endsWith(QLatin1Char('\\')) && !normalPath.endsWith(QLatin1String(":\\")))
-#ifdef Q_OS_WINCE
-            && normalPath.size() > 1)
-#else
-            )
-#endif
-        normalPath.chop(1);
-        QFileInfo fileInfo(normalPath.toLower());
-        if (!fileInfo.exists())
-            continue;
-
-        bool isDir = fileInfo.isDir();
-        if (isDir) {
-            if (directories->contains(path))
-                continue;
-        } else {
-            if (files->contains(path))
-                continue;
-        }
-
-        // qDebug()<<"Looking for a thread/handle for"<<normalPath;
-
-        const QString absolutePath = isDir ? fileInfo.absoluteFilePath() : fileInfo.absolutePath();
-        const uint flags = isDir
-                           ? (FILE_NOTIFY_CHANGE_DIR_NAME
-                              | FILE_NOTIFY_CHANGE_FILE_NAME)
-                           : (FILE_NOTIFY_CHANGE_DIR_NAME
-                              | FILE_NOTIFY_CHANGE_FILE_NAME
-                              | FILE_NOTIFY_CHANGE_ATTRIBUTES
-                              | FILE_NOTIFY_CHANGE_SIZE
-                              | FILE_NOTIFY_CHANGE_LAST_WRITE
-                              | FILE_NOTIFY_CHANGE_SECURITY);
-
-        QWindowsFileSystemWatcherEngine::PathInfo pathInfo;
-        pathInfo.absolutePath = absolutePath;
-        pathInfo.isDir = isDir;
-        pathInfo.path = path;
-        pathInfo = fileInfo;
-
-        // Look for a thread
-        QWindowsFileSystemWatcherEngineThread *thread = 0;
-        QWindowsFileSystemWatcherEngine::Handle handle;
-        QList<QWindowsFileSystemWatcherEngineThread *>::const_iterator jt, end;
-        end = threads.constEnd();
-        for(jt = threads.constBegin(); jt != end; ++jt) {
-            thread = *jt;
-            QMutexLocker locker(&(thread->mutex));
-
-            handle = thread->handleForDir.value(absolutePath);
-            if (handle.handle != INVALID_HANDLE_VALUE && handle.flags == flags) {
-                // found a thread now insert...
-                // qDebug()<<"  Found a thread"<<thread;
-
-                QHash<QString, QWindowsFileSystemWatcherEngine::PathInfo> &h
-                        = thread->pathInfoForHandle[handle.handle];
-                if (!h.contains(fileInfo.absoluteFilePath())) {
-                    thread->pathInfoForHandle[handle.handle].insert(fileInfo.absoluteFilePath(), pathInfo);
-                    if (isDir)
-                        directories->append(path);
-                    else
-                        files->append(path);
-                }
-                it.remove();
-                thread->wakeup();
-                break;
-            }
-        }
-
-        // no thread found, first create a handle
-        if (handle.handle == INVALID_HANDLE_VALUE || handle.flags != flags) {
-            // qDebug()<<"  No thread found";
-            // Volume and folder paths need a trailing slash for proper notification
-            // (e.g. "c:" -> "c:/").
-            const QString effectiveAbsolutePath =
-                    isDir ? (absolutePath + QLatin1Char('/')) : absolutePath;
-
-            handle.handle = FindFirstChangeNotification((wchar_t*) QDir::toNativeSeparators(effectiveAbsolutePath).utf16(), false, flags);
-            handle.flags = flags;
-            if (handle.handle == INVALID_HANDLE_VALUE)
-                continue;
-
-            // now look for a thread to insert
-            bool found = false;
-            foreach(QWindowsFileSystemWatcherEngineThread *thread, threads) {
-                QMutexLocker(&(thread->mutex));
-                if (thread->handles.count() < MAXIMUM_WAIT_OBJECTS) {
-                    // qDebug() << "  Added handle" << handle.handle << "for" << absolutePath << "to watch" << fileInfo.absoluteFilePath();
-                    // qDebug()<< "  to existing thread"<<thread;
-                    thread->handles.append(handle.handle);
-                    thread->handleForDir.insert(absolutePath, handle);
-
-                    thread->pathInfoForHandle[handle.handle].insert(fileInfo.absoluteFilePath(), pathInfo);
-                    if (isDir)
-                        directories->append(path);
-                    else
-                        files->append(path);
-
-                    it.remove();
-                    found = true;
-                    thread->wakeup();
-                    break;
-                }
-            }
-            if (!found) {
-                QWindowsFileSystemWatcherEngineThread *thread = new QWindowsFileSystemWatcherEngineThread();
-                //qDebug()<<"  ###Creating new thread"<<thread<<"("<<(threads.count()+1)<<"threads)";
-                thread->handles.append(handle.handle);
-                thread->handleForDir.insert(absolutePath, handle);
-
-                thread->pathInfoForHandle[handle.handle].insert(fileInfo.absoluteFilePath(), pathInfo);
-                if (isDir)
-                    directories->append(path);
-                else
-                    files->append(path);
-
-                connect(thread, SIGNAL(fileChanged(QString,bool)),
-                        this, SIGNAL(fileChanged(QString,bool)));
-                connect(thread, SIGNAL(directoryChanged(QString,bool)),
-                        this, SIGNAL(directoryChanged(QString,bool)));
-                
-                thread->msg = '@';
-                thread->start();
-                threads.append(thread);
-                it.remove();
-            }
-        }
-    }
-    return p;
-}
-
-QStringList QWindowsFileSystemWatcherEngine::removePaths(const QStringList &paths,
-                                                          QStringList *files,
-                                                          QStringList *directories)
-{
-    // qDebug()<<"removePaths"<<paths;
-    QStringList p = paths;
-    QMutableListIterator<QString> it(p);
-    while (it.hasNext()) {
-        QString path = it.next();
-        QString normalPath = path;
-        if (normalPath.endsWith(QLatin1Char('/')) || normalPath.endsWith(QLatin1Char('\\')))
-            normalPath.chop(1);
-        QFileInfo fileInfo(normalPath.toLower());
-        // qDebug()<<"removing"<<normalPath;
-        QString absolutePath = fileInfo.absoluteFilePath();
-        QList<QWindowsFileSystemWatcherEngineThread *>::iterator jt, end;
-        end = threads.end();
-        for(jt = threads.begin(); jt!= end; ++jt) {
-            QWindowsFileSystemWatcherEngineThread *thread = *jt;
-            if (*jt == 0)
-                continue;
-
-            QMutexLocker locker(&(thread->mutex));
-
-            QWindowsFileSystemWatcherEngine::Handle handle = thread->handleForDir.value(absolutePath);
-            if (handle.handle == INVALID_HANDLE_VALUE) {
-                // perhaps path is a file?
-                absolutePath = fileInfo.absolutePath();
-                handle = thread->handleForDir.value(absolutePath);
-            }
-            if (handle.handle != INVALID_HANDLE_VALUE) {
-                QHash<QString, QWindowsFileSystemWatcherEngine::PathInfo> &h =
-                        thread->pathInfoForHandle[handle.handle];
-                if (h.remove(fileInfo.absoluteFilePath())) {
-                    // ###
-                    files->removeAll(path);
-                    directories->removeAll(path);
-
-                    if (h.isEmpty()) {
-                        // qDebug() << "Closing handle" << handle.handle;
-                        FindCloseChangeNotification(handle.handle);    // This one might generate a notification
-
-                        int indexOfHandle = thread->handles.indexOf(handle.handle);
-                        Q_ASSERT(indexOfHandle != -1);
-                        thread->handles.remove(indexOfHandle);
-
-                        thread->handleForDir.remove(absolutePath);
-                        // h is now invalid
-
-                        it.remove();
-
-                        if (thread->handleForDir.isEmpty()) {
-                            // qDebug()<<"Stopping thread "<<thread;
-                            locker.unlock();
-                            thread->stop();
-                            thread->wait();
-                            locker.relock();
-                            // We can't delete the thread until the mutex locker is
-                            // out of scope
-                        }
-                    }
-                }
-                // Found the file, go to next one
-                break;
-            }
-        }
-    }
-
-    // Remove all threads that we stopped
-    QList<QWindowsFileSystemWatcherEngineThread *>::iterator jt, end;
-    end = threads.end();
-    for(jt = threads.begin(); jt != end; ++jt) {
-        if (!(*jt)->isRunning()) {
-            delete *jt;
-            *jt = 0;
-        }
-    }
-
-    threads.removeAll(0);
-    return p;
-}
-
-///////////
-// QWindowsFileSystemWatcherEngineThread
-///////////
-
-QWindowsFileSystemWatcherEngineThread::QWindowsFileSystemWatcherEngineThread()
-        : msg(0)
-{
-    if (HANDLE h = CreateEvent(0, false, false, 0)) {
-        handles.reserve(MAXIMUM_WAIT_OBJECTS);
-        handles.append(h);
-    }
-    moveToThread(this);
-}
-
-
-QWindowsFileSystemWatcherEngineThread::~QWindowsFileSystemWatcherEngineThread()
-{
-    CloseHandle(handles.at(0));
-    handles[0] = INVALID_HANDLE_VALUE;
-
-    foreach (HANDLE h, handles) {
-        if (h == INVALID_HANDLE_VALUE)
-            continue;
-        FindCloseChangeNotification(h);
-    }
-}
-
-void QWindowsFileSystemWatcherEngineThread::run()
-{
-    QMutexLocker locker(&mutex);
-    forever {
-        QVector<HANDLE> handlesCopy = handles;
-        locker.unlock();
-        // qDebug() << "QWindowsFileSystemWatcherThread"<<this<<"waiting on" << handlesCopy.count() << "handles";
-        DWORD r = WaitForMultipleObjects(handlesCopy.count(), handlesCopy.constData(), false, INFINITE);
-        locker.relock();
-        do {
-            if (r == WAIT_OBJECT_0) {
-                int m = msg;
-                msg = 0;
-                if (m == 'q') {
-                    // qDebug() << "thread"<<this<<"told to quit";
-                    return;
-                }
-                if (m != '@')  {
-                    qDebug("QWindowsFileSystemWatcherEngine: unknown message '%c' send to thread", char(m));
-                }
-                break;
-            } else if (r > WAIT_OBJECT_0 && r < WAIT_OBJECT_0 + uint(handlesCopy.count())) {
-                int at = r - WAIT_OBJECT_0;
-                Q_ASSERT(at < handlesCopy.count());
-                HANDLE handle = handlesCopy.at(at);
-
-                // When removing a path, FindCloseChangeNotification might actually fire a notification
-                // for some reason, so we must check if the handle exist in the handles vector
-                if (handles.contains(handle)) {
-                    // qDebug()<<"thread"<<this<<"Acknowledged handle:"<<at<<handle;
-                    if (!FindNextChangeNotification(handle)) {
-                        qErrnoWarning("QFileSystemWatcher: FindNextChangeNotification failed!!");
-                    }
-
-                    QHash<QString, QWindowsFileSystemWatcherEngine::PathInfo> &h = pathInfoForHandle[handle];
-                    QMutableHashIterator<QString, QWindowsFileSystemWatcherEngine::PathInfo> it(h);
-                    while (it.hasNext()) {
-                        QHash<QString, QWindowsFileSystemWatcherEngine::PathInfo>::iterator x = it.next();
-                        QString absolutePath = x.value().absolutePath;
-                        QFileInfo fileInfo(x.value().path);
-                        // qDebug() << "checking" << x.key();
-                        if (!fileInfo.exists()) {
-                            // qDebug() << x.key() << "removed!";
-                            if (x.value().isDir)
-                                emit directoryChanged(x.value().path, true);
-                            else
-                                emit fileChanged(x.value().path, true);
-                            h.erase(x);
-
-                            // close the notification handle if the directory has been removed
-                            if (h.isEmpty()) {
-                                // qDebug() << "Thread closing handle" << handle;
-                                FindCloseChangeNotification(handle);    // This one might generate a notification
-
-                                int indexOfHandle = handles.indexOf(handle);
-                                Q_ASSERT(indexOfHandle != -1);
-                                handles.remove(indexOfHandle);
-
-                                handleForDir.remove(absolutePath);
-                                // h is now invalid
-                            }
-                        } else if (x.value().isDir) {
-                            // qDebug() << x.key() << "directory changed!";
-                            emit directoryChanged(x.value().path, false);
-                            x.value() = fileInfo;
-                        } else if (x.value() != fileInfo) {
-                            // qDebug() << x.key() << "file changed!";
-                            emit fileChanged(x.value().path, false);
-                            x.value() = fileInfo;
-                        }
-                    }
-                }
-            } else {
-                // qErrnoWarning("QFileSystemWatcher: error while waiting for change notification");
-                break;  // avoid endless loop
-            }
-            handlesCopy = handles;
-            r = WaitForMultipleObjects(handlesCopy.count(), handlesCopy.constData(), false, 0);
-        } while (r != WAIT_TIMEOUT);
-    }
-}
-
-
-void QWindowsFileSystemWatcherEngineThread::stop()
-{
-    msg = 'q';
-    SetEvent(handles.at(0));
-}
-
-void QWindowsFileSystemWatcherEngineThread::wakeup()
-{
-    msg = '@';
-    SetEvent(handles.at(0));
-}
-
-QT_END_NAMESPACE
-#endif // QT_NO_FILESYSTEMWATCHER
-#include "moc_qfilesystemwatcher_win_p.h"
diff --git a/src/core/io/qfilesystemwatcher_win_p.h b/src/core/io/qfilesystemwatcher_win_p.h
deleted file mode 100644 (file)
index d481a86..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QFILESYSTEMWATCHER_WIN_P_H
-#define QFILESYSTEMWATCHER_WIN_P_H
-
-//
-//  W A R N I N G
-//  -------------
-//
-// This file is not part of the Qt API.  It exists for the convenience
-// of the QLibrary class.  This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qfilesystemwatcher_p.h"
-
-#ifndef QT_NO_FILESYSTEMWATCHER
-
-#include <qt_windows.h>
-
-#include <QtCore/qdatetime.h>
-#include <QtCore/qfile.h>
-#include <QtCore/qfileinfo.h>
-#include <QtCore/qhash.h>
-#include <QtCore/qmutex.h>
-#include <QtCore/qvector.h>
-
-QT_BEGIN_NAMESPACE
-
-class QWindowsFileSystemWatcherEngineThread;
-
-// Even though QWindowsFileSystemWatcherEngine is derived of QThread
-// via QFileSystemWatcher, it does not start a thread.
-// Instead QWindowsFileSystemWatcher creates QWindowsFileSystemWatcherEngineThreads
-// to do the actually watching.
-class QWindowsFileSystemWatcherEngine : public QFileSystemWatcherEngine
-{
-    Q_OBJECT
-public:
-    QWindowsFileSystemWatcherEngine();
-    ~QWindowsFileSystemWatcherEngine();
-
-    QStringList addPaths(const QStringList &paths, QStringList *files, QStringList *directories);
-    QStringList removePaths(const QStringList &paths, QStringList *files, QStringList *directories);
-
-    void stop();
-
-
-    class Handle
-    {
-    public:
-        HANDLE handle;
-        uint flags;
-
-        Handle()
-                : handle(INVALID_HANDLE_VALUE), flags(0u)
-        { }
-        Handle(const Handle &other)
-                : handle(other.handle), flags(other.flags)
-        { }
-    };
-
-    class PathInfo {
-    public:
-        QString absolutePath;
-        QString path;
-        bool isDir;
-
-        // fileinfo bits
-        uint ownerId;
-        uint groupId;
-        QFile::Permissions permissions;
-        QDateTime lastModified;
-
-        PathInfo &operator=(const QFileInfo &fileInfo)
-                           {
-            ownerId = fileInfo.ownerId();
-            groupId = fileInfo.groupId();
-            permissions = fileInfo.permissions();
-            lastModified = fileInfo.lastModified();
-            return *this;
-        }
-
-        bool operator!=(const QFileInfo &fileInfo) const
-        {
-            return (ownerId != fileInfo.ownerId()
-                    || groupId != fileInfo.groupId()
-                    || permissions != fileInfo.permissions()
-                    || lastModified != fileInfo.lastModified());
-        }
-    };
-private:
-    QList<QWindowsFileSystemWatcherEngineThread *> threads;
-
-};
-
-class QWindowsFileSystemWatcherEngineThread : public QThread
-{
-    Q_OBJECT
-
-public:
-    QWindowsFileSystemWatcherEngineThread();
-    ~QWindowsFileSystemWatcherEngineThread();
-    void run();
-    void stop();
-    void wakeup();
-
-    QMutex mutex;
-    QVector<HANDLE> handles;
-    int msg;
-
-    QHash<QString, QWindowsFileSystemWatcherEngine::Handle> handleForDir;
-
-    QHash<HANDLE, QHash<QString, QWindowsFileSystemWatcherEngine::PathInfo> > pathInfoForHandle;
-
-Q_SIGNALS:
-    void fileChanged(const QString &path, bool removed);
-    void directoryChanged(const QString &path, bool removed);
-};
-
-#endif // QT_NO_FILESYSTEMWATCHER
-
-QT_END_NAMESPACE
-
-#endif // QFILESYSTEMWATCHER_WIN_P_H
diff --git a/src/core/io/qfsfileengine_win.cpp b/src/core/io/qfsfileengine_win.cpp
deleted file mode 100644 (file)
index 36097c7..0000000
+++ /dev/null
@@ -1,1013 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#define _POSIX_
-#include "qplatformdefs.h"
-#include "qabstractfileengine.h"
-#include "qfsfileengine_p.h"
-#include "qfilesystemengine_p.h"
-#include <qdebug.h>
-
-#include "qfile.h"
-#include "qdir.h"
-#include "qdatetime.h"
-#include "qt_windows.h"
-
-#if !defined(Q_OS_WINCE)
-#  include <sys/types.h>
-#  include <direct.h>
-#  include <winioctl.h>
-#else
-#  include <types.h>
-#endif
-#include <objbase.h>
-#include <shlobj.h>
-#include <initguid.h>
-#include <accctrl.h>
-#include <ctype.h>
-#include <limits.h>
-#define SECURITY_WIN32
-#include <security.h>
-
-#ifndef PATH_MAX
-#define PATH_MAX FILENAME_MAX
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(Q_OS_WINCE)
-static inline bool isUncPath(const QString &path)
-{
-    // Starts with \\, but not \\.
-    return (path.startsWith(QLatin1String("\\\\"))
-            && path.size() > 2 && path.at(2) != QLatin1Char('.'));
-}
-#endif
-
-/*!
-    \internal
-*/
-QString QFSFileEnginePrivate::longFileName(const QString &path)
-{
-    if (path.startsWith(QLatin1String("\\\\.\\")))
-        return path;
-
-    QString absPath = QFileSystemEngine::nativeAbsoluteFilePath(path);
-#if !defined(Q_OS_WINCE)
-    QString prefix = QLatin1String("\\\\?\\");
-    if (isUncPath(absPath)) {
-        prefix.append(QLatin1String("UNC\\")); // "\\\\?\\UNC\\"
-        absPath.remove(0, 2);
-    }
-    return prefix + absPath;
-#else
-    return absPath;
-#endif
-}
-
-/*
-    \internal
-*/
-bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode)
-{
-    Q_Q(QFSFileEngine);
-
-    // All files are opened in share mode (both read and write).
-    DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
-
-    int accessRights = 0;
-    if (openMode & QIODevice::ReadOnly)
-        accessRights |= GENERIC_READ;
-    if (openMode & QIODevice::WriteOnly)
-        accessRights |= GENERIC_WRITE;
-
-    SECURITY_ATTRIBUTES securityAtts = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE };
-
-    // WriteOnly can create files, ReadOnly cannot.
-    DWORD creationDisp = (openMode & QIODevice::WriteOnly) ? OPEN_ALWAYS : OPEN_EXISTING;
-    // Create the file handle.
-    fileHandle = CreateFile((const wchar_t*)fileEntry.nativeFilePath().utf16(),
-                            accessRights,
-                            shareMode,
-                            &securityAtts,
-                            creationDisp,
-                            FILE_ATTRIBUTE_NORMAL,
-                            NULL);
-
-    // Bail out on error.
-    if (fileHandle == INVALID_HANDLE_VALUE) {
-        q->setError(QFile::OpenError, qt_error_string());
-        return false;
-    }
-
-    // Truncate the file after successfully opening it if Truncate is passed.
-    if (openMode & QIODevice::Truncate)
-        q->setSize(0);
-
-    // Seek to the end when in Append mode.
-    if (openMode & QFile::Append) {
-        ::SetFilePointer(fileHandle, 0, 0, FILE_END);
-    }
-
-    return true;
-}
-
-/*
-    \internal
-*/
-bool QFSFileEnginePrivate::nativeClose()
-{
-    Q_Q(QFSFileEngine);
-    if (fh || fd != -1) {
-        // stdlib / stdio mode.
-        return closeFdFh();
-    }
-
-    // Windows native mode.
-    bool ok = true;
-
-#ifndef Q_OS_WINCE
-    if (cachedFd != -1) {
-        if (::_close(cachedFd) && !::CloseHandle(fileHandle)) {
-            q->setError(QFile::UnspecifiedError, qt_error_string());
-            ok = false;
-        }
-
-        // System handle is closed with associated file descriptor.
-        fileHandle = INVALID_HANDLE_VALUE;
-        cachedFd = -1;
-
-        return ok;
-    }
-#endif
-
-    if ((fileHandle == INVALID_HANDLE_VALUE || !::CloseHandle(fileHandle))) {
-        q->setError(QFile::UnspecifiedError, qt_error_string());
-        ok = false;
-    }
-    fileHandle = INVALID_HANDLE_VALUE;
-    return ok;
-}
-
-/*
-    \internal
-*/
-bool QFSFileEnginePrivate::nativeFlush()
-{
-    if (fh) {
-        // Buffered stdlib mode.
-        return flushFh();
-    }
-    if (fd != -1) {
-        // Unbuffered stdio mode; always succeeds (no buffer).
-        return true;
-    }
-
-    // Windows native mode; flushing is
-    // unnecessary. FlushFileBuffers(), the equivalent of sync() or
-    // fsync() on Unix, does a low-level flush to the disk, and we
-    // don't expose an API for this.
-    return true;
-}
-
-/*
-    \internal
-*/
-qint64 QFSFileEnginePrivate::nativeSize() const
-{
-    Q_Q(const QFSFileEngine);
-    QFSFileEngine *thatQ = const_cast<QFSFileEngine *>(q);
-
-    // ### Don't flush; for buffered files, we should get away with ftell.
-    thatQ->flush();
-
-    // Always retrive the current information
-    metaData.clearFlags(QFileSystemMetaData::SizeAttribute);
-#if defined(Q_OS_WINCE)
-    // Buffered stdlib mode.
-    if (fh) {
-        QT_OFF_T oldPos = QT_FTELL(fh);
-        QT_FSEEK(fh, 0, SEEK_END);
-        qint64 fileSize = (qint64)QT_FTELL(fh);
-        QT_FSEEK(fh, oldPos, SEEK_SET);
-        if (fileSize == -1) {
-            fileSize = 0;
-            thatQ->setError(QFile::UnspecifiedError, qt_error_string(errno));
-        }
-        return fileSize;
-    }
-    if (fd != -1) {
-        thatQ->setError(QFile::UnspecifiedError, QLatin1String("Not implemented!"));
-        return 0;
-    }
-#endif
-    bool filled = false;
-    if (fileHandle != INVALID_HANDLE_VALUE && openMode != QIODevice::NotOpen )
-        filled = QFileSystemEngine::fillMetaData(fileHandle, metaData,
-                                                 QFileSystemMetaData::SizeAttribute);
-    else
-        filled = doStat(QFileSystemMetaData::SizeAttribute);
-
-    if (!filled) {
-        thatQ->setError(QFile::UnspecifiedError, qt_error_string(errno));
-    }
-    return metaData.size();
-}
-
-/*
-    \internal
-*/
-qint64 QFSFileEnginePrivate::nativePos() const
-{
-    Q_Q(const QFSFileEngine);
-    QFSFileEngine *thatQ = const_cast<QFSFileEngine *>(q);
-
-    if (fh || fd != -1) {
-        // stdlib / stido mode.
-        return posFdFh();
-    }
-
-    // Windows native mode.
-    if (fileHandle == INVALID_HANDLE_VALUE)
-        return 0;
-
-#if !defined(Q_OS_WINCE)
-    LARGE_INTEGER currentFilePos;
-    LARGE_INTEGER offset;
-    offset.QuadPart = 0;
-    if (!::SetFilePointerEx(fileHandle, offset, &currentFilePos, FILE_CURRENT)) {
-        thatQ->setError(QFile::UnspecifiedError, qt_error_string());
-        return 0;
-    }
-
-    return qint64(currentFilePos.QuadPart);
-#else
-    LARGE_INTEGER filepos;
-    filepos.HighPart = 0;
-    DWORD newFilePointer = SetFilePointer(fileHandle, 0, &filepos.HighPart, FILE_CURRENT);
-    if (newFilePointer == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
-        thatQ->setError(QFile::UnspecifiedError, qt_error_string());
-        return 0;
-    }
-
-    filepos.LowPart = newFilePointer;
-    return filepos.QuadPart;
-#endif
-}
-
-/*
-    \internal
-*/
-bool QFSFileEnginePrivate::nativeSeek(qint64 pos)
-{
-    Q_Q(QFSFileEngine);
-
-    if (fh || fd != -1) {
-        // stdlib / stdio mode.
-        return seekFdFh(pos);
-    }
-
-#if !defined(Q_OS_WINCE)
-    LARGE_INTEGER currentFilePos;
-    LARGE_INTEGER offset;
-    offset.QuadPart = pos;
-    if (!::SetFilePointerEx(fileHandle, offset, &currentFilePos, FILE_BEGIN)) {
-        q->setError(QFile::UnspecifiedError, qt_error_string());
-        return false;
-    }
-
-    return true;
-#else
-    DWORD newFilePointer;
-    LARGE_INTEGER *li = reinterpret_cast<LARGE_INTEGER*>(&pos);
-    newFilePointer = SetFilePointer(fileHandle, li->LowPart, &li->HighPart, FILE_BEGIN);
-    if (newFilePointer == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
-        q->setError(QFile::PositionError, qt_error_string());
-        return false;
-    }
-
-    return true;
-#endif
-}
-
-/*
-    \internal
-*/
-qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 maxlen)
-{
-    Q_Q(QFSFileEngine);
-
-    if (fh || fd != -1) {
-        // stdio / stdlib mode.
-        if (fh && nativeIsSequential() && feof(fh)) {
-            q->setError(QFile::ReadError, qt_error_string(int(errno)));
-            return -1;
-        }
-
-        return readFdFh(data, maxlen);
-    }
-
-    // Windows native mode.
-    if (fileHandle == INVALID_HANDLE_VALUE)
-        return -1;
-
-    DWORD bytesToRead = DWORD(maxlen); // <- lossy
-
-    // Reading on Windows fails with ERROR_NO_SYSTEM_RESOURCES when
-    // the chunks are too large, so we limit the block size to 32MB.
-    static const DWORD maxBlockSize = 32 * 1024 * 1024;
-
-    qint64 totalRead = 0;
-    do {
-        DWORD blockSize = qMin<DWORD>(bytesToRead, maxBlockSize);
-        DWORD bytesRead;
-        if (!ReadFile(fileHandle, data + totalRead, blockSize, &bytesRead, NULL)) {
-            if (totalRead == 0) {
-                // Note: only return failure if the first ReadFile fails.
-                q->setError(QFile::ReadError, qt_error_string());
-                return -1;
-            }
-            break;
-        }
-        if (bytesRead == 0)
-            break;
-        totalRead += bytesRead;
-        bytesToRead -= bytesRead;
-    } while (totalRead < maxlen);
-    return qint64(totalRead);
-}
-
-/*
-    \internal
-*/
-qint64 QFSFileEnginePrivate::nativeReadLine(char *data, qint64 maxlen)
-{
-    Q_Q(QFSFileEngine);
-
-    if (fh || fd != -1) {
-        // stdio / stdlib mode.
-        return readLineFdFh(data, maxlen);
-    }
-
-    // Windows native mode.
-    if (fileHandle == INVALID_HANDLE_VALUE)
-        return -1;
-
-    // ### No equivalent in Win32?
-    return q->QAbstractFileEngine::readLine(data, maxlen);
-}
-
-/*
-    \internal
-*/
-qint64 QFSFileEnginePrivate::nativeWrite(const char *data, qint64 len)
-{
-    Q_Q(QFSFileEngine);
-
-    if (fh || fd != -1) {
-        // stdio / stdlib mode.
-        return writeFdFh(data, len);
-    }
-
-    // Windows native mode.
-    if (fileHandle == INVALID_HANDLE_VALUE)
-        return -1;
-
-    qint64 bytesToWrite = DWORD(len); // <- lossy
-
-    // Writing on Windows fails with ERROR_NO_SYSTEM_RESOURCES when
-    // the chunks are too large, so we limit the block size to 32MB.
-    static const DWORD maxBlockSize = 32 * 1024 * 1024;
-
-    qint64 totalWritten = 0;
-    do {
-        DWORD blockSize = qMin<DWORD>(bytesToWrite, maxBlockSize);
-        DWORD bytesWritten;
-        if (!WriteFile(fileHandle, data + totalWritten, blockSize, &bytesWritten, NULL)) {
-            if (totalWritten == 0) {
-                // Note: Only return error if the first WriteFile failed.
-                q->setError(QFile::WriteError, qt_error_string());
-                return -1;
-            }
-            break;
-        }
-        if (bytesWritten == 0)
-            break;
-        totalWritten += bytesWritten;
-        bytesToWrite -= bytesWritten;
-    } while (totalWritten < len);
-    return qint64(totalWritten);
-}
-
-/*
-    \internal
-*/
-int QFSFileEnginePrivate::nativeHandle() const
-{
-    if (fh || fd != -1)
-        return fh ? QT_FILENO(fh) : fd;
-#ifndef Q_OS_WINCE
-    if (cachedFd != -1)
-        return cachedFd;
-
-    int flags = 0;
-    if (openMode & QIODevice::Append)
-        flags |= _O_APPEND;
-    if (!(openMode & QIODevice::WriteOnly))
-        flags |= _O_RDONLY;
-    cachedFd = _open_osfhandle((intptr_t) fileHandle, flags);
-    return cachedFd;
-#else
-    return -1;
-#endif
-}
-
-/*
-    \internal
-*/
-bool QFSFileEnginePrivate::nativeIsSequential() const
-{
-#if !defined(Q_OS_WINCE)
-    HANDLE handle = fileHandle;
-    if (fh || fd != -1)
-        handle = (HANDLE)_get_osfhandle(fh ? QT_FILENO(fh) : fd);
-    if (handle == INVALID_HANDLE_VALUE)
-        return false;
-
-    DWORD fileType = GetFileType(handle);
-    return (fileType == FILE_TYPE_CHAR)
-            || (fileType == FILE_TYPE_PIPE);
-#else
-    return false;
-#endif
-}
-
-bool QFSFileEngine::remove()
-{
-    Q_D(QFSFileEngine);
-    QSystemError error;
-    bool ret = QFileSystemEngine::removeFile(d->fileEntry, error);
-    if (!ret)
-        setError(QFile::RemoveError, error.toString());
-    return ret;
-}
-
-bool QFSFileEngine::copy(const QString &copyName)
-{
-    Q_D(QFSFileEngine);
-    QSystemError error;
-    bool ret = QFileSystemEngine::copyFile(d->fileEntry, QFileSystemEntry(copyName), error);
-    if (!ret)
-        setError(QFile::CopyError, error.toString());
-    return ret;
-}
-
-bool QFSFileEngine::rename(const QString &newName)
-{
-    Q_D(QFSFileEngine);
-    QSystemError error;
-    bool ret = QFileSystemEngine::renameFile(d->fileEntry, QFileSystemEntry(newName), error);
-    if (!ret)
-        setError(QFile::RenameError, error.toString());
-    return ret;
-}
-
-bool QFSFileEngine::mkdir(const QString &name, bool createParentDirectories) const
-{
-    return QFileSystemEngine::createDirectory(QFileSystemEntry(name), createParentDirectories);
-}
-
-bool QFSFileEngine::rmdir(const QString &name, bool recurseParentDirectories) const
-{
-    return QFileSystemEngine::removeDirectory(QFileSystemEntry(name), recurseParentDirectories);
-}
-
-bool QFSFileEngine::caseSensitive() const
-{
-    return false;
-}
-
-bool QFSFileEngine::setCurrentPath(const QString &path)
-{
-    return QFileSystemEngine::setCurrentPath(QFileSystemEntry(path));
-}
-
-QString QFSFileEngine::currentPath(const QString &fileName)
-{
-#if !defined(Q_OS_WINCE)
-    QString ret;
-    //if filename is a drive: then get the pwd of that drive
-    if (fileName.length() >= 2 &&
-        fileName.at(0).isLetter() && fileName.at(1) == QLatin1Char(':')) {
-        int drv = fileName.toUpper().at(0).toLatin1() - 'A' + 1;
-        if (_getdrive() != drv) {
-            wchar_t buf[PATH_MAX];
-            ::_wgetdcwd(drv, buf, PATH_MAX);
-            ret = QString::fromWCharArray(buf);
-        }
-    }
-    if (ret.isEmpty()) {
-        //just the pwd
-        ret = QFileSystemEngine::currentPath().filePath();
-    }
-    if (ret.length() >= 2 && ret[1] == QLatin1Char(':'))
-        ret[0] = ret.at(0).toUpper(); // Force uppercase drive letters.
-    return ret;
-#else
-    Q_UNUSED(fileName);
-    return QFileSystemEngine::currentPath().filePath();
-#endif
-}
-
-QString QFSFileEngine::homePath()
-{
-    return QFileSystemEngine::homePath();
-}
-
-QString QFSFileEngine::rootPath()
-{
-    return QFileSystemEngine::rootPath();
-}
-
-QString QFSFileEngine::tempPath()
-{
-    return QFileSystemEngine::tempPath();
-}
-
-QFileInfoList QFSFileEngine::drives()
-{
-    QFileInfoList ret;
-#if !defined(Q_OS_WINCE)
-#if defined(Q_OS_WIN32)
-    quint32 driveBits = (quint32) GetLogicalDrives() & 0x3ffffff;
-#elif defined(Q_OS_OS2EMX)
-    quint32 driveBits, cur;
-    if (DosQueryCurrentDisk(&cur, &driveBits) != NO_ERROR)
-        exit(1);
-    driveBits &= 0x3ffffff;
-#endif
-    char driveName[] = "A:/";
-
-    while (driveBits) {
-        if (driveBits & 1)
-            ret.append(QFileInfo(QLatin1String(driveName)));
-        driveName[0]++;
-        driveBits = driveBits >> 1;
-    }
-    return ret;
-#else
-    ret.append(QFileInfo(QLatin1String("/")));
-    return ret;
-#endif
-}
-
-bool QFSFileEnginePrivate::doStat(QFileSystemMetaData::MetaDataFlags flags) const
-{
-    if (!tried_stat || !metaData.hasFlags(flags)) {
-        tried_stat = true;
-
-#if !defined(Q_OS_WINCE)
-        int localFd = fd;
-        if (fh && fileEntry.isEmpty())
-            localFd = QT_FILENO(fh);
-        if (localFd != -1)
-            QFileSystemEngine::fillMetaData(localFd, metaData, flags);
-#endif
-        if (metaData.missingFlags(flags) && !fileEntry.isEmpty())
-            QFileSystemEngine::fillMetaData(fileEntry, metaData, metaData.missingFlags(flags));
-    }
-
-    return metaData.exists();
-}
-
-
-bool QFSFileEngine::link(const QString &newName)
-{
-#if !defined(Q_OS_WINCE)
-#if !defined(QT_NO_LIBRARY) && !defined(Q_CC_MWERKS)
-    bool ret = false;
-
-    QString linkName = newName;
-    //### assume that they add .lnk
-
-    IShellLink *psl;
-    bool neededCoInit = false;
-
-    HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl);
-
-    if (hres == CO_E_NOTINITIALIZED) { // COM was not initialized
-        neededCoInit = true;
-        CoInitialize(NULL);
-        hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl);
-    }
-
-    if (SUCCEEDED(hres)) {
-        hres = psl->SetPath((wchar_t *)fileName(AbsoluteName).replace(QLatin1Char('/'), QLatin1Char('\\')).utf16());
-        if (SUCCEEDED(hres)) {
-            hres = psl->SetWorkingDirectory((wchar_t *)fileName(AbsolutePathName).replace(QLatin1Char('/'), QLatin1Char('\\')).utf16());
-            if (SUCCEEDED(hres)) {
-                IPersistFile *ppf;
-                hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf);
-                if (SUCCEEDED(hres)) {
-                    hres = ppf->Save((wchar_t*)linkName.utf16(), TRUE);
-                    if (SUCCEEDED(hres))
-                         ret = true;
-                    ppf->Release();
-                }
-            }
-        }
-        psl->Release();
-    }
-    if (!ret)
-        setError(QFile::RenameError, qt_error_string());
-
-    if (neededCoInit)
-        CoUninitialize();
-
-    return ret;
-#else
-    Q_UNUSED(newName);
-    return false;
-#endif // QT_NO_LIBRARY
-#else
-    QString linkName = newName;
-    linkName.replace(QLatin1Char('/'), QLatin1Char('\\'));
-    if (!linkName.endsWith(QLatin1String(".lnk")))
-        linkName += QLatin1String(".lnk");
-    QString orgName = fileName(AbsoluteName).replace(QLatin1Char('/'), QLatin1Char('\\'));
-    // Need to append on our own
-    orgName.prepend(QLatin1Char('"'));
-    orgName.append(QLatin1Char('"'));
-    bool ret = SUCCEEDED(SHCreateShortcut((wchar_t*)linkName.utf16(), (wchar_t*)orgName.utf16()));
-    if (!ret)
-        setError(QFile::RenameError, qt_error_string());
-    return ret;
-#endif // Q_OS_WINCE
-}
-
-/*!
-    \reimp
-*/
-QAbstractFileEngine::FileFlags QFSFileEngine::fileFlags(QAbstractFileEngine::FileFlags type) const
-{
-    Q_D(const QFSFileEngine);
-
-    if (type & Refresh)
-        d->metaData.clear();
-
-    QAbstractFileEngine::FileFlags ret = 0;
-
-    if (type & FlagsMask)
-        ret |= LocalDiskFlag;
-
-    bool exists;
-    {
-        QFileSystemMetaData::MetaDataFlags queryFlags = 0;
-
-        queryFlags |= QFileSystemMetaData::MetaDataFlags(uint(type))
-                & QFileSystemMetaData::Permissions;
-
-        // AliasType and BundleType are 0x0
-        if (type & TypesMask)
-            queryFlags |= QFileSystemMetaData::AliasType
-                    | QFileSystemMetaData::LinkType
-                    | QFileSystemMetaData::FileType
-                    | QFileSystemMetaData::DirectoryType
-                    | QFileSystemMetaData::BundleType;
-
-        if (type & FlagsMask)
-            queryFlags |= QFileSystemMetaData::HiddenAttribute
-                    | QFileSystemMetaData::ExistsAttribute;
-
-        queryFlags |= QFileSystemMetaData::LinkType;
-
-        exists = d->doStat(queryFlags);
-    }
-
-    if (exists && (type & PermsMask))
-        ret |= FileFlags(uint(d->metaData.permissions()));
-
-    if (type & TypesMask) {
-        if ((type & LinkType) && d->metaData.isLegacyLink())
-            ret |= LinkType;
-        if (d->metaData.isDirectory()) {
-            ret |= DirectoryType;
-        } else {
-            ret |= FileType;
-        }
-    }
-    if (type & FlagsMask) {
-        if (d->metaData.exists()) {
-            ret |= ExistsFlag;
-            if (d->fileEntry.isRoot())
-                ret |= RootFlag;
-            else if (d->metaData.isHidden())
-                ret |= HiddenFlag;
-        }
-    }
-    return ret;
-}
-
-QString QFSFileEngine::fileName(FileName file) const
-{
-    Q_D(const QFSFileEngine);
-    if (file == BaseName) {
-        return d->fileEntry.fileName();
-    } else if (file == PathName) {
-        return d->fileEntry.path();
-    } else if (file == AbsoluteName || file == AbsolutePathName) {
-        QString ret;
-
-        if (!isRelativePath()) {
-#if !defined(Q_OS_WINCE)
-            if (d->fileEntry.filePath().startsWith(QLatin1Char('/')) || // It's a absolute path to the current drive, so \a.txt -> Z:\a.txt
-                d->fileEntry.filePath().size() == 2 ||                  // It's a drive letter that needs to get a working dir appended
-                (d->fileEntry.filePath().size() > 2 && d->fileEntry.filePath().at(2) != QLatin1Char('/')) || // It's a drive-relative path, so Z:a.txt -> Z:\currentpath\a.txt
-                d->fileEntry.filePath().contains(QLatin1String("/../")) || d->fileEntry.filePath().contains(QLatin1String("/./")) ||
-                d->fileEntry.filePath().endsWith(QLatin1String("/..")) || d->fileEntry.filePath().endsWith(QLatin1String("/.")))
-            {
-                ret = QDir::fromNativeSeparators(QFileSystemEngine::nativeAbsoluteFilePath(d->fileEntry.filePath()));
-            } else
-#endif
-            {
-                ret = d->fileEntry.filePath();
-            }
-        } else {
-            ret = QDir::cleanPath(QDir::currentPath() + QLatin1Char('/') + d->fileEntry.filePath());
-        }
-
-        // The path should be absolute at this point.
-        // From the docs :
-        // Absolute paths begin with the directory separator "/"
-        // (optionally preceded by a drive specification under Windows).
-        if (ret.at(0) != QLatin1Char('/')) {
-            Q_ASSERT(ret.length() >= 2);
-            Q_ASSERT(ret.at(0).isLetter());
-            Q_ASSERT(ret.at(1) == QLatin1Char(':'));
-
-            // Force uppercase drive letters.
-            ret[0] = ret.at(0).toUpper();
-        }
-
-        if (file == AbsolutePathName) {
-            int slash = ret.lastIndexOf(QLatin1Char('/'));
-            if (slash < 0)
-                return ret;
-            else if (ret.at(0) != QLatin1Char('/') && slash == 2)
-                return ret.left(3);      // include the slash
-            else
-                return ret.left(slash > 0 ? slash : 1);
-        }
-        return ret;
-    } else if (file == CanonicalName || file == CanonicalPathName) {
-        if (!(fileFlags(ExistsFlag) & ExistsFlag))
-            return QString();
-        QFileSystemEntry entry(QFileSystemEngine::canonicalName(QFileSystemEntry(fileName(AbsoluteName)), d->metaData));
-
-        if (file == CanonicalPathName)
-            return entry.path();
-        return entry.filePath();
-    } else if (file == LinkName) {
-        return QFileSystemEngine::getLinkTarget(d->fileEntry, d->metaData).filePath();
-    } else if (file == BundleName) {
-        return QString();
-    }
-    return d->fileEntry.filePath();
-}
-
-bool QFSFileEngine::isRelativePath() const
-{
-    Q_D(const QFSFileEngine);
-    // drive, e.g. "a:", or UNC root, e.q. "//"
-    return d->fileEntry.isRelative();
-}
-
-uint QFSFileEngine::ownerId(FileOwner /*own*/) const
-{
-    static const uint nobodyID = (uint) -2;
-    return nobodyID;
-}
-
-QString QFSFileEngine::owner(FileOwner own) const
-{
-    Q_D(const QFSFileEngine);
-    return QFileSystemEngine::owner(d->fileEntry, own);
-}
-
-bool QFSFileEngine::setPermissions(uint perms)
-{
-    Q_D(QFSFileEngine);
-    QSystemError error;
-    bool ret = QFileSystemEngine::setPermissions(d->fileEntry, QFile::Permissions(perms), error);
-    if (!ret)
-        setError(QFile::PermissionsError, error.toString());
-    return ret;
-}
-
-bool QFSFileEngine::setSize(qint64 size)
-{
-    Q_D(QFSFileEngine);
-
-    if (d->fileHandle != INVALID_HANDLE_VALUE || d->fd != -1 || d->fh) {
-        // resize open file
-        HANDLE fh = d->fileHandle;
-#if !defined(Q_OS_WINCE)
-        if (fh == INVALID_HANDLE_VALUE) {
-            if (d->fh)
-                fh = (HANDLE)_get_osfhandle(QT_FILENO(d->fh));
-            else
-                fh = (HANDLE)_get_osfhandle(d->fd);
-        }
-#endif
-        if (fh == INVALID_HANDLE_VALUE)
-            return false;
-        qint64 currentPos = pos();
-
-        if (seek(size) && SetEndOfFile(fh)) {
-            seek(qMin(currentPos, size));
-            return true;
-        }
-
-        seek(currentPos);
-        return false;
-    }
-
-    if (!d->fileEntry.isEmpty()) {
-        // resize file on disk
-        QFile file(d->fileEntry.filePath());
-        if (file.open(QFile::ReadWrite)) {
-            bool ret = file.resize(size);
-            if (!ret)
-                setError(QFile::ResizeError, file.errorString());
-            return ret;
-        }
-    }
-    return false;
-}
-
-
-QDateTime QFSFileEngine::fileTime(FileTime time) const
-{
-    Q_D(const QFSFileEngine);
-
-    if (d->doStat(QFileSystemMetaData::Times))
-        return d->metaData.fileTime(time);
-
-    return QDateTime();
-}
-
-uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size,
-                                 QFile::MemoryMapFlags flags)
-{
-    Q_Q(QFSFileEngine);
-    Q_UNUSED(flags);
-    if (openMode == QFile::NotOpen) {
-        q->setError(QFile::PermissionsError, qt_error_string(ERROR_ACCESS_DENIED));
-        return 0;
-    }
-    if (offset == 0 && size == 0) {
-        q->setError(QFile::UnspecifiedError, qt_error_string(ERROR_INVALID_PARAMETER));
-        return 0;
-    }
-
-    if (mapHandle == NULL) {
-        // get handle to the file
-        HANDLE handle = fileHandle;
-
-#ifndef Q_OS_WINCE
-        if (handle == INVALID_HANDLE_VALUE && fh)
-            handle = (HANDLE)::_get_osfhandle(QT_FILENO(fh));
-#endif
-
-#ifdef Q_USE_DEPRECATED_MAP_API
-        nativeClose();
-        // handle automatically closed by kernel with mapHandle (below).
-        handle = ::CreateFileForMapping((const wchar_t*)fileEntry.nativeFilePath().utf16(),
-                GENERIC_READ | (openMode & QIODevice::WriteOnly ? GENERIC_WRITE : 0),
-                0,
-                NULL,
-                OPEN_EXISTING,
-                FILE_ATTRIBUTE_NORMAL,
-                NULL);
-        // Since this is a special case, we check if the return value was NULL and if so
-        // we change it to INVALID_HANDLE_VALUE to follow the logic inside this function.
-        if(0 == handle)
-            handle = INVALID_HANDLE_VALUE;
-#endif
-
-        if (handle == INVALID_HANDLE_VALUE) {
-            q->setError(QFile::PermissionsError, qt_error_string(ERROR_ACCESS_DENIED));
-            return 0;
-        }
-
-        // first create the file mapping handle
-        DWORD protection = (openMode & QIODevice::WriteOnly) ? PAGE_READWRITE : PAGE_READONLY;
-        mapHandle = ::CreateFileMapping(handle, 0, protection, 0, 0, 0);
-        if (mapHandle == NULL) {
-            q->setError(QFile::PermissionsError, qt_error_string());
-#ifdef Q_USE_DEPRECATED_MAP_API
-            ::CloseHandle(handle);
-#endif
-            return 0;
-        }
-    }
-
-    // setup args to map
-    DWORD access = 0;
-    if (openMode & QIODevice::ReadOnly) access = FILE_MAP_READ;
-    if (openMode & QIODevice::WriteOnly) access = FILE_MAP_WRITE;
-
-    DWORD offsetHi = offset >> 32;
-    DWORD offsetLo = offset & Q_UINT64_C(0xffffffff);
-    SYSTEM_INFO sysinfo;
-    ::GetSystemInfo(&sysinfo);
-    DWORD mask = sysinfo.dwAllocationGranularity - 1;
-    DWORD extra = offset & mask;
-    if (extra)
-        offsetLo &= ~mask;
-
-    // attempt to create the map
-    LPVOID mapAddress = ::MapViewOfFile(mapHandle, access,
-                                      offsetHi, offsetLo, size + extra);
-    if (mapAddress) {
-        uchar *address = extra + static_cast<uchar*>(mapAddress);
-        maps[address] = extra;
-        return address;
-    }
-
-    switch(GetLastError()) {
-    case ERROR_ACCESS_DENIED:
-        q->setError(QFile::PermissionsError, qt_error_string());
-        break;
-    case ERROR_INVALID_PARAMETER:
-        // size are out of bounds
-    default:
-        q->setError(QFile::UnspecifiedError, qt_error_string());
-    }
-
-    ::CloseHandle(mapHandle);
-    mapHandle = NULL;
-    return 0;
-}
-
-bool QFSFileEnginePrivate::unmap(uchar *ptr)
-{
-    Q_Q(QFSFileEngine);
-    if (!maps.contains(ptr)) {
-        q->setError(QFile::PermissionsError, qt_error_string(ERROR_ACCESS_DENIED));
-        return false;
-    }
-    uchar *start = ptr - maps[ptr];
-    if (!UnmapViewOfFile(start)) {
-        q->setError(QFile::PermissionsError, qt_error_string());
-        return false;
-    }
-
-    maps.remove(ptr);
-    if (maps.isEmpty()) {
-        ::CloseHandle(mapHandle);
-        mapHandle = NULL;
-    }
-
-    return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/core/io/qprocess_win.cpp b/src/core/io/qprocess_win.cpp
deleted file mode 100644 (file)
index d7c5390..0000000
+++ /dev/null
@@ -1,879 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qprocess.h"
-#include "qprocess_p.h"
-#include "qwindowspipewriter_p.h"
-
-#include <qdatetime.h>
-#include <qdir.h>
-#include <qfileinfo.h>
-#include <qregexp.h>
-#include <qtimer.h>
-#include <qthread.h>
-#include <qmutex.h>
-#include <qwaitcondition.h>
-#include <qwineventnotifier_p.h>
-#include <qthread_p.h>
-#include <qdebug.h>
-
-#include "qfsfileengine_p.h" // for longFileName
-
-
-#ifndef QT_NO_PROCESS
-
-QT_BEGIN_NAMESPACE
-
-//#define QPROCESS_DEBUG
-
-#define NOTIFYTIMEOUT 100
-
-static void qt_create_pipe(Q_PIPE *pipe, bool in)
-{
-    // Open the pipes.  Make non-inheritable copies of input write and output
-    // read handles to avoid non-closable handles (this is done by the
-    // DuplicateHandle() call).
-
-#if !defined(Q_OS_WINCE)
-    SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
-
-    HANDLE tmpHandle;
-    if (in) {                   // stdin
-        if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024))
-            return;
-        if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(),
-                             &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS))
-            return;
-    } else {                    // stdout or stderr
-        if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024))
-            return;
-        if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(),
-                             &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS))
-            return;
-    }
-
-    CloseHandle(tmpHandle);
-#else
-       Q_UNUSED(pipe);
-       Q_UNUSED(in);
-#endif
-}
-
-/*
-    Create the pipes to a QProcessPrivate::Channel.
-
-    This function must be called in order: stdin, stdout, stderr
-*/
-bool QProcessPrivate::createChannel(Channel &channel)
-{
-    Q_Q(QProcess);
-
-    if (&channel == &stderrChannel && processChannelMode == QProcess::MergedChannels) {
-        return DuplicateHandle(GetCurrentProcess(), stdoutChannel.pipe[1], GetCurrentProcess(),
-                               &stderrChannel.pipe[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
-    }
-
-    if (channel.type == Channel::Normal) {
-        // we're piping this channel to our own process
-        qt_create_pipe(channel.pipe, &channel == &stdinChannel);
-
-        return true;
-    } else if (channel.type == Channel::Redirect) {
-        // we're redirecting the channel to/from a file
-        SECURITY_ATTRIBUTES secAtt = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
-
-        if (&channel == &stdinChannel) {
-            // try to open in read-only mode
-            channel.pipe[1] = INVALID_Q_PIPE;
-            channel.pipe[0] =
-                CreateFile((const wchar_t*)QFSFileEnginePrivate::longFileName(channel.file).utf16(),
-                           GENERIC_READ,
-                           FILE_SHARE_READ | FILE_SHARE_WRITE,
-                           &secAtt,
-                           OPEN_EXISTING,
-                           FILE_ATTRIBUTE_NORMAL,
-                           NULL);
-
-            if (channel.pipe[0] != INVALID_Q_PIPE)
-                return true;
-
-            q->setErrorString(QProcess::tr("Could not open input redirection for reading"));
-        } else {
-            // open in write mode
-            channel.pipe[0] = INVALID_Q_PIPE;
-            channel.pipe[1] =
-                CreateFile((const wchar_t *)QFSFileEnginePrivate::longFileName(channel.file).utf16(),
-                           GENERIC_WRITE,
-                           FILE_SHARE_READ | FILE_SHARE_WRITE,
-                           &secAtt,
-                           channel.append ? OPEN_ALWAYS : CREATE_ALWAYS,
-                           FILE_ATTRIBUTE_NORMAL,
-                           NULL);
-
-            if (channel.pipe[1] != INVALID_Q_PIPE) {
-                if (channel.append) {
-                    SetFilePointer(channel.pipe[1], 0, NULL, FILE_END);
-                }
-                return true;
-            }
-
-            q->setErrorString(QProcess::tr("Could not open output redirection for writing"));
-        }
-
-        // could not open file
-        processError = QProcess::FailedToStart;
-        emit q->error(processError);
-        cleanup();
-        return false;
-    } else {
-        Q_ASSERT_X(channel.process, "QProcess::start", "Internal error");
-
-        Channel *source;
-        Channel *sink;
-
-        if (channel.type == Channel::PipeSource) {
-            // we are the source
-            source = &channel;
-            sink = &channel.process->stdinChannel;
-
-            if (source->pipe[1] != INVALID_Q_PIPE) {
-                // already constructed by the sink
-                // make it inheritable
-                HANDLE tmpHandle = source->pipe[1];
-                if (!DuplicateHandle(GetCurrentProcess(), tmpHandle,
-                                     GetCurrentProcess(), &source->pipe[1],
-                                     0, TRUE, DUPLICATE_SAME_ACCESS))
-                    return false;
-
-                CloseHandle(tmpHandle);
-                return true;
-            }
-
-            Q_ASSERT(source == &stdoutChannel);
-            Q_ASSERT(sink->process == this && sink->type == Channel::PipeSink);
-
-            qt_create_pipe(source->pipe, /* in = */ false); // source is stdout
-            sink->pipe[0] = source->pipe[0];
-            source->pipe[0] = INVALID_Q_PIPE;
-
-            return true;
-        } else {
-            // we are the sink;
-            source = &channel.process->stdoutChannel;
-            sink = &channel;
-
-            if (sink->pipe[0] != INVALID_Q_PIPE) {
-                // already constructed by the source
-                // make it inheritable
-                HANDLE tmpHandle = sink->pipe[0];
-                if (!DuplicateHandle(GetCurrentProcess(), tmpHandle,
-                                     GetCurrentProcess(), &sink->pipe[0],
-                                     0, TRUE, DUPLICATE_SAME_ACCESS))
-                    return false;
-
-                CloseHandle(tmpHandle);
-                return true;
-            }
-            Q_ASSERT(sink == &stdinChannel);
-            Q_ASSERT(source->process == this && source->type == Channel::PipeSource);
-
-            qt_create_pipe(sink->pipe, /* in = */ true); // sink is stdin
-            source->pipe[1] = sink->pipe[1];
-            sink->pipe[1] = INVALID_Q_PIPE;
-
-            return true;
-        }
-    }
-}
-
-void QProcessPrivate::destroyPipe(Q_PIPE pipe[2])
-{
-    if (pipe[0] == stdinChannel.pipe[0] && pipe[1] == stdinChannel.pipe[1] && pipeWriter) {
-        delete pipeWriter;
-        pipeWriter = 0;
-    }
-
-    if (pipe[0] != INVALID_Q_PIPE) {
-        CloseHandle(pipe[0]);
-        pipe[0] = INVALID_Q_PIPE;
-    }
-    if (pipe[1] != INVALID_Q_PIPE) {
-        CloseHandle(pipe[1]);
-        pipe[1] = INVALID_Q_PIPE;
-    }
-}
-
-
-static QString qt_create_commandline(const QString &program, const QStringList &arguments)
-{
-    QString args;
-    if (!program.isEmpty()) {
-        QString programName = program;
-        if (!programName.startsWith(QLatin1Char('\"')) && !programName.endsWith(QLatin1Char('\"')) && programName.contains(QLatin1Char(' ')))
-            programName = QLatin1Char('\"') + programName + QLatin1Char('\"');
-        programName.replace(QLatin1Char('/'), QLatin1Char('\\'));
-
-        // add the prgram as the first arg ... it works better
-        args = programName + QLatin1Char(' ');
-    }
-
-    for (int i=0; i<arguments.size(); ++i) {
-        QString tmp = arguments.at(i);
-        // Quotes are escaped and their preceding backslashes are doubled.
-        tmp.replace(QRegExp(QLatin1String("(\\\\*)\"")), QLatin1String("\\1\\1\\\""));
-        if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\t'))) {
-            // The argument must not end with a \ since this would be interpreted
-            // as escaping the quote -- rather put the \ behind the quote: e.g.
-            // rather use "foo"\ than "foo\"
-            int i = tmp.length();
-            while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\'))
-                --i;
-            tmp.insert(i, QLatin1Char('"'));
-            tmp.prepend(QLatin1Char('"'));
-        }
-        args += QLatin1Char(' ') + tmp;
-    }
-    return args;
-}
-
-QProcessEnvironment QProcessEnvironment::systemEnvironment()
-{
-    QProcessEnvironment env;
-#if !defined(Q_OS_WINCE)
-    // Calls to setenv() affect the low-level environment as well.
-    // This is not the case the other way round.
-    if (wchar_t *envStrings = GetEnvironmentStringsW()) {
-        for (const wchar_t *entry = envStrings; *entry; ) {
-            int entryLen = wcslen(entry);
-            // + 1 to permit magic cmd variable names starting with =
-            if (const wchar_t *equal = wcschr(entry + 1, L'=')) {
-                int nameLen = equal - entry;
-                QString name = QString::fromWCharArray(entry, nameLen);
-                QString value = QString::fromWCharArray(equal + 1, entryLen - nameLen - 1);
-                env.d->hash.insert(QProcessEnvironmentPrivate::Key(name), value);
-            }
-            entry += entryLen + 1;
-        }
-        FreeEnvironmentStringsW(envStrings);
-    }
-#endif
-    return env;
-}
-
-#if !defined(Q_OS_WINCE)
-static QByteArray qt_create_environment(const QProcessEnvironmentPrivate::Hash &environment)
-{
-    QByteArray envlist;
-    if (!environment.isEmpty()) {
-        QProcessEnvironmentPrivate::Hash copy = environment;
-
-        // add PATH if necessary (for DLL loading)
-        QProcessEnvironmentPrivate::Key pathKey(QLatin1String("PATH"));
-        if (!copy.contains(pathKey)) {
-            QByteArray path = qgetenv("PATH");
-            if (!path.isEmpty())
-                copy.insert(pathKey, QString::fromLocal8Bit(path));
-        }
-
-        // add systemroot if needed
-        QProcessEnvironmentPrivate::Key rootKey(QLatin1String("SystemRoot"));
-        if (!copy.contains(rootKey)) {
-            QByteArray systemRoot = qgetenv("SystemRoot");
-            if (!systemRoot.isEmpty())
-                copy.insert(rootKey, QString::fromLocal8Bit(systemRoot));
-        }
-
-        int pos = 0;
-        QProcessEnvironmentPrivate::Hash::ConstIterator it = copy.constBegin(),
-                                                       end = copy.constEnd();
-
-        static const wchar_t equal = L'=';
-        static const wchar_t nul = L'\0';
-
-        for ( ; it != end; ++it) {
-            uint tmpSize = sizeof(wchar_t) * (it.key().length() + it.value().length() + 2);
-            // ignore empty strings
-            if (tmpSize == sizeof(wchar_t) * 2)
-                continue;
-            envlist.resize(envlist.size() + tmpSize);
-
-            tmpSize = it.key().length() * sizeof(wchar_t);
-            memcpy(envlist.data()+pos, it.key().utf16(), tmpSize);
-            pos += tmpSize;
-
-            memcpy(envlist.data()+pos, &equal, sizeof(wchar_t));
-            pos += sizeof(wchar_t);
-
-            tmpSize = it.value().length() * sizeof(wchar_t);
-            memcpy(envlist.data()+pos, it.value().utf16(), tmpSize);
-            pos += tmpSize;
-
-            memcpy(envlist.data()+pos, &nul, sizeof(wchar_t));
-            pos += sizeof(wchar_t);
-        }
-        // add the 2 terminating 0 (actually 4, just to be on the safe side)
-        envlist.resize( envlist.size()+4 );
-        envlist[pos++] = 0;
-        envlist[pos++] = 0;
-        envlist[pos++] = 0;
-        envlist[pos++] = 0;
-    }
-    return envlist;
-}
-#endif
-
-void QProcessPrivate::startProcess()
-{
-    Q_Q(QProcess);
-
-    bool success = false;
-
-    if (pid) {
-        CloseHandle(pid->hThread);
-        CloseHandle(pid->hProcess);
-        delete pid;
-        pid = 0;
-    }
-    pid = new PROCESS_INFORMATION;
-    memset(pid, 0, sizeof(PROCESS_INFORMATION));
-
-    q->setProcessState(QProcess::Starting);
-
-    if (!createChannel(stdinChannel) ||
-        !createChannel(stdoutChannel) ||
-        !createChannel(stderrChannel))
-        return;
-
-#if defined(Q_OS_WINCE)
-    QString args = qt_create_commandline(QString(), arguments);
-#else
-    QString args = qt_create_commandline(program, arguments);
-    QByteArray envlist;
-    if (environment.d.constData())
-        envlist = qt_create_environment(environment.d.constData()->hash);
-#endif
-    if (!nativeArguments.isEmpty()) {
-        if (!args.isEmpty())
-             args += QLatin1Char(' ');
-        args += nativeArguments;
-    }
-
-#if defined QPROCESS_DEBUG
-    qDebug("Creating process");
-    qDebug("   program : [%s]", program.toLatin1().constData());
-    qDebug("   args : %s", args.toLatin1().constData());
-    qDebug("   pass environment : %s", environment.isEmpty() ? "no" : "yes");
-#endif
-
-#if defined(Q_OS_WINCE)
-    QString fullPathProgram = program;
-    if (!QDir::isAbsolutePath(fullPathProgram))
-        fullPathProgram = QFileInfo(fullPathProgram).absoluteFilePath();
-    fullPathProgram.replace(QLatin1Char('/'), QLatin1Char('\\'));
-    success = CreateProcess((wchar_t*)fullPathProgram.utf16(),
-                            (wchar_t*)args.utf16(),
-                            0, 0, false, 0, 0, 0, 0, pid);
-#else
-    DWORD dwCreationFlags = CREATE_NO_WINDOW;
-    dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
-    STARTUPINFOW startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
-                                 (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
-                                 (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
-                                 0, 0, 0,
-                                 STARTF_USESTDHANDLES,
-                                 0, 0, 0,
-                                 stdinChannel.pipe[0], stdoutChannel.pipe[1], stderrChannel.pipe[1]
-    };
-    success = CreateProcess(0, (wchar_t*)args.utf16(),
-                            0, 0, TRUE, dwCreationFlags,
-                            environment.isEmpty() ? 0 : envlist.data(),
-                            workingDirectory.isEmpty() ? 0 : (wchar_t*)QDir::toNativeSeparators(workingDirectory).utf16(),
-                            &startupInfo, pid);
-    if (!success) {
-        // Capture the error string before we do CloseHandle below
-        q->setErrorString(QProcess::tr("Process failed to start: %1").arg(qt_error_string()));
-    }
-
-    if (stdinChannel.pipe[0] != INVALID_Q_PIPE) {
-        CloseHandle(stdinChannel.pipe[0]);
-        stdinChannel.pipe[0] = INVALID_Q_PIPE;
-    }
-    if (stdoutChannel.pipe[1] != INVALID_Q_PIPE) {
-        CloseHandle(stdoutChannel.pipe[1]);
-        stdoutChannel.pipe[1] = INVALID_Q_PIPE;
-    }
-    if (stderrChannel.pipe[1] != INVALID_Q_PIPE) {
-        CloseHandle(stderrChannel.pipe[1]);
-        stderrChannel.pipe[1] = INVALID_Q_PIPE;
-    }
-#endif // Q_OS_WINCE
-
-    if (!success) {
-        cleanup();
-        processError = QProcess::FailedToStart;
-        emit q->error(processError);
-        q->setProcessState(QProcess::NotRunning);
-        return;
-    }
-
-    q->setProcessState(QProcess::Running);
-    // User can call kill()/terminate() from the stateChanged() slot
-    // so check before proceeding 
-    if (!pid) 
-        return;
-
-    if (threadData->eventDispatcher) {
-        processFinishedNotifier = new QWinEventNotifier(pid->hProcess, q);
-        QObject::connect(processFinishedNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_processDied()));
-        processFinishedNotifier->setEnabled(true);
-        notifier = new QTimer(q);
-        QObject::connect(notifier, SIGNAL(timeout()), q, SLOT(_q_notified()));
-        notifier->start(NOTIFYTIMEOUT);
-    }
-
-    // give the process a chance to start ...
-    Sleep(SLEEPMIN * 2);
-    _q_startupNotification();
-}
-
-bool QProcessPrivate::processStarted()
-{
-    return processState == QProcess::Running;
-}
-
-qint64 QProcessPrivate::bytesAvailableFromStdout() const
-{
-    if (stdoutChannel.pipe[0] == INVALID_Q_PIPE)
-        return 0;
-
-    DWORD bytesAvail = 0;
-#if !defined(Q_OS_WINCE)
-       PeekNamedPipe(stdoutChannel.pipe[0], 0, 0, 0, &bytesAvail, 0);
-#if defined QPROCESS_DEBUG
-    qDebug("QProcessPrivate::bytesAvailableFromStdout() == %d", bytesAvail);
-#endif
-    if (processChannelMode == QProcess::ForwardedChannels && bytesAvail > 0) {
-        QByteArray buf(bytesAvail, 0);
-        DWORD bytesRead = 0;
-        if (ReadFile(stdoutChannel.pipe[0], buf.data(), buf.size(), &bytesRead, 0) && bytesRead > 0) {
-            HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
-            if (hStdout) {
-                DWORD bytesWritten = 0;
-                WriteFile(hStdout, buf.data(), bytesRead, &bytesWritten, 0);
-            }
-        }
-        bytesAvail = 0;
-    }
-#endif
-    return bytesAvail;
-}
-
-qint64 QProcessPrivate::bytesAvailableFromStderr() const
-{
-    if (stderrChannel.pipe[0] == INVALID_Q_PIPE)
-        return 0;
-
-    DWORD bytesAvail = 0;
-#if !defined(Q_OS_WINCE)
-       PeekNamedPipe(stderrChannel.pipe[0], 0, 0, 0, &bytesAvail, 0);
-#if defined QPROCESS_DEBUG
-    qDebug("QProcessPrivate::bytesAvailableFromStderr() == %d", bytesAvail);
-#endif
-    if (processChannelMode == QProcess::ForwardedChannels && bytesAvail > 0) {
-        QByteArray buf(bytesAvail, 0);
-        DWORD bytesRead = 0;
-        if (ReadFile(stderrChannel.pipe[0], buf.data(), buf.size(), &bytesRead, 0) && bytesRead > 0) {
-            HANDLE hStderr = GetStdHandle(STD_ERROR_HANDLE);
-            if (hStderr) {
-                DWORD bytesWritten = 0;
-                WriteFile(hStderr, buf.data(), bytesRead, &bytesWritten, 0);
-            }
-        }
-        bytesAvail = 0;
-    }
-#endif
-    return bytesAvail;
-}
-
-qint64 QProcessPrivate::readFromStdout(char *data, qint64 maxlen)
-{
-    DWORD read = qMin(maxlen, bytesAvailableFromStdout());
-    DWORD bytesRead = 0;
-
-    if (read > 0 && !ReadFile(stdoutChannel.pipe[0], data, read, &bytesRead, 0))
-        return -1;
-    return bytesRead;
-}
-
-qint64 QProcessPrivate::readFromStderr(char *data, qint64 maxlen)
-{
-    DWORD read = qMin(maxlen, bytesAvailableFromStderr());
-    DWORD bytesRead = 0;
-
-    if (read > 0 && !ReadFile(stderrChannel.pipe[0], data, read, &bytesRead, 0))
-        return -1;
-    return bytesRead;
-}
-
-
-static BOOL QT_WIN_CALLBACK qt_terminateApp(HWND hwnd, LPARAM procId)
-{
-    DWORD currentProcId = 0;
-    GetWindowThreadProcessId(hwnd, &currentProcId);
-    if (currentProcId == (DWORD)procId)
-           PostMessage(hwnd, WM_CLOSE, 0, 0);
-
-    return TRUE;
-}
-
-void QProcessPrivate::terminateProcess()
-{
-    if (pid) {
-        EnumWindows(qt_terminateApp, (LPARAM)pid->dwProcessId);
-        PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
-    }
-}
-
-void QProcessPrivate::killProcess()
-{
-    if (pid)
-        TerminateProcess(pid->hProcess, 0xf291);
-}
-
-bool QProcessPrivate::waitForStarted(int)
-{
-    Q_Q(QProcess);
-
-    if (processStarted())
-        return true;
-
-    if (processError == QProcess::FailedToStart)
-        return false;
-
-    processError = QProcess::Timedout;
-    q->setErrorString(QProcess::tr("Process operation timed out"));
-    return false;
-}
-
-bool QProcessPrivate::waitForReadyRead(int msecs)
-{
-    Q_Q(QProcess);
-
-#if defined(Q_OS_WINCE)
-    processError = QProcess::ReadError;
-    q->setErrorString(QProcess::tr("Error reading from process"));
-    emit q->error(processError);
-    return false;
-#endif
-
-    QIncrementalSleepTimer timer(msecs);
-
-    forever {
-        if (!writeBuffer.isEmpty() && !_q_canWrite())
-            return false;
-        if (pipeWriter && pipeWriter->waitForWrite(0))
-            timer.resetIncrements();
-        bool readyReadEmitted = false;
-        if (bytesAvailableFromStdout() != 0) {
-            readyReadEmitted = _q_canReadStandardOutput() ? true : readyReadEmitted;
-            timer.resetIncrements();
-        }
-
-        if (bytesAvailableFromStderr() != 0) {
-            readyReadEmitted = _q_canReadStandardError() ? true : readyReadEmitted;
-            timer.resetIncrements();
-        }
-
-        if (readyReadEmitted)
-            return true;
-
-        if (!pid)
-            return false;
-        if (WaitForSingleObject(pid->hProcess, 0) == WAIT_OBJECT_0) {
-            // find the return value if there is noew data to read
-            _q_processDied();
-            return false;
-        }
-
-        Sleep(timer.nextSleepTime());
-        if (timer.hasTimedOut())
-            break;
-    }
-
-    processError = QProcess::Timedout;
-    q->setErrorString(QProcess::tr("Process operation timed out"));
-    return false;
-}
-
-bool QProcessPrivate::waitForBytesWritten(int msecs)
-{
-    Q_Q(QProcess);
-
-#if defined(Q_OS_WINCE)
-    processError = QProcess::ReadError;
-    q->setErrorString(QProcess::tr("Error reading from process"));
-    emit q->error(processError);
-    return false;
-#endif
-
-    QIncrementalSleepTimer timer(msecs);
-
-    forever {
-        // Check if we have any data pending: the pipe writer has
-        // bytes waiting to written, or it has written data since the
-        // last time we called pipeWriter->waitForWrite().
-        bool pendingDataInPipe = pipeWriter && (pipeWriter->bytesToWrite() || pipeWriter->hadWritten());
-
-        // If we don't have pending data, and our write buffer is
-        // empty, we fail.
-        if (!pendingDataInPipe && writeBuffer.isEmpty())
-            return false;
-
-        // If we don't have pending data and we do have data in our
-        // write buffer, try to flush that data over to the pipe
-        // writer.  Fail on error.
-        if (!pendingDataInPipe) {
-            if (!_q_canWrite())
-                return false;
-        }
-
-        // Wait for the pipe writer to acknowledge that it has
-        // written. This will succeed if either the pipe writer has
-        // already written the data, or if it manages to write data
-        // within the given timeout. If the write buffer was non-empty
-        // and the pipeWriter is now dead, that means _q_canWrite()
-        // destroyed the writer after it successfully wrote the last
-        // batch.
-        if (!pipeWriter || pipeWriter->waitForWrite(0))
-            return true;
-
-        // If we wouldn't write anything, check if we can read stdout.
-        if (bytesAvailableFromStdout() != 0) {
-            _q_canReadStandardOutput();
-            timer.resetIncrements();
-        }
-
-        // Check if we can read stderr.
-        if (bytesAvailableFromStderr() != 0) {
-            _q_canReadStandardError();
-            timer.resetIncrements();
-        }
-
-        // Check if the process died while reading.
-        if (!pid)
-            return false;
-
-        // Wait for the process to signal any change in its state,
-        // such as incoming data, or if the process died.
-        if (WaitForSingleObject(pid->hProcess, 0) == WAIT_OBJECT_0) {
-            _q_processDied();
-            return false;
-        }
-
-        // Only wait for as long as we've been asked.
-        if (timer.hasTimedOut())
-            break;
-    }
-
-    processError = QProcess::Timedout;
-    q->setErrorString(QProcess::tr("Process operation timed out"));
-    return false;
-}
-
-
-bool QProcessPrivate::waitForFinished(int msecs)
-{
-    Q_Q(QProcess);
-#if defined QPROCESS_DEBUG
-    qDebug("QProcessPrivate::waitForFinished(%d)", msecs);
-#endif
-
-    QIncrementalSleepTimer timer(msecs);
-
-    forever {
-        if (!writeBuffer.isEmpty() && !_q_canWrite())
-            return false;
-        if (pipeWriter && pipeWriter->waitForWrite(0))
-            timer.resetIncrements();
-
-        if (bytesAvailableFromStdout() != 0) {
-            _q_canReadStandardOutput();
-            timer.resetIncrements();
-        }
-
-        if (bytesAvailableFromStderr() != 0) {
-            _q_canReadStandardError();
-            timer.resetIncrements();
-        }
-
-        if (!pid)
-            return true;
-
-        if (WaitForSingleObject(pid->hProcess, timer.nextSleepTime()) == WAIT_OBJECT_0) {
-            _q_processDied();
-            return true;
-        }
-
-        if (timer.hasTimedOut())
-            break;
-    }
-    processError = QProcess::Timedout;
-    q->setErrorString(QProcess::tr("Process operation timed out"));
-    return false;
-}
-
-
-void QProcessPrivate::findExitCode()
-{
-    DWORD theExitCode;
-    if (GetExitCodeProcess(pid->hProcess, &theExitCode)) {
-        exitCode = theExitCode;
-        //### for now we assume a crash if exit code is less than -1 or the magic number
-        crashed = (exitCode == 0xf291 || (int)exitCode < 0);
-    }
-}
-
-void QProcessPrivate::flushPipeWriter()
-{
-    if (pipeWriter && pipeWriter->bytesToWrite() > 0) {
-        pipeWriter->waitForWrite(ULONG_MAX);
-    }
-}
-
-qint64 QProcessPrivate::pipeWriterBytesToWrite() const
-{
-    return pipeWriter ? pipeWriter->bytesToWrite() : qint64(0);
-}
-
-qint64 QProcessPrivate::writeToStdin(const char *data, qint64 maxlen)
-{
-    Q_Q(QProcess);
-
-#if defined(Q_OS_WINCE)
-    processError = QProcess::WriteError;
-    q->setErrorString(QProcess::tr("Error writing to process"));
-    emit q->error(processError);
-    return -1;
-#endif
-
-    if (!pipeWriter) {
-        pipeWriter = new QWindowsPipeWriter(stdinChannel.pipe[1], q);
-        pipeWriter->start();
-    }
-
-    return pipeWriter->write(data, maxlen);
-}
-
-bool QProcessPrivate::waitForWrite(int msecs)
-{
-    Q_Q(QProcess);
-
-    if (!pipeWriter || pipeWriter->waitForWrite(msecs))
-        return true;
-
-    processError = QProcess::Timedout;
-    q->setErrorString(QProcess::tr("Process operation timed out"));
-    return false;
-}
-
-void QProcessPrivate::_q_notified()
-{
-    notifier->stop();
-
-    if (!writeBuffer.isEmpty() && (!pipeWriter || pipeWriter->waitForWrite(0)))
-        _q_canWrite();
-
-    if (bytesAvailableFromStdout())
-        _q_canReadStandardOutput();
-
-    if (bytesAvailableFromStderr())
-        _q_canReadStandardError();
-
-    if (processState != QProcess::NotRunning)
-        notifier->start(NOTIFYTIMEOUT);
-}
-
-bool QProcessPrivate::startDetached(const QString &program, const QStringList &arguments, const QString &workingDir, qint64 *pid)
-{
-#if defined(Q_OS_WINCE)
-    Q_UNUSED(workingDir);
-    QString args = qt_create_commandline(QString(), arguments);
-#else
-    QString args = qt_create_commandline(program, arguments);
-#endif
-
-    bool success = false;
-
-    PROCESS_INFORMATION pinfo;
-
-#if defined(Q_OS_WINCE)
-        QString fullPathProgram = program;
-        if (!QDir::isAbsolutePath(fullPathProgram))
-            fullPathProgram.prepend(QDir::currentPath().append(QLatin1Char('/')));
-        fullPathProgram.replace(QLatin1Char('/'), QLatin1Char('\\'));
-        success = CreateProcess((wchar_t*)fullPathProgram.utf16(),
-                                (wchar_t*)args.utf16(),
-                                0, 0, false, CREATE_NEW_CONSOLE, 0, 0, 0, &pinfo);
-#else
-        STARTUPINFOW startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
-                                     (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
-                                     (ulong)CW_USEDEFAULT, (ulong)CW_USEDEFAULT,
-                                     0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-                                   };
-        success = CreateProcess(0, (wchar_t*)args.utf16(),
-                                0, 0, FALSE, CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE, 0,
-                                workingDir.isEmpty() ? 0 : (wchar_t*)workingDir.utf16(),
-                                &startupInfo, &pinfo);
-#endif // Q_OS_WINCE
-
-    if (success) {
-        CloseHandle(pinfo.hThread);
-        CloseHandle(pinfo.hProcess);
-        if (pid)
-            *pid = pinfo.dwProcessId;
-    }
-
-    return success;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PROCESS
diff --git a/src/core/io/qsettings_mac.cpp b/src/core/io/qsettings_mac.cpp
deleted file mode 100644 (file)
index 4d2b003..0000000
+++ /dev/null
@@ -1,736 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsettings.h"
-#include "qsettings_p.h"
-#include "qdatetime.h"
-#include "qdir.h"
-#include "qvarlengtharray.h"
-#include "qcore_mac_p.h"
-#ifndef QT_BOOTSTRAPPED
-#include "qcoreapplication.h"
-#endif
-#if __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-#include <Security/SecCode.h>
-#include <Security/SecRequirement.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-static const CFStringRef hostNames[2] = { kCFPreferencesCurrentHost, kCFPreferencesAnyHost };
-static const int numHostNames = 2;
-
-/*
-    On the Mac, it is more natural to use '.' as the key separator
-    than '/'. Therefore, it makes sense to replace '/' with '.' in
-    keys. Then we replace '.' with middle dots (which we can't show
-    here) and middle dots with '/'. A key like "4.0/BrowserCommand"
-    becomes "4<middot>0.BrowserCommand".
-*/
-
-enum RotateShift { Macify = 1, Qtify = 2 };
-
-static QString rotateSlashesDotsAndMiddots(const QString &key, int shift)
-{
-    static const int NumKnights = 3;
-    static const char knightsOfTheRoundTable[NumKnights] = { '/', '.', '\xb7' };
-    QString result = key;
-
-    for (int i = 0; i < result.size(); ++i) {
-        for (int j = 0; j < NumKnights; ++j) {
-            if (result.at(i) == QLatin1Char(knightsOfTheRoundTable[j])) {
-                result[i] = QLatin1Char(knightsOfTheRoundTable[(j + shift) % NumKnights]).unicode();
-                break;
-            }
-        }
-    }
-    return result;
-}
-
-static QCFType<CFStringRef> macKey(const QString &key)
-{
-    return QCFString::toCFStringRef(rotateSlashesDotsAndMiddots(key, Macify));
-}
-
-static QString qtKey(CFStringRef cfkey)
-{
-    return rotateSlashesDotsAndMiddots(QCFString::toQString(cfkey), Qtify);
-}
-
-static QCFType<CFPropertyListRef> macValue(const QVariant &value);
-
-static CFArrayRef macList(const QList<QVariant> &list)
-{
-    int n = list.size();
-    QVarLengthArray<QCFType<CFPropertyListRef> > cfvalues(n);
-    for (int i = 0; i < n; ++i)
-        cfvalues[i] = macValue(list.at(i));
-    return CFArrayCreate(kCFAllocatorDefault, reinterpret_cast<const void **>(cfvalues.data()),
-                         CFIndex(n), &kCFTypeArrayCallBacks);
-}
-
-static QCFType<CFPropertyListRef> macValue(const QVariant &value)
-{
-    CFPropertyListRef result = 0;
-
-    switch (value.type()) {
-    case QVariant::ByteArray:
-        {
-            QByteArray ba = value.toByteArray();
-            result = CFDataCreate(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(ba.data()),
-                                  CFIndex(ba.size()));
-        }
-        break;
-    // should be same as below (look for LIST)
-    case QVariant::List:
-    case QVariant::StringList:
-    case QVariant::Polygon:
-        result = macList(value.toList());
-        break;
-    case QVariant::Map:
-        {
-            /*
-                QMap<QString, QVariant> is potentially a multimap,
-                whereas CFDictionary is a single-valued map. To allow
-                for multiple values with the same key, we store
-                multiple values in a CFArray. To avoid ambiguities,
-                we also wrap lists in a CFArray singleton.
-            */
-            QMap<QString, QVariant> map = value.toMap();
-            QMap<QString, QVariant>::const_iterator i = map.constBegin();
-
-            int maxUniqueKeys = map.size();
-            int numUniqueKeys = 0;
-            QVarLengthArray<QCFType<CFPropertyListRef> > cfkeys(maxUniqueKeys);
-            QVarLengthArray<QCFType<CFPropertyListRef> > cfvalues(maxUniqueKeys);
-
-            while (i != map.constEnd()) {
-                const QString &key = i.key();
-                QList<QVariant> values;
-
-                do {
-                    values << i.value();
-                    ++i;
-                } while (i != map.constEnd() && i.key() == key);
-
-                bool singleton = (values.count() == 1);
-                if (singleton) {
-                    switch (values.first().type()) {
-                    // should be same as above (look for LIST)
-                    case QVariant::List:
-                    case QVariant::StringList:
-                    case QVariant::Polygon:
-                        singleton = false;
-                    default:
-                        ;
-                    }
-                }
-
-                cfkeys[numUniqueKeys] = QCFString::toCFStringRef(key);
-                cfvalues[numUniqueKeys] = singleton ? macValue(values.first()) : macList(values);
-                ++numUniqueKeys;
-            }
-
-            result = CFDictionaryCreate(kCFAllocatorDefault,
-                                        reinterpret_cast<const void **>(cfkeys.data()),
-                                        reinterpret_cast<const void **>(cfvalues.data()),
-                                        CFIndex(numUniqueKeys),
-                                        &kCFTypeDictionaryKeyCallBacks,
-                                        &kCFTypeDictionaryValueCallBacks);
-        }
-        break;
-    case QVariant::DateTime:
-        {
-            /*
-                CFDate, unlike QDateTime, doesn't store timezone information.
-            */
-            QDateTime dt = value.toDateTime();
-            if (dt.timeSpec() == Qt::LocalTime) {
-                QDateTime reference;
-                reference.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970);
-                result = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTime(reference.secsTo(dt)));
-            } else {
-                goto string_case;
-            }
-        }
-        break;
-    case QVariant::Bool:
-        result = value.toBool() ? kCFBooleanTrue : kCFBooleanFalse;
-        break;
-    case QVariant::Int:
-    case QVariant::UInt:
-        {
-            int n = value.toInt();
-            result = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &n);
-        }
-        break;
-    case QVariant::Double:
-        {
-            double n = value.toDouble();
-            result = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &n);
-        }
-        break;
-    case QVariant::LongLong:
-    case QVariant::ULongLong:
-        {
-            qint64 n = value.toLongLong();
-            result = CFNumberCreate(0, kCFNumberLongLongType, &n);
-        }
-        break;
-    case QVariant::String:
-    string_case:
-    default:
-        result = QCFString::toCFStringRef(QSettingsPrivate::variantToString(value));
-    }
-    return result;
-}
-
-static QVariant qtValue(CFPropertyListRef cfvalue)
-{
-    if (!cfvalue)
-        return QVariant();
-
-    CFTypeID typeId = CFGetTypeID(cfvalue);
-
-    /*
-        Sorted grossly from most to least frequent type.
-    */
-    if (typeId == CFStringGetTypeID()) {
-        return QSettingsPrivate::stringToVariant(QCFString::toQString(static_cast<CFStringRef>(cfvalue)));
-    } else if (typeId == CFNumberGetTypeID()) {
-        CFNumberRef cfnumber = static_cast<CFNumberRef>(cfvalue);
-        if (CFNumberIsFloatType(cfnumber)) {
-            double d;
-            CFNumberGetValue(cfnumber, kCFNumberDoubleType, &d);
-            return d;
-        } else {
-            int i;
-            qint64 ll;
-
-            if (CFNumberGetValue(cfnumber, kCFNumberIntType, &i))
-                return i;
-            CFNumberGetValue(cfnumber, kCFNumberLongLongType, &ll);
-            return ll;
-        }
-    } else if (typeId == CFArrayGetTypeID()) {
-        CFArrayRef cfarray = static_cast<CFArrayRef>(cfvalue);
-        QList<QVariant> list;
-        CFIndex size = CFArrayGetCount(cfarray);
-        bool metNonString = false;
-        for (CFIndex i = 0; i < size; ++i) {
-            QVariant value = qtValue(CFArrayGetValueAtIndex(cfarray, i));
-            if (value.type() != QVariant::String)
-                metNonString = true;
-            list << value;
-        }
-        if (metNonString)
-            return list;
-        else
-            return QVariant(list).toStringList();
-    } else if (typeId == CFBooleanGetTypeID()) {
-        return (bool)CFBooleanGetValue(static_cast<CFBooleanRef>(cfvalue));
-    } else if (typeId == CFDataGetTypeID()) {
-        CFDataRef cfdata = static_cast<CFDataRef>(cfvalue);
-        return QByteArray(reinterpret_cast<const char *>(CFDataGetBytePtr(cfdata)),
-                          CFDataGetLength(cfdata));
-    } else if (typeId == CFDictionaryGetTypeID()) {
-        CFDictionaryRef cfdict = static_cast<CFDictionaryRef>(cfvalue);
-        CFTypeID arrayTypeId = CFArrayGetTypeID();
-        int size = (int)CFDictionaryGetCount(cfdict);
-        QVarLengthArray<CFPropertyListRef> keys(size);
-        QVarLengthArray<CFPropertyListRef> values(size);
-        CFDictionaryGetKeysAndValues(cfdict, keys.data(), values.data());
-
-        QMultiMap<QString, QVariant> map;
-        for (int i = 0; i < size; ++i) {
-            QString key = QCFString::toQString(static_cast<CFStringRef>(keys[i]));
-
-            if (CFGetTypeID(values[i]) == arrayTypeId) {
-                CFArrayRef cfarray = static_cast<CFArrayRef>(values[i]);
-                CFIndex arraySize = CFArrayGetCount(cfarray);
-                for (CFIndex j = arraySize - 1; j >= 0; --j)
-                    map.insert(key, qtValue(CFArrayGetValueAtIndex(cfarray, j)));
-            } else {
-                map.insert(key, qtValue(values[i]));
-            }
-        }
-        return map;
-    } else if (typeId == CFDateGetTypeID()) {
-        QDateTime dt;
-        dt.setTime_t((uint)kCFAbsoluteTimeIntervalSince1970);
-        return dt.addSecs((int)CFDateGetAbsoluteTime(static_cast<CFDateRef>(cfvalue)));
-    }
-    return QVariant();
-}
-
-static QString comify(const QString &organization)
-{
-    for (int i = organization.size() - 1; i >= 0; --i) {
-        QChar ch = organization.at(i);
-        if (ch == QLatin1Char('.') || ch == QChar(0x3002) || ch == QChar(0xff0e)
-                || ch == QChar(0xff61)) {
-            QString suffix = organization.mid(i + 1).toLower();
-            if (suffix.size() == 2 || suffix == QLatin1String("com")
-                    || suffix == QLatin1String("org") || suffix == QLatin1String("net")
-                    || suffix == QLatin1String("edu") || suffix == QLatin1String("gov")
-                    || suffix == QLatin1String("mil") || suffix == QLatin1String("biz")
-                    || suffix == QLatin1String("info") || suffix == QLatin1String("name")
-                    || suffix == QLatin1String("pro") || suffix == QLatin1String("aero")
-                    || suffix == QLatin1String("coop") || suffix == QLatin1String("museum")) {
-                QString result = organization;
-                result.replace(QLatin1Char('/'), QLatin1Char(' '));
-                return result;
-            }
-            break;
-        }
-        int uc = ch.unicode();
-        if ((uc < 'a' || uc > 'z') && (uc < 'A' || uc > 'Z'))
-            break;
-    }
-
-    QString domain;
-    for (int i = 0; i < organization.size(); ++i) {
-        QChar ch = organization.at(i);
-        int uc = ch.unicode();
-        if ((uc >= 'a' && uc <= 'z') || (uc >= '0' && uc <= '9')) {
-            domain += ch;
-        } else if (uc >= 'A' && uc <= 'Z') {
-            domain += ch.toLower();
-        } else {
-           domain += QLatin1Char(' ');
-        }
-    }
-    domain = domain.simplified();
-    domain.replace(QLatin1Char(' '), QLatin1Char('-'));
-    if (!domain.isEmpty())
-        domain.append(QLatin1String(".com"));
-    return domain;
-}
-
-class QMacSettingsPrivate : public QSettingsPrivate
-{
-public:
-    QMacSettingsPrivate(QSettings::Scope scope, const QString &organization,
-                        const QString &application);
-    QMacSettingsPrivate(CFStringRef bundleIdentifier);
-    ~QMacSettingsPrivate();
-
-    void remove(const QString &key);
-    void set(const QString &key, const QVariant &value);
-    bool get(const QString &key, QVariant *value) const;
-    QStringList children(const QString &prefix, ChildSpec spec) const;
-    void clear();
-    void sync();
-    void flush();
-    bool isWritable() const;
-    QString fileName() const;
-
-private:
-    struct SearchDomain
-    {
-        CFStringRef userName;
-        CFStringRef applicationOrSuiteId;
-    };
-
-    QCFString applicationId;
-    QCFString suiteId;
-    QCFString hostName;
-    SearchDomain domains[6];
-    int numDomains;
-};
-
-QMacSettingsPrivate::QMacSettingsPrivate(QSettings::Scope scope, const QString &organization,
-                                         const QString &application)
-    : QSettingsPrivate(QSettings::NativeFormat, scope, organization, application)
-{
-    QString javaPackageName;
-    int curPos = 0;
-    int nextDot;
-
-    QString domainName = comify(organization);
-    if (domainName.isEmpty()) {
-        setStatus(QSettings::AccessError);
-        domainName = QLatin1String("unknown-organization.trolltech.com");
-    }
-
-    while ((nextDot = domainName.indexOf(QLatin1Char('.'), curPos)) != -1) {
-        javaPackageName.prepend(domainName.mid(curPos, nextDot - curPos));
-        javaPackageName.prepend(QLatin1Char('.'));
-        curPos = nextDot + 1;
-    }
-    javaPackageName.prepend(domainName.mid(curPos));
-    javaPackageName = javaPackageName.toLower();
-    if (curPos == 0)
-        javaPackageName.prepend(QLatin1String("com."));
-    suiteId = javaPackageName;
-
-    if (scope == QSettings::SystemScope)
-        spec |= F_System;
-
-    if (application.isEmpty()) {
-        spec |= F_Organization;
-    } else {
-        javaPackageName += QLatin1Char('.');
-        javaPackageName += application;
-        applicationId = javaPackageName;
-    }
-
-    numDomains = 0;
-    for (int i = (spec & F_System) ? 1 : 0; i < 2; ++i) {
-        for (int j = (spec & F_Organization) ? 1 : 0; j < 3; ++j) {
-            SearchDomain &domain = domains[numDomains++];
-            domain.userName = (i == 0) ? kCFPreferencesCurrentUser : kCFPreferencesAnyUser;
-            if (j == 0)
-                domain.applicationOrSuiteId = applicationId;
-            else if (j == 1)
-                domain.applicationOrSuiteId = suiteId;
-            else
-                domain.applicationOrSuiteId = kCFPreferencesAnyApplication;
-        }
-    }
-
-    hostName = (scope == QSettings::SystemScope) ? kCFPreferencesCurrentHost : kCFPreferencesAnyHost;
-    sync();
-}
-
-QMacSettingsPrivate::QMacSettingsPrivate(CFStringRef bundleIdentifier)
-    : QSettingsPrivate(QSettings::NativeFormat, QSettings::UserScope, QString(), QString())
-{
-    // applicationId and suiteId are QCFStrings and take ownership, retain to prevent double deletes.
-    CFRetain(bundleIdentifier);
-    applicationId = bundleIdentifier;
-    CFRetain(bundleIdentifier);
-    suiteId = bundleIdentifier;
-
-    numDomains = 1;
-    domains[0].userName = kCFPreferencesCurrentUser;
-    domains[0].applicationOrSuiteId = bundleIdentifier;
-    hostName = kCFPreferencesAnyHost;
-    sync();
-}
-
-QMacSettingsPrivate::~QMacSettingsPrivate()
-{
-}
-
-void QMacSettingsPrivate::remove(const QString &key)
-{
-    QStringList keys = children(key + QLatin1Char('/'), AllKeys);
-
-    // If i == -1, then delete "key" itself.
-    for (int i = -1; i < keys.size(); ++i) {
-        QString subKey = key;
-        if (i >= 0) {
-            subKey += QLatin1Char('/');
-            subKey += keys.at(i);
-        }
-        CFPreferencesSetValue(macKey(subKey), 0, domains[0].applicationOrSuiteId,
-                              domains[0].userName, hostName);
-    }
-}
-
-void QMacSettingsPrivate::set(const QString &key, const QVariant &value)
-{
-    CFPreferencesSetValue(macKey(key), macValue(value), domains[0].applicationOrSuiteId,
-                          domains[0].userName, hostName);
-}
-
-bool QMacSettingsPrivate::get(const QString &key, QVariant *value) const
-{
-    QCFString k = macKey(key);
-    for (int i = 0; i < numDomains; ++i) {
-        for (int j = 0; j < numHostNames; ++j) {
-            QCFType<CFPropertyListRef> ret =
-                    CFPreferencesCopyValue(k, domains[i].applicationOrSuiteId, domains[i].userName,
-                                           hostNames[j]);
-            if (ret) {
-                if (value)
-                    *value = qtValue(ret);
-                return true;
-            }
-        }
-
-        if (!fallbacks)
-            break;
-    }
-    return false;
-}
-
-QStringList QMacSettingsPrivate::children(const QString &prefix, ChildSpec spec) const
-{
-    QMap<QString, QString> result;
-    int startPos = prefix.size();
-
-    for (int i = 0; i < numDomains; ++i) {
-        for (int j = 0; j < numHostNames; ++j) {
-            QCFType<CFArrayRef> cfarray = CFPreferencesCopyKeyList(domains[i].applicationOrSuiteId,
-                                                                   domains[i].userName,
-                                                                   hostNames[j]);
-            if (cfarray) {
-                CFIndex size = CFArrayGetCount(cfarray);
-                for (CFIndex k = 0; k < size; ++k) {
-                    QString currentKey =
-                            qtKey(static_cast<CFStringRef>(CFArrayGetValueAtIndex(cfarray, k)));
-                    if (currentKey.startsWith(prefix))
-                        processChild(currentKey.mid(startPos), spec, result);
-                }
-            }
-        }
-
-        if (!fallbacks)
-            break;
-    }
-    return result.keys();
-}
-
-void QMacSettingsPrivate::clear()
-{
-    QCFType<CFArrayRef> cfarray = CFPreferencesCopyKeyList(domains[0].applicationOrSuiteId,
-                                                           domains[0].userName, hostName);
-    CFPreferencesSetMultiple(0, cfarray, domains[0].applicationOrSuiteId, domains[0].userName,
-                             hostName);
-}
-
-void QMacSettingsPrivate::sync()
-{
-    for (int i = 0; i < numDomains; ++i) {
-        for (int j = 0; j < numHostNames; ++j) {
-            Boolean ok = CFPreferencesSynchronize(domains[i].applicationOrSuiteId,
-                                                  domains[i].userName, hostNames[j]);
-            // only report failures for the primary file (the one we write to)
-            if (!ok && i == 0 && hostNames[j] == hostName && status == QSettings::NoError) {
-#if 1
-                // work around what seems to be a bug in CFPreferences:
-                // don't report an error if there are no preferences for the application
-                QCFType<CFArrayRef> appIds = CFPreferencesCopyApplicationList(domains[i].userName,
-                                                                              hostNames[j]);
-
-                // iterate through all the applications and see if we're there
-                CFIndex size = CFArrayGetCount(appIds);
-                for (CFIndex k = 0; k < size; ++k) {
-                    const void *cfvalue = CFArrayGetValueAtIndex(appIds, k);
-                    if (CFGetTypeID(cfvalue) == CFStringGetTypeID()) {
-                        if (CFStringCompare(static_cast<CFStringRef>(cfvalue),
-                                            domains[i].applicationOrSuiteId,
-                                            kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
-                            setStatus(QSettings::AccessError);
-                            break;
-                        }
-                    }
-                }
-#else
-                setStatus(QSettings::AccessError);
-#endif
-            }
-        }
-    }
-}
-
-void QMacSettingsPrivate::flush()
-{
-    sync();
-}
-
-bool QMacSettingsPrivate::isWritable() const
-{
-    QMacSettingsPrivate *that = const_cast<QMacSettingsPrivate *>(this);
-    QString impossibleKey(QLatin1String("qt_internal/"));
-
-    QSettings::Status oldStatus = that->status;
-    that->status = QSettings::NoError;
-
-    that->set(impossibleKey, QVariant());
-    that->sync();
-    bool writable = (status == QSettings::NoError) && that->get(impossibleKey, 0);
-    that->remove(impossibleKey);
-    that->sync();
-
-    that->status = oldStatus;
-    return writable;
-}
-
-QString QMacSettingsPrivate::fileName() const
-{
-    QString result;
-    if ((spec & F_System) == 0)
-        result = QDir::homePath();
-    result += QLatin1String("/Library/Preferences/");
-    result += QCFString::toQString(domains[0].applicationOrSuiteId);
-    result += QLatin1String(".plist");
-    return result;
-}
-
-QSettingsPrivate *QSettingsPrivate::create(QSettings::Format format,
-                                           QSettings::Scope scope,
-                                           const QString &organization,
-                                           const QString &application)
-{
-#ifndef QT_BOOTSTRAPPED
-    static bool useAppLocalStorage = false;
-    static bool initialized = false;
-
-    if (!initialized) {
-        bool inSandbox = false;
-
-#if __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-        // If we are running on at least 10.7.0 and have the com.apple.security.app-sandbox
-        // entitlement, we are in a sandbox
-        SInt32 version = 0;
-        Gestalt(gestaltSystemVersion, &version);
-        SecCodeRef secCodeSelf;
-        if (version >= 0x1070 && SecCodeCopySelf(kSecCSDefaultFlags, &secCodeSelf) == errSecSuccess) {
-            SecRequirementRef sandboxReq;
-            CFStringRef entitlement = CFSTR("entitlement [\"com.apple.security.app-sandbox\"]");
-            if (SecRequirementCreateWithString(entitlement, kSecCSDefaultFlags, &sandboxReq) == errSecSuccess) {
-                if (SecCodeCheckValidity(secCodeSelf, kSecCSDefaultFlags, sandboxReq) == errSecSuccess)
-                    inSandbox = true;
-                CFRelease(sandboxReq);
-            }
-            CFRelease(secCodeSelf);
-        }
-#endif
-
-        bool forAppStore = false;
-        if (!inSandbox) {
-            CFTypeRef val = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), CFSTR("ForAppStore"));
-            forAppStore = (val &&
-                           CFGetTypeID(val) == CFStringGetTypeID() &&
-                           CFStringCompare(CFStringRef(val), CFSTR("yes"), kCFCompareCaseInsensitive) == 0);
-        }
-
-        useAppLocalStorage = inSandbox || forAppStore;
-        initialized = true;
-    }
-
-    if (useAppLocalStorage) {
-        // Ensure that the global and app-local settings go to the same file, since that's
-        // what we really want
-        if (organization == QLatin1String("Trolltech") ||
-                organization.isEmpty() ||
-                (organization == qApp->organizationDomain() && application == qApp->applicationName()) ||
-                (organization == qApp->organizationName()) && application == qApp->applicationName())
-        {
-            CFStringRef bundleIdentifier = CFBundleGetIdentifier(CFBundleGetMainBundle());
-            if (!bundleIdentifier) {
-                qWarning("QSettingsPrivate::create: You must set the bundle identifier when using ForAppStore");
-            } else {
-                QSettingsPrivate* settings = new QMacSettingsPrivate(bundleIdentifier);
-                if (organization == QLatin1String("Trolltech"))
-                    settings->beginGroupOrArray(QSettingsGroup("QtLibrarySettings"));
-                return settings;
-            }
-        }
-   }
-#endif
-
-    if (format == QSettings::NativeFormat) {
-        return new QMacSettingsPrivate(scope, organization, application);
-    } else {
-        return new QConfFileSettingsPrivate(format, scope, organization, application);
-    }
-}
-
-static QCFType<CFURLRef> urlFromFileName(const QString &fileName)
-{
-    return CFURLCreateWithFileSystemPath(kCFAllocatorDefault, QCFString(fileName),
-                                         kCFURLPOSIXPathStyle, false);
-}
-
-bool QConfFileSettingsPrivate::readPlistFile(const QString &fileName, ParsedSettingsMap *map) const
-{
-    QCFType<CFDataRef> resource;
-    SInt32 code;
-    if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, urlFromFileName(fileName),
-                                                  &resource, 0, 0, &code))
-        return false;
-
-    QCFString errorStr;
-    QCFType<CFPropertyListRef> propertyList =
-            CFPropertyListCreateFromXMLData(kCFAllocatorDefault, resource, kCFPropertyListImmutable,
-                                            &errorStr);
-
-    if (!propertyList)
-        return true;
-    if (CFGetTypeID(propertyList) != CFDictionaryGetTypeID())
-        return false;
-
-    CFDictionaryRef cfdict =
-            static_cast<CFDictionaryRef>(static_cast<CFPropertyListRef>(propertyList));
-    int size = (int)CFDictionaryGetCount(cfdict);
-    QVarLengthArray<CFPropertyListRef> keys(size);
-    QVarLengthArray<CFPropertyListRef> values(size);
-    CFDictionaryGetKeysAndValues(cfdict, keys.data(), values.data());
-
-    for (int i = 0; i < size; ++i) {
-        QString key = qtKey(static_cast<CFStringRef>(keys[i]));
-        map->insert(QSettingsKey(key, Qt::CaseSensitive), qtValue(values[i]));
-    }
-    return true;
-}
-
-bool QConfFileSettingsPrivate::writePlistFile(const QString &fileName,
-                                              const ParsedSettingsMap &map) const
-{
-    QVarLengthArray<QCFType<CFStringRef> > cfkeys(map.size());
-    QVarLengthArray<QCFType<CFPropertyListRef> > cfvalues(map.size());
-    int i = 0;
-    ParsedSettingsMap::const_iterator j;
-    for (j = map.constBegin(); j != map.constEnd(); ++j) {
-        cfkeys[i] = macKey(j.key());
-        cfvalues[i] = macValue(j.value());
-        ++i;
-    }
-
-    QCFType<CFDictionaryRef> propertyList =
-            CFDictionaryCreate(kCFAllocatorDefault,
-                               reinterpret_cast<const void **>(cfkeys.data()),
-                               reinterpret_cast<const void **>(cfvalues.data()),
-                               CFIndex(map.size()),
-                               &kCFTypeDictionaryKeyCallBacks,
-                               &kCFTypeDictionaryValueCallBacks);
-
-    QCFType<CFDataRef> xmlData = CFPropertyListCreateXMLData(kCFAllocatorDefault, propertyList);
-
-    SInt32 code;
-    return CFURLWriteDataAndPropertiesToResource(urlFromFileName(fileName), xmlData, 0, &code);
-}
-
-QT_END_NAMESPACE
diff --git a/src/core/io/qsettings_win.cpp b/src/core/io/qsettings_win.cpp
deleted file mode 100644 (file)
index 2f6ca78..0000000
+++ /dev/null
@@ -1,847 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsettings.h"
-
-#ifndef QT_NO_SETTINGS
-
-#include "qsettings_p.h"
-#include "qvector.h"
-#include "qmap.h"
-#include "qt_windows.h"
-#include "qdebug.h"
-
-QT_BEGIN_NAMESPACE
-
-/*  Keys are stored in QStrings. If the variable name starts with 'u', this is a "user"
-    key, ie. "foo/bar/alpha/beta". If the variable name starts with 'r', this is a "registry"
-    key, ie. "\foo\bar\alpha\beta". */
-
-/*******************************************************************************
-** Some convenience functions
-*/
-
-/*
-  We don't use KEY_ALL_ACCESS because it gives more rights than what we
-  need. See task 199061.
- */
-static const REGSAM registryPermissions = KEY_READ | KEY_WRITE;
-
-static QString keyPath(const QString &rKey)
-{
-    int idx = rKey.lastIndexOf(QLatin1Char('\\'));
-    if (idx == -1)
-        return QString();
-    return rKey.left(idx + 1);
-}
-
-static QString keyName(const QString &rKey)
-{
-    int idx = rKey.lastIndexOf(QLatin1Char('\\'));
-
-    QString res;
-    if (idx == -1)
-        res = rKey;
-    else
-        res = rKey.mid(idx + 1);
-
-    if (res == QLatin1String("Default") || res == QLatin1String("."))
-        res = QLatin1String("");
-
-    return res;
-}
-
-static QString escapedKey(QString uKey)
-{
-    QChar *data = uKey.data();
-    int l = uKey.length();
-    for (int i = 0; i < l; ++i) {
-        ushort &ucs = data[i].unicode();
-        if (ucs == '\\')
-            ucs = '/';
-        else if (ucs == '/')
-            ucs = '\\';
-    }
-    return uKey;
-}
-
-static QString unescapedKey(QString rKey)
-{
-    return escapedKey(rKey);
-}
-
-typedef QMap<QString, QString> NameSet;
-
-static void mergeKeySets(NameSet *dest, const NameSet &src)
-{
-    NameSet::const_iterator it = src.constBegin();
-    for (; it != src.constEnd(); ++it)
-        dest->insert(unescapedKey(it.key()), QString());
-}
-
-static void mergeKeySets(NameSet *dest, const QStringList &src)
-{
-    QStringList::const_iterator it = src.constBegin();
-    for (; it != src.constEnd(); ++it)
-        dest->insert(unescapedKey(*it), QString());
-}
-
-/*******************************************************************************
-** Wrappers for the insane windows registry API
-*/
-
-static QString errorCodeToString(DWORD errorCode)
-{
-    wchar_t *data = 0;
-    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, errorCode, 0, data, 0, 0);
-    QString result = QString::fromWCharArray(data);
-
-    if (data != 0)
-        LocalFree(data);
-
-    if (result.endsWith(QLatin1Char('\n')))
-        result.truncate(result.length() - 1);
-
-    return result;
-}
-
-// Open a key with the specified perms
-static HKEY openKey(HKEY parentHandle, REGSAM perms, const QString &rSubKey)
-{
-    HKEY resultHandle = 0;
-    LONG res = RegOpenKeyEx(parentHandle, reinterpret_cast<const wchar_t *>(rSubKey.utf16()),
-                            0, perms, &resultHandle);
-
-    if (res == ERROR_SUCCESS)
-        return resultHandle;
-
-    return 0;
-}
-
-// Open a key with the specified perms, create it if it does not exist
-static HKEY createOrOpenKey(HKEY parentHandle, REGSAM perms, const QString &rSubKey)
-{
-    // try to open it
-    HKEY resultHandle = openKey(parentHandle, perms, rSubKey);
-    if (resultHandle != 0)
-        return resultHandle;
-
-    // try to create it
-    LONG res = RegCreateKeyEx(parentHandle, reinterpret_cast<const wchar_t *>(rSubKey.utf16()), 0, 0,
-                              REG_OPTION_NON_VOLATILE, perms, 0, &resultHandle, 0);
-
-    if (res == ERROR_SUCCESS)
-        return resultHandle;
-
-    //qWarning("QSettings: Failed to create subkey \"%s\": %s",
-    //        rSubKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
-
-    return 0;
-}
-
-// Open or create a key in read-write mode if possible, otherwise read-only
-static HKEY createOrOpenKey(HKEY parentHandle, const QString &rSubKey, bool *readOnly)
-{
-    // try to open or create it read/write
-    HKEY resultHandle = createOrOpenKey(parentHandle, registryPermissions, rSubKey);
-    if (resultHandle != 0) {
-        if (readOnly != 0)
-            *readOnly = false;
-        return resultHandle;
-    }
-
-    // try to open or create it read/only
-    resultHandle = createOrOpenKey(parentHandle, KEY_READ, rSubKey);
-    if (resultHandle != 0) {
-        if (readOnly != 0)
-            *readOnly = true;
-        return resultHandle;
-    }
-    return 0;
-}
-
-static QStringList childKeysOrGroups(HKEY parentHandle, QSettingsPrivate::ChildSpec spec)
-{
-    QStringList result;
-    DWORD numKeys;
-    DWORD maxKeySize;
-    DWORD numSubgroups;
-    DWORD maxSubgroupSize;
-
-    // Find the number of keys and subgroups, as well as the max of their lengths.
-    LONG res = RegQueryInfoKey(parentHandle, 0, 0, 0, &numSubgroups, &maxSubgroupSize, 0,
-                               &numKeys, &maxKeySize, 0, 0, 0);
-
-    if (res != ERROR_SUCCESS) {
-        qWarning("QSettings: RegQueryInfoKey() failed: %s", errorCodeToString(res).toLatin1().data());
-        return result;
-    }
-
-    ++maxSubgroupSize;
-    ++maxKeySize;
-
-    int n;
-    int m;
-    if (spec == QSettingsPrivate::ChildKeys) {
-        n = numKeys;
-        m = maxKeySize;
-    } else {
-        n = numSubgroups;
-        m = maxSubgroupSize;
-    }
-
-    /* The size does not include the terminating null character. */
-    ++m;
-
-    // Get the list
-    QByteArray buff(m * sizeof(wchar_t), 0);
-    for (int i = 0; i < n; ++i) {
-        QString item;
-        DWORD l = buff.size() / sizeof(wchar_t);
-        if (spec == QSettingsPrivate::ChildKeys) {
-            res = RegEnumValue(parentHandle, i, reinterpret_cast<wchar_t *>(buff.data()), &l, 0, 0, 0, 0);
-        } else {
-            res = RegEnumKeyEx(parentHandle, i, reinterpret_cast<wchar_t *>(buff.data()), &l, 0, 0, 0, 0);
-        }
-        if (res == ERROR_SUCCESS)
-            item = QString::fromWCharArray((const wchar_t *)buff.constData(), l);
-
-        if (res != ERROR_SUCCESS) {
-            qWarning("QSettings: RegEnumValue failed: %s", errorCodeToString(res).toLatin1().data());
-            continue;
-        }
-        if (item.isEmpty())
-            item = QLatin1String(".");
-        result.append(item);
-    }
-    return result;
-}
-
-static void allKeys(HKEY parentHandle, const QString &rSubKey, NameSet *result)
-{
-    HKEY handle = openKey(parentHandle, KEY_READ, rSubKey);
-    if (handle == 0)
-        return;
-
-    QStringList childKeys = childKeysOrGroups(handle, QSettingsPrivate::ChildKeys);
-    QStringList childGroups = childKeysOrGroups(handle, QSettingsPrivate::ChildGroups);
-    RegCloseKey(handle);
-
-    for (int i = 0; i < childKeys.size(); ++i) {
-        QString s = rSubKey;
-        if (!s.isEmpty())
-            s += QLatin1Char('\\');
-        s += childKeys.at(i);
-        result->insert(s, QString());
-    }
-
-    for (int i = 0; i < childGroups.size(); ++i) {
-        QString s = rSubKey;
-        if (!s.isEmpty())
-            s += QLatin1Char('\\');
-        s += childGroups.at(i);
-        allKeys(parentHandle, s, result);
-    }
-}
-
-static void deleteChildGroups(HKEY parentHandle)
-{
-    QStringList childGroups = childKeysOrGroups(parentHandle, QSettingsPrivate::ChildGroups);
-
-    for (int i = 0; i < childGroups.size(); ++i) {
-        QString group = childGroups.at(i);
-
-        // delete subgroups in group
-        HKEY childGroupHandle = openKey(parentHandle, registryPermissions, group);
-        if (childGroupHandle == 0)
-            continue;
-        deleteChildGroups(childGroupHandle);
-        RegCloseKey(childGroupHandle);
-
-        // delete group itself
-        LONG res = RegDeleteKey(parentHandle, reinterpret_cast<const wchar_t *>(group.utf16()));
-        if (res != ERROR_SUCCESS) {
-            qWarning("QSettings: RegDeleteKey failed on subkey \"%s\": %s",
-                      group.toLatin1().data(), errorCodeToString(res).toLatin1().data());
-            return;
-        }
-    }
-}
-
-/*******************************************************************************
-** class RegistryKey
-*/
-
-class RegistryKey
-{
-public:
-    RegistryKey(HKEY parent_handle = 0, const QString &key = QString(), bool read_only = true);
-    QString key() const;
-    HKEY handle() const;
-    HKEY parentHandle() const;
-    bool readOnly() const;
-    void close();
-private:
-    HKEY m_parent_handle;
-    mutable HKEY m_handle;
-    QString m_key;
-    mutable bool m_read_only;
-};
-
-RegistryKey::RegistryKey(HKEY parent_handle, const QString &key, bool read_only)
-{
-    m_parent_handle = parent_handle;
-    m_handle = 0;
-    m_read_only = read_only;
-    m_key = key;
-}
-
-QString RegistryKey::key() const
-{
-    return m_key;
-}
-
-HKEY RegistryKey::handle() const
-{
-    if (m_handle != 0)
-        return m_handle;
-
-    if (m_read_only)
-        m_handle = openKey(m_parent_handle, KEY_READ, m_key);
-    else
-        m_handle = createOrOpenKey(m_parent_handle, m_key, &m_read_only);
-
-    return m_handle;
-}
-
-HKEY RegistryKey::parentHandle() const
-{
-    return m_parent_handle;
-}
-
-bool RegistryKey::readOnly() const
-{
-    return m_read_only;
-}
-
-void RegistryKey::close()
-{
-    if (m_handle != 0)
-        RegCloseKey(m_handle);
-    m_handle = 0;
-}
-
-typedef QVector<RegistryKey> RegistryKeyList;
-
-/*******************************************************************************
-** class QWinSettingsPrivate
-*/
-
-class QWinSettingsPrivate : public QSettingsPrivate
-{
-public:
-    QWinSettingsPrivate(QSettings::Scope scope, const QString &organization,
-                        const QString &application);
-    QWinSettingsPrivate(QString rKey);
-    ~QWinSettingsPrivate();
-
-    void remove(const QString &uKey);
-    void set(const QString &uKey, const QVariant &value);
-    bool get(const QString &uKey, QVariant *value) const;
-    QStringList children(const QString &uKey, ChildSpec spec) const;
-    void clear();
-    void sync();
-    void flush();
-    bool isWritable() const;
-    HKEY writeHandle() const;
-    bool readKey(HKEY parentHandle, const QString &rSubKey, QVariant *value) const;
-    QString fileName() const;
-
-private:
-    RegistryKeyList regList; // list of registry locations to search for keys
-    bool deleteWriteHandleOnExit;
-};
-
-QWinSettingsPrivate::QWinSettingsPrivate(QSettings::Scope scope, const QString &organization,
-                                         const QString &application)
-    : QSettingsPrivate(QSettings::NativeFormat, scope, organization, application)
-{
-    deleteWriteHandleOnExit = false;
-
-    if (!organization.isEmpty()) {
-        QString prefix = QLatin1String("Software\\") + organization;
-        QString orgPrefix = prefix + QLatin1String("\\OrganizationDefaults");
-        QString appPrefix = prefix + QLatin1Char('\\') + application;
-
-        if (scope == QSettings::UserScope) {
-            if (!application.isEmpty())
-                regList.append(RegistryKey(HKEY_CURRENT_USER, appPrefix, !regList.isEmpty()));
-
-            regList.append(RegistryKey(HKEY_CURRENT_USER, orgPrefix, !regList.isEmpty()));
-        }
-
-        if (!application.isEmpty())
-            regList.append(RegistryKey(HKEY_LOCAL_MACHINE, appPrefix, !regList.isEmpty()));
-
-        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, orgPrefix, !regList.isEmpty()));
-    }
-
-    if (regList.isEmpty())
-        setStatus(QSettings::AccessError);
-}
-
-QWinSettingsPrivate::QWinSettingsPrivate(QString rPath)
-    : QSettingsPrivate(QSettings::NativeFormat)
-{
-    deleteWriteHandleOnExit = false;
-
-    if (rPath.startsWith(QLatin1String("\\")))
-        rPath = rPath.mid(1);
-
-    if (rPath.startsWith(QLatin1String("HKEY_CURRENT_USER\\")))
-        regList.append(RegistryKey(HKEY_CURRENT_USER, rPath.mid(18), false));
-    else if (rPath == QLatin1String("HKEY_CURRENT_USER"))
-        regList.append(RegistryKey(HKEY_CURRENT_USER, QString(), false));
-    else if (rPath.startsWith(QLatin1String("HKEY_LOCAL_MACHINE\\")))
-        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, rPath.mid(19), false));
-    else if (rPath == QLatin1String("HKEY_LOCAL_MACHINE"))
-        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, QString(), false));
-    else if (rPath.startsWith(QLatin1String("HKEY_CLASSES_ROOT\\")))
-        regList.append(RegistryKey(HKEY_CLASSES_ROOT, rPath.mid(18), false));
-    else if (rPath == QLatin1String("HKEY_CLASSES_ROOT"))
-        regList.append(RegistryKey(HKEY_CLASSES_ROOT, QString(), false));
-    else if (rPath.startsWith(QLatin1String("HKEY_USERS\\")))
-        regList.append(RegistryKey(HKEY_USERS, rPath.mid(11), false));
-    else if (rPath == QLatin1String(QLatin1String("HKEY_USERS")))
-        regList.append(RegistryKey(HKEY_USERS, QString(), false));
-    else
-        regList.append(RegistryKey(HKEY_LOCAL_MACHINE, rPath, false));
-}
-
-bool QWinSettingsPrivate::readKey(HKEY parentHandle, const QString &rSubKey, QVariant *value) const
-{
-    QString rSubkeyName = keyName(rSubKey);
-    QString rSubkeyPath = keyPath(rSubKey);
-
-    // open a handle on the subkey
-    HKEY handle = openKey(parentHandle, KEY_READ, rSubkeyPath);
-    if (handle == 0)
-        return false;
-
-    // get the size and type of the value
-    DWORD dataType;
-    DWORD dataSize;
-    LONG res = RegQueryValueEx(handle, reinterpret_cast<const wchar_t *>(rSubkeyName.utf16()), 0, &dataType, 0, &dataSize);
-    if (res != ERROR_SUCCESS) {
-        RegCloseKey(handle);
-        return false;
-    }
-
-    // get the value
-    QByteArray data(dataSize, 0);
-    res = RegQueryValueEx(handle, reinterpret_cast<const wchar_t *>(rSubkeyName.utf16()), 0, 0,
-                           reinterpret_cast<unsigned char*>(data.data()), &dataSize);
-    if (res != ERROR_SUCCESS) {
-        RegCloseKey(handle);
-        return false;
-    }
-
-    switch (dataType) {
-        case REG_EXPAND_SZ:
-        case REG_SZ: {
-            QString s;
-            if (dataSize) {
-                s = QString::fromWCharArray(((const wchar_t *)data.constData()));
-            }
-            if (value != 0)
-                *value = stringToVariant(s);
-            break;
-        }
-
-        case REG_MULTI_SZ: {
-            QStringList l;
-            if (dataSize) {
-                int i = 0;
-                for (;;) {
-                    QString s = QString::fromWCharArray((const wchar_t *)data.constData() + i);
-                    i += s.length() + 1;
-
-                    if (s.isEmpty())
-                        break;
-                    l.append(s);
-                }
-            }
-            if (value != 0)
-                *value = stringListToVariantList(l);
-            break;
-        }
-
-        case REG_NONE:
-        case REG_BINARY: {
-            QString s;
-            if (dataSize) {
-                s = QString::fromWCharArray((const wchar_t *)data.constData(), data.size() / 2);
-            }
-            if (value != 0)
-                *value = stringToVariant(s);
-            break;
-        }
-
-        case REG_DWORD_BIG_ENDIAN:
-        case REG_DWORD: {
-            Q_ASSERT(data.size() == sizeof(int));
-            int i;
-            memcpy((char*)&i, data.constData(), sizeof(int));
-            if (value != 0)
-                *value = i;
-            break;
-        }
-
-        case REG_QWORD: {
-            Q_ASSERT(data.size() == sizeof(qint64));
-            qint64 i;
-            memcpy((char*)&i, data.constData(), sizeof(qint64));
-            if (value != 0)
-                *value = i;
-            break;
-        }
-
-        default:
-            qWarning("QSettings: Unknown data %d type in Windows registry", static_cast<int>(dataType));
-            if (value != 0)
-                *value = QVariant();
-            break;
-    }
-
-    RegCloseKey(handle);
-    return true;
-}
-
-HKEY QWinSettingsPrivate::writeHandle() const
-{
-    if (regList.isEmpty())
-        return 0;
-    const RegistryKey &key = regList.at(0);
-    if (key.handle() == 0 || key.readOnly())
-        return 0;
-    return key.handle();
-}
-
-QWinSettingsPrivate::~QWinSettingsPrivate()
-{
-    if (deleteWriteHandleOnExit && writeHandle() != 0) {
-#if defined(Q_OS_WINCE)
-        remove(regList.at(0).key()); 
-#else
-        QString emptyKey;
-        DWORD res = RegDeleteKey(writeHandle(), reinterpret_cast<const wchar_t *>(emptyKey.utf16()));
-        if (res != ERROR_SUCCESS) {
-            qWarning("QSettings: Failed to delete key \"%s\": %s",
-                    regList.at(0).key().toLatin1().data(), errorCodeToString(res).toLatin1().data());
-        }
-#endif
-    }
-
-    for (int i = 0; i < regList.size(); ++i)
-        regList[i].close();
-}
-
-void QWinSettingsPrivate::remove(const QString &uKey)
-{
-    if (writeHandle() == 0) {
-        setStatus(QSettings::AccessError);
-        return;
-    }
-
-    QString rKey = escapedKey(uKey);
-
-    // try to delete value bar in key foo
-    LONG res;
-    HKEY handle = openKey(writeHandle(), registryPermissions, keyPath(rKey));
-    if (handle != 0) {
-        res = RegDeleteValue(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()));
-        RegCloseKey(handle);
-    }
-
-    // try to delete key foo/bar and all subkeys
-    handle = openKey(writeHandle(), registryPermissions, rKey);
-    if (handle != 0) {
-        deleteChildGroups(handle);
-
-        if (rKey.isEmpty()) {
-            QStringList childKeys = childKeysOrGroups(handle, QSettingsPrivate::ChildKeys);
-
-            for (int i = 0; i < childKeys.size(); ++i) {
-                QString group = childKeys.at(i);
-
-                LONG res = RegDeleteValue(handle, reinterpret_cast<const wchar_t *>(group.utf16()));
-                if (res != ERROR_SUCCESS) {
-                    qWarning("QSettings: RegDeleteValue failed on subkey \"%s\": %s",
-                              group.toLatin1().data(), errorCodeToString(res).toLatin1().data());
-                }
-            }
-        } else {
-#if defined(Q_OS_WINCE)
-            // For WinCE always Close the handle first.
-            RegCloseKey(handle);
-#endif
-            res = RegDeleteKey(writeHandle(), reinterpret_cast<const wchar_t *>(rKey.utf16()));
-
-            if (res != ERROR_SUCCESS) {
-                qWarning("QSettings: RegDeleteKey failed on key \"%s\": %s",
-                            rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
-            }
-        }
-        RegCloseKey(handle);
-    }
-}
-
-static bool stringContainsNullChar(const QString &s)
-{
-    for (int i = 0; i < s.length(); ++i) {
-        if (s.at(i).unicode() == 0)
-            return true;
-    }
-    return false;
-}
-
-void QWinSettingsPrivate::set(const QString &uKey, const QVariant &value)
-{
-    if (writeHandle() == 0) {
-        setStatus(QSettings::AccessError);
-        return;
-    }
-
-    QString rKey = escapedKey(uKey);
-
-    HKEY handle = createOrOpenKey(writeHandle(), registryPermissions, keyPath(rKey));
-    if (handle == 0) {
-        setStatus(QSettings::AccessError);
-        return;
-    }
-
-    DWORD type;
-    QByteArray regValueBuff;
-
-    // Determine the type
-    switch (value.type()) {
-        case QVariant::List:
-        case QVariant::StringList: {
-            // If none of the elements contains '\0', we can use REG_MULTI_SZ, the
-            // native registry string list type. Otherwise we use REG_BINARY.
-            type = REG_MULTI_SZ;
-            QStringList l = variantListToStringList(value.toList());
-            QStringList::const_iterator it = l.constBegin();
-            for (; it != l.constEnd(); ++it) {
-                if ((*it).length() == 0 || stringContainsNullChar(*it)) {
-                    type = REG_BINARY;
-                    break;
-                }
-            }
-
-            if (type == REG_BINARY) {
-                QString s = variantToString(value);
-                regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
-            } else {
-                QStringList::const_iterator it = l.constBegin();
-                for (; it != l.constEnd(); ++it) {
-                    const QString &s = *it;
-                    regValueBuff += QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
-                }
-                regValueBuff.append((char)0);
-                regValueBuff.append((char)0);
-            }
-            break;
-        }
-
-        case QVariant::Int:
-        case QVariant::UInt: {
-            type = REG_DWORD;
-            qint32 i = value.toInt();
-            regValueBuff = QByteArray((const char*)&i, sizeof(qint32));
-            break;
-        }
-
-        case QVariant::LongLong:
-        case QVariant::ULongLong: {
-            type = REG_QWORD;
-            qint64 i = value.toLongLong();
-            regValueBuff = QByteArray((const char*)&i, sizeof(qint64));
-            break;
-        }
-
-        case QVariant::ByteArray:
-            // fallthrough intended
-
-        default: {
-            // If the string does not contain '\0', we can use REG_SZ, the native registry
-            // string type. Otherwise we use REG_BINARY.
-            QString s = variantToString(value);
-            type = stringContainsNullChar(s) ? REG_BINARY : REG_SZ;
-            if (type == REG_BINARY) {
-                regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
-            } else {
-                regValueBuff = QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
-            }
-            break;
-        }
-    }
-
-    // set the value
-    LONG res = RegSetValueEx(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()), 0, type,
-                             reinterpret_cast<const unsigned char*>(regValueBuff.constData()),
-                             regValueBuff.size());
-
-    if (res == ERROR_SUCCESS) {
-        deleteWriteHandleOnExit = false;
-    } else {
-        qWarning("QSettings: failed to set subkey \"%s\": %s",
-                rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
-        setStatus(QSettings::AccessError);
-    }
-
-    RegCloseKey(handle);
-}
-
-bool QWinSettingsPrivate::get(const QString &uKey, QVariant *value) const
-{
-    QString rKey = escapedKey(uKey);
-
-    for (int i = 0; i < regList.size(); ++i) {
-        HKEY handle = regList.at(i).handle();
-        if (handle != 0 && readKey(handle, rKey, value))
-            return true;
-
-        if (!fallbacks)
-            return false;
-    }
-
-    return false;
-}
-
-QStringList QWinSettingsPrivate::children(const QString &uKey, ChildSpec spec) const
-{
-    NameSet result;
-    QString rKey = escapedKey(uKey);
-
-    for (int i = 0; i < regList.size(); ++i) {
-        HKEY parent_handle = regList.at(i).handle();
-        if (parent_handle == 0)
-            continue;
-        HKEY handle = openKey(parent_handle, KEY_READ, rKey);
-        if (handle == 0)
-            continue;
-
-        if (spec == AllKeys) {
-            NameSet keys;
-            allKeys(handle, QLatin1String(""), &keys);
-            mergeKeySets(&result, keys);
-        } else { // ChildGroups or ChildKeys
-            QStringList names = childKeysOrGroups(handle, spec);
-            mergeKeySets(&result, names);
-        }
-
-        RegCloseKey(handle);
-
-        if (!fallbacks)
-            return result.keys();
-    }
-
-    return result.keys();
-}
-
-void QWinSettingsPrivate::clear()
-{
-    remove(QString());
-    deleteWriteHandleOnExit = true;
-}
-
-void QWinSettingsPrivate::sync()
-{
-    RegFlushKey(writeHandle());
-}
-
-void QWinSettingsPrivate::flush()
-{
-    // Windows does this for us.
-}
-
-QString QWinSettingsPrivate::fileName() const
-{
-    if (regList.isEmpty())
-        return QString();
-
-    const RegistryKey &key = regList.at(0);
-    QString result;
-    if (key.parentHandle() == HKEY_CURRENT_USER)
-        result = QLatin1String("\\HKEY_CURRENT_USER\\");
-    else
-        result = QLatin1String("\\HKEY_LOCAL_MACHINE\\");
-
-    return result + regList.at(0).key();
-}
-
-bool QWinSettingsPrivate::isWritable() const
-{
-    return writeHandle() != 0;
-}
-
-QSettingsPrivate *QSettingsPrivate::create(QSettings::Format format, QSettings::Scope scope,
-                                           const QString &organization, const QString &application)
-{
-    if (format == QSettings::NativeFormat) {
-        return new QWinSettingsPrivate(scope, organization, application);
-    } else {
-        return new QConfFileSettingsPrivate(format, scope, organization, application);
-    }
-}
-
-QSettingsPrivate *QSettingsPrivate::create(const QString &fileName, QSettings::Format format)
-{
-    if (format == QSettings::NativeFormat) {
-        return new QWinSettingsPrivate(fileName);
-    } else {
-        return new QConfFileSettingsPrivate(fileName, format);
-    }
-}
-
-QT_END_NAMESPACE
-#endif // QT_NO_SETTINGS
diff --git a/src/core/io/qstandardpaths_mac.cpp b/src/core/io/qstandardpaths_mac.cpp
deleted file mode 100644 (file)
index 72446d8..0000000
+++ /dev/null
@@ -1,203 +0,0 @@
-/***********************************************************************
-*
-* Copyright (c) 2015 Ivailo Monev
-* Copyright (c) 2012-2015 Barbara Geller
-* Copyright (c) 2012-2015 Ansel Sermersheim
-* Copyright (c) 2012-2014 Digia Plc and/or its subsidiary(-ies).
-* Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-*
-* This file is part of CopperSpice.
-*
-* CopperSpice is free software: you can redistribute it and/or 
-* modify it under the terms of the GNU Lesser General Public License
-* version 2.1 as published by the Free Software Foundation.
-*
-* CopperSpice is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with CopperSpice.  If not, see 
-* <http://www.gnu.org/licenses/>.
-*
-***********************************************************************/
-
-#include <qstandardpaths.h>
-#include <qdir.h>
-#include <qcore_mac_p.h>
-#include <qcoreapplication.h>
-
-#include <CoreFoundation/CoreFoundation.h>
-#include <ApplicationServices/ApplicationServices.h>
-
-QT_BEGIN_NAMESPACE
-
-/*
-    Translates a QStandardPaths::StandardLocation into the mac equivalent.
-*/
-OSType translateLocation(QStandardPaths::StandardLocation type)
-{
-   switch (type) {
-      case QStandardPaths::ConfigLocation:
-      case QStandardPaths::GenericConfigLocation:
-         return kPreferencesFolderType;
-      case QStandardPaths::DesktopLocation:
-         return kDesktopFolderType;
-      case QStandardPaths::DownloadLocation: // needs NSSearchPathForDirectoriesInDomains with NSDownloadsDirectory
-      // which needs an objective-C *.mm file...
-      case QStandardPaths::DocumentsLocation:
-         return kDocumentsFolderType;
-      case QStandardPaths::FontsLocation:
-         // There are at least two different font directories on the mac: /Library/Fonts and ~/Library/Fonts.
-         // To select a specific one we have to specify a different first parameter when calling FSFindFolder.
-         return kFontsFolderType;
-      case QStandardPaths::ApplicationsLocation:
-         return kApplicationsFolderType;
-      case QStandardPaths::MusicLocation:
-         return kMusicDocumentsFolderType;
-      case QStandardPaths::MoviesLocation:
-         return kMovieDocumentsFolderType;
-      case QStandardPaths::PicturesLocation:
-         return kPictureDocumentsFolderType;
-      case QStandardPaths::TempLocation:
-         return kTemporaryFolderType;
-      case QStandardPaths::GenericDataLocation:
-      case QStandardPaths::RuntimeLocation:
-      case QStandardPaths::DataLocation:
-         return kApplicationSupportFolderType;
-      case QStandardPaths::GenericCacheLocation:
-      case QStandardPaths::CacheLocation:
-         return kCachedDataFolderType;
-      default:
-         return kDesktopFolderType;
-   }
-}
-
-/*
-    Constructs a full unicode path from a FSRef.
-*/
-static QString getFullPath(const FSRef &ref)
-{
-   QByteArray ba(2048, 0);
-   if (FSRefMakePath(&ref, reinterpret_cast<UInt8 *>(ba.data()), ba.size()) == noErr) {
-      return QString::fromUtf8(ba.constData()).normalized(QString::NormalizationForm_C);
-   }
-   return QString();
-}
-
-static void appendOrganizationAndApp(QString &path)
-{
-   const QString org = QCoreApplication::organizationName();
-
-   if (!org.isEmpty()) {
-      path += QLatin1Char('/') + org;
-   }
-
-   const QString appName = QCoreApplication::applicationName();
-
-   if (!appName.isEmpty()) {
-      path += QLatin1Char('/') + appName;
-   }
-}
-
-static QString macLocation(QStandardPaths::StandardLocation type, short domain)
-{
-   // http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/Reference/reference.html
-   FSRef ref;
-   OSErr err = FSFindFolder(domain, translateLocation(type), false, &ref);
-   if (err) {
-      return QString();
-   }
-
-   QString path = getFullPath(ref);
-
-   if (type == QStandardPaths::DataLocation || type == QStandardPaths::CacheLocation) {
-      appendOrganizationAndApp(path);
-   }
-   return path;
-}
-
-QString QStandardPaths::writableLocation(StandardLocation type)
-{
-   switch (type) {
-      case HomeLocation:
-         return QDir::homePath();
-      case TempLocation:
-         return QDir::tempPath();
-      case GenericDataLocation:
-      case DataLocation:
-      case GenericCacheLocation:
-      case CacheLocation:
-      case RuntimeLocation:
-         return macLocation(type, kUserDomain);
-      default:
-         return macLocation(type, kOnAppropriateDisk);
-   }
-}
-
-QStringList QStandardPaths::standardLocations(StandardLocation type)
-{
-   QStringList dirs;
-
-   if (type == GenericDataLocation || type == DataLocation || type == GenericCacheLocation || type == CacheLocation) {
-      const QString path = macLocation(type, kOnAppropriateDisk);
-      if (!path.isEmpty()) {
-         dirs.append(path);
-      }
-   }
-
-   if (type == DataLocation) {
-      CFBundleRef mainBundle = CFBundleGetMainBundle();
-      if (mainBundle) {
-         CFURLRef bundleUrl = CFBundleCopyBundleURL(mainBundle);
-         CFStringRef cfBundlePath = CFURLCopyPath(bundleUrl);
-         QString bundlePath = QCFString::toQString(cfBundlePath);
-         CFRelease(cfBundlePath);
-         CFRelease(bundleUrl);
-
-         CFURLRef resourcesUrl = CFBundleCopyResourcesDirectoryURL(mainBundle);
-         CFStringRef cfResourcesPath = CFURLCopyPath(bundleUrl);
-         QString resourcesPath = QCFString::toQString(cfResourcesPath);
-         CFRelease(cfResourcesPath);
-         CFRelease(resourcesUrl);
-
-         // Handle bundled vs unbundled executables. CFBundleGetMainBundle() returns
-         // a valid bundle in both cases. CFBundleCopyResourcesDirectoryURL() returns
-         // an absolute path for unbundled executables.
-         if (resourcesPath.startsWith(QLatin1Char('/'))) {
-            dirs.append(resourcesPath);
-         } else {
-            dirs.append(bundlePath + resourcesPath);
-         }
-      }
-   }
-   const QString localDir = writableLocation(type);
-   dirs.prepend(localDir);
-   return dirs;
-}
-
-QString QStandardPaths::displayName(StandardLocation type)
-{
-   if (QStandardPaths::HomeLocation == type) {
-      return QCoreApplication::translate("QStandardPaths", "Home");
-   }
-
-   FSRef ref;
-   OSErr err = FSFindFolder(kOnAppropriateDisk, translateLocation(type), false, &ref);
-   if (err) {
-      return QString();
-   }
-
-   QCFString displayName;
-   err = LSCopyDisplayNameForRef(&ref, &displayName);
-   if (err) {
-      return QString();
-   }
-
-   return static_cast<QString>(displayName);
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/core/io/qstandardpaths_win.cpp b/src/core/io/qstandardpaths_win.cpp
deleted file mode 100644 (file)
index 7e1a978..0000000
+++ /dev/null
@@ -1,205 +0,0 @@
-/***********************************************************************
-*
-* Copyright (c) 2015 Ivailo Monev
-* Copyright (c) 2012-2015 Barbara Geller
-* Copyright (c) 2012-2015 Ansel Sermersheim
-* Copyright (c) 2012-2014 Digia Plc and/or its subsidiary(-ies).
-* Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies).
-* All rights reserved.
-*
-* This file is part of CopperSpice.
-*
-* CopperSpice is free software: you can redistribute it and/or 
-* modify it under the terms of the GNU Lesser General Public License
-* version 2.1 as published by the Free Software Foundation.
-*
-* CopperSpice is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with CopperSpice.  If not, see 
-* <http://www.gnu.org/licenses/>.
-*
-***********************************************************************/
-
-#include <qstandardpaths.h>
-
-#include <qdir.h>
-#include <qsystemlibrary_p.h>
-#include <qstringlist.h>
-#include <qcoreapplication.h>
-#include <qt_windows.h>
-#include <shlobj.h>
-#include <intshcut.h>
-
-#ifndef CSIDL_MYMUSIC
-#define CSIDL_MYMUSIC 13
-#define CSIDL_MYVIDEO 14
-#endif
-
-#ifndef QT_NO_STANDARDPATHS
-
-QT_BEGIN_NAMESPACE
-
-typedef BOOL (WINAPI *GetSpecialFolderPath)(HWND, LPWSTR, int, BOOL);
-static GetSpecialFolderPath resolveGetSpecialFolderPath()
-{
-   static GetSpecialFolderPath gsfp = 0;
-   if (!gsfp) {
-      QSystemLibrary library(QLatin1String("shell32"));
-      gsfp = (GetSpecialFolderPath)library.resolve("SHGetSpecialFolderPathW");
-   }
-   return gsfp;
-}
-
-static QString convertCharArray(const wchar_t *path)
-{
-   return QDir::fromNativeSeparators(QString::fromWCharArray(path));
-}
-
-QString QStandardPaths::writableLocation(StandardLocation type)
-{
-   QString result;
-
-   static GetSpecialFolderPath SHGetSpecialFolderPath = resolveGetSpecialFolderPath();
-   if (!SHGetSpecialFolderPath) {
-      return QString();
-   }
-
-   wchar_t path[MAX_PATH];
-
-   switch (type) {
-      case ConfigLocation: // same as DataLocation, on Windows (oversight, but too late to fix it)
-      case GenericConfigLocation: // same as GenericDataLocation, on Windows
-      case DataLocation:
-      case GenericDataLocation:
-
-         if (SHGetSpecialFolderPath(0, path, CSIDL_LOCAL_APPDATA, FALSE)) {
-            result = convertCharArray(path);
-         }
-
-         if (type != GenericDataLocation && type != GenericConfigLocation) {
-            if (!QCoreApplication::organizationName().isEmpty()) {
-               result += QLatin1Char('/') + QCoreApplication::organizationName();
-            }
-            if (!QCoreApplication::applicationName().isEmpty()) {
-               result += QLatin1Char('/') + QCoreApplication::applicationName();
-            }
-         }
-
-         break;
-
-      case DesktopLocation:
-         if (SHGetSpecialFolderPath(0, path, CSIDL_DESKTOPDIRECTORY, FALSE)) {
-            result = convertCharArray(path);
-         }
-         break;
-
-      case DownloadLocation: // TODO implement with SHGetKnownFolderPath(FOLDERID_Downloads) (starting from Vista)
-      case DocumentsLocation:
-         if (SHGetSpecialFolderPath(0, path, CSIDL_PERSONAL, FALSE)) {
-            result = convertCharArray(path);
-         }
-         break;
-
-      case FontsLocation:
-         if (SHGetSpecialFolderPath(0, path, CSIDL_FONTS, FALSE)) {
-            result = convertCharArray(path);
-         }
-         break;
-
-      case ApplicationsLocation:
-         if (SHGetSpecialFolderPath(0, path, CSIDL_PROGRAMS, FALSE)) {
-            result = convertCharArray(path);
-         }
-         break;
-
-      case MusicLocation:
-         if (SHGetSpecialFolderPath(0, path, CSIDL_MYMUSIC, FALSE)) {
-            result = convertCharArray(path);
-         }
-         break;
-
-      case MoviesLocation:
-         if (SHGetSpecialFolderPath(0, path, CSIDL_MYVIDEO, FALSE)) {
-            result = convertCharArray(path);
-         }
-         break;
-
-      case PicturesLocation:
-         if (SHGetSpecialFolderPath(0, path, CSIDL_MYPICTURES, FALSE)) {
-            result = convertCharArray(path);
-         }
-         break;
-
-      case CacheLocation:
-         // Although Microsoft has a Cache key it is a pointer to IE's cache, not a cache
-         // location for everyone.  Most applications seem to be using a
-         // cache directory located in their AppData directory
-         return writableLocation(DataLocation) + QLatin1String("/cache");
-
-      case GenericCacheLocation:
-         return writableLocation(GenericDataLocation) + QLatin1String("/cache");
-
-      case RuntimeLocation:
-      case HomeLocation:
-         result = QDir::homePath();
-         break;
-
-      case TempLocation:
-         result = QDir::tempPath();
-         break;
-   }
-   return result;
-}
-
-QStringList QStandardPaths::standardLocations(StandardLocation type)
-{
-   QStringList dirs;
-
-   // type-specific handling goes here
-   static GetSpecialFolderPath SHGetSpecialFolderPath = resolveGetSpecialFolderPath();
-
-   if (SHGetSpecialFolderPath) {
-      wchar_t path[MAX_PATH];
-      switch (type) {
-         case ConfigLocation: // same as DataLocation, on Windows (oversight, but too late to fix it)
-         case GenericConfigLocation: // same as GenericDataLocation, on Windows
-         case DataLocation:
-         case GenericDataLocation:
-            if (SHGetSpecialFolderPath(0, path, CSIDL_COMMON_APPDATA, FALSE)) {
-               QString result = convertCharArray(path);
-               if (type != GenericDataLocation && type != GenericConfigLocation) {
-
-                  if (!QCoreApplication::organizationName().isEmpty()) {
-                     result += QLatin1Char('/') + QCoreApplication::organizationName();
-                  }
-                  if (!QCoreApplication::applicationName().isEmpty()) {
-                     result += QLatin1Char('/') + QCoreApplication::applicationName();
-                  }
-
-               }
-               dirs.append(result);
-
-               if (type != GenericDataLocation) {
-                  dirs.append(QCoreApplication::applicationDirPath());
-                  dirs.append(QCoreApplication::applicationDirPath() + QLatin1String("/data"));
-               }
-            }
-
-            break;
-         default:
-            break;
-      }
-   }
-
-   const QString localDir = writableLocation(type);
-   dirs.prepend(localDir);
-   return dirs;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STANDARDPATHS
diff --git a/src/core/kernel/qcore_mac.cpp b/src/core/kernel/qcore_mac.cpp
deleted file mode 100644 (file)
index e80568b..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qcore_mac_p.h>
-#include <new>
-
-QT_BEGIN_NAMESPACE
-
-QString QCFString::toQString(CFStringRef str)
-{
-    if (!str)
-        return QString();
-
-    CFIndex length = CFStringGetLength(str);
-    if (length == 0)
-        return QString();
-
-    QString string(length, Qt::Uninitialized);
-    CFStringGetCharacters(str, CFRangeMake(0, length), reinterpret_cast<UniChar *>(const_cast<QChar *>(string.unicode())));
-
-    return string;
-}
-
-QCFString::operator QString() const
-{
-    if (string.isEmpty() && type)
-        const_cast<QCFString*>(this)->string = toQString(type);
-    return string;
-}
-
-CFStringRef QCFString::toCFStringRef(const QString &string)
-{
-    return CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar *>(string.unicode()),
-                                        string.length());
-}
-
-QCFString::operator CFStringRef() const
-{
-    if (!type) {
-        if (string.d->data != string.d->array)
-            const_cast<QCFString*>(this)->string.reallocData(); // ### Qt5: do we really need this stupid user protection?
-        const_cast<QCFString*>(this)->type =
-            CFStringCreateWithCharactersNoCopy(0,
-                                               reinterpret_cast<const UniChar *>(string.unicode()),
-                                               string.length(),
-                                               kCFAllocatorNull);
-    }
-    return type;
-}
-
-
-#if !defined(Q_OS_IOS)
-void qt_mac_to_pascal_string(const QString &s, Str255 str, TextEncoding encoding, int len)
-{
-    if(len == -1)
-        len = s.length();
-#if 0
-    UnicodeMapping mapping;
-    mapping.unicodeEncoding = CreateTextEncoding(kTextEncodingUnicodeDefault,
-                                                 kTextEncodingDefaultVariant,
-                                                 kUnicode16BitFormat);
-    mapping.otherEncoding = (encoding ? encoding : );
-    mapping.mappingVersion = kUnicodeUseLatestMapping;
-
-    UnicodeToTextInfo info;
-    OSStatus err = CreateUnicodeToTextInfo(&mapping, &info);
-    if(err != noErr) {
-        qDebug("Qt: internal: Unable to create pascal string '%s'::%d [%ld]",
-               s.left(len).latin1(), (int)encoding, err);
-        return;
-    }
-    const int unilen = len * 2;
-    const UniChar *unibuf = (UniChar *)s.unicode();
-    ConvertFromUnicodeToPString(info, unilen, unibuf, str);
-    DisposeUnicodeToTextInfo(&info);
-#else
-    Q_UNUSED(encoding);
-    CFStringGetPascalString(QCFString(s), str, 256, CFStringGetSystemEncoding());
-#endif
-}
-
-QString qt_mac_from_pascal_string(const Str255 pstr)
-{
-    return QCFString(CFStringCreateWithPascalString(0, pstr, CFStringGetSystemEncoding()));
-}
-
-OSErr qt_mac_create_fsref(const QString &file, FSRef *fsref)
-{
-    return FSPathMakeRef(reinterpret_cast<const UInt8 *>(file.toUtf8().constData()), fsref, 0);
-}
-
-// Don't use this function, it won't work in 10.5 (Leopard) and up
-OSErr qt_mac_create_fsspec(const QString &file, FSSpec *spec)
-{
-    FSRef fsref;
-    OSErr ret = qt_mac_create_fsref(file, &fsref);
-    if (ret == noErr)
-        ret = FSGetCatalogInfo(&fsref, kFSCatInfoNone, 0, 0, spec, 0);
-    return ret;
-}
-#endif // !defined(Q_OS_IOS)
-
-QT_END_NAMESPACE
diff --git a/src/core/kernel/qcore_mac_p.h b/src/core/kernel/qcore_mac_p.h
deleted file mode 100644 (file)
index 639d9a6..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QCORE_MAC_P_H
-#define QCORE_MAC_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.
-//
-
-#ifndef __IMAGECAPTURE__
-#  define __IMAGECAPTURE__
-#endif
-
-#undef OLD_DEBUG
-#ifdef DEBUG
-# define OLD_DEBUG DEBUG
-# undef DEBUG
-#endif
-#define DEBUG 0
-#ifdef qDebug
-#  define old_qDebug qDebug
-#  undef qDebug
-#endif
-
-#if defined(QT_BOOTSTRAPPED)
-#include <ApplicationServices/ApplicationServices.h>
-#else
-#include <CoreFoundation/CoreFoundation.h>
-#endif
-
-#if !defined(Q_OS_IOS)
-#include <CoreServices/CoreServices.h>
-#endif
-
-#undef DEBUG
-#ifdef OLD_DEBUG
-#  define DEBUG OLD_DEBUG
-#  undef OLD_DEBUG
-#endif
-
-#ifdef old_qDebug
-#  undef qDebug
-#  define qDebug QT_NO_QDEBUG_MACRO
-#  undef old_qDebug
-#endif
-
-#include "qstring.h"
-
-QT_BEGIN_NAMESPACE
-
-/*
-    Helper class that automates refernce counting for CFtypes.
-    After constructing the QCFType object, it can be copied like a
-    value-based type.
-
-    Note that you must own the object you are wrapping.
-    This is typically the case if you get the object from a Core
-    Foundation function with the word "Create" or "Copy" in it. If
-    you got the object from a "Get" function, either retain it or use
-    constructFromGet(). One exception to this rule is the
-    HIThemeGet*Shape functions, which in reality are "Copy" functions.
-*/
-template <typename T>
-class Q_CORE_EXPORT QCFType
-{
-public:
-    inline QCFType(const T &t = 0) : type(t) {}
-    inline QCFType(const QCFType &helper) : type(helper.type) { if (type) CFRetain(type); }
-    inline ~QCFType() { if (type) CFRelease(type); }
-    inline operator T() { return type; }
-    inline QCFType operator =(const QCFType &helper)
-    {
-       if (helper.type)
-           CFRetain(helper.type);
-       CFTypeRef type2 = type;
-       type = helper.type;
-       if (type2)
-           CFRelease(type2);
-       return *this;
-    }
-    inline T *operator&() { return &type; }
-    template <typename X> X as() const { return reinterpret_cast<X>(type); }
-    static QCFType constructFromGet(const T &t)
-    {
-        CFRetain(t);
-        return QCFType<T>(t);
-    }
-protected:
-    T type;
-};
-
-class Q_CORE_EXPORT QCFString : public QCFType<CFStringRef>
-{
-public:
-    inline QCFString(const QString &str) : QCFType<CFStringRef>(0), string(str) {}
-    inline QCFString(const CFStringRef cfstr = 0) : QCFType<CFStringRef>(cfstr) {}
-    inline QCFString(const QCFType<CFStringRef> &other) : QCFType<CFStringRef>(other) {}
-    operator QString() const;
-    operator CFStringRef() const;
-    static QString toQString(CFStringRef cfstr);
-    static CFStringRef toCFStringRef(const QString &str);
-private:
-    QString string;
-};
-
-
-#if !defined(Q_OS_IOS)
-Q_CORE_EXPORT void qt_mac_to_pascal_string(const QString &s, Str255 str, TextEncoding encoding = 0, int len = -1);
-Q_CORE_EXPORT QString qt_mac_from_pascal_string(const Str255 pstr);
-
-Q_CORE_EXPORT OSErr qt_mac_create_fsref(const QString &file, FSRef *fsref);
-// Don't use this function, it won't work in 10.5 (Leopard) and up
-Q_CORE_EXPORT OSErr qt_mac_create_fsspec(const QString &file, FSSpec *spec);
-#endif // !defined(Q_OS_IOS)
-
-QT_END_NAMESPACE
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
-#ifndef __LP64__
-       typedef float CGFloat;
-        typedef int NSInteger;
-        typedef unsigned int NSUInteger;
-       #define SRefCon SInt32
-       #define URefCon UInt32
-#endif
-#endif
-
-#endif // QCORE_MAC_P_H
diff --git a/src/core/kernel/qcoreapplication_mac.cpp b/src/core/kernel/qcoreapplication_mac.cpp
deleted file mode 100644 (file)
index 1333580..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qcoreapplication.h"
-#include "qcoreapplication_p.h"
-#include <qcore_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
-  QCoreApplication utility functions
- *****************************************************************************/
-QString qAppFileName()
-{
-    static QString appFileName;
-    if (appFileName.isEmpty()) {
-        QCFType<CFURLRef> bundleURL(CFBundleCopyExecutableURL(CFBundleGetMainBundle()));
-        if(bundleURL) {
-            QCFString cfPath(CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle));
-            if(cfPath)
-                appFileName = cfPath;
-        }
-    }
-    return appFileName;
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/core/kernel/qcoreapplication_win.cpp b/src/core/kernel/qcoreapplication_win.cpp
deleted file mode 100644 (file)
index 95cb3ed..0000000
+++ /dev/null
@@ -1,1065 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qcoreapplication.h"
-#include "qcoreapplication_p.h"
-#include "qstringlist.h"
-#include "qt_windows.h"
-#include "qvector.h"
-#include "qmutex.h"
-#include "qfileinfo.h"
-#include "qcorecmdlineargs_p.h"
-#include <qthread_p.h>
-#include <ctype.h>
-
-QT_BEGIN_NAMESPACE
-
-bool usingWinMain = false;  // whether the qWinMain() is used or not
-int appCmdShow = 0;
-
-Q_CORE_EXPORT HINSTANCE qWinAppInst()                // get Windows app handle
-{
-    return GetModuleHandle(0);
-}
-
-Q_CORE_EXPORT HINSTANCE qWinAppPrevInst()                // get Windows prev app handle
-{
-    return 0;
-}
-
-Q_CORE_EXPORT int qWinAppCmdShow()                        // get main window show command
-{
-#if defined(Q_OS_WINCE)
-    return appCmdShow;
-#else
-    STARTUPINFO startupInfo;
-    GetStartupInfo(&startupInfo);
-
-    return (startupInfo.dwFlags & STARTF_USESHOWWINDOW)
-        ? startupInfo.wShowWindow
-        : SW_SHOWDEFAULT;
-#endif
-}
-
-Q_CORE_EXPORT QString qAppFileName()                // get application file name
-{
-    // We do MAX_PATH + 2 here, and request with MAX_PATH + 1, so we can handle all paths
-    // up to, and including MAX_PATH size perfectly fine with string termination, as well
-    // as easily detect if the file path is indeed larger than MAX_PATH, in which case we
-    // need to use the heap instead. This is a work-around, since contrary to what the
-    // MSDN documentation states, GetModuleFileName sometimes doesn't set the
-    // ERROR_INSUFFICIENT_BUFFER error number, and we thus cannot rely on this value if
-    // GetModuleFileName(0, buffer, MAX_PATH) == MAX_PATH.
-    // GetModuleFileName(0, buffer, MAX_PATH + 1) == MAX_PATH just means we hit the normal
-    // file path limit, and we handle it normally, if the result is MAX_PATH + 1, we use
-    // heap (even if the result _might_ be exactly MAX_PATH + 1, but that's ok).
-    wchar_t buffer[MAX_PATH + 2];
-    DWORD v = GetModuleFileName(0, buffer, MAX_PATH + 1);
-    buffer[MAX_PATH + 1] = 0;
-
-    if (v == 0)
-        return QString();
-    else if (v <= MAX_PATH)
-        return QString::fromWCharArray(buffer);
-
-    // MAX_PATH sized buffer wasn't large enough to contain the full path, use heap
-    wchar_t *b = 0;
-    int i = 1;
-    size_t size;
-    do {
-        ++i;
-        size = MAX_PATH * i;
-        b = reinterpret_cast<wchar_t *>(realloc(b, (size + 1) * sizeof(wchar_t)));
-        if (b)
-            v = GetModuleFileName(NULL, b, size);
-    } while (b && v == size);
-
-    if (b)
-        *(b + size) = 0;
-    QString res = QString::fromWCharArray(b);
-    free(b);
-
-    return res;
-}
-
-QString QCoreApplicationPrivate::appName() const
-{
-    return QFileInfo(qAppFileName()).baseName();
-}
-
-class QWinMsgHandlerCriticalSection
-{
-    CRITICAL_SECTION cs;
-public:
-    QWinMsgHandlerCriticalSection()
-    { InitializeCriticalSection(&cs); }
-    ~QWinMsgHandlerCriticalSection()
-    { DeleteCriticalSection(&cs); }
-
-    void lock()
-    { EnterCriticalSection(&cs); }
-    void unlock()
-    { LeaveCriticalSection(&cs); }
-};
-
-Q_CORE_EXPORT void qWinMsgHandler(QtMsgType t, const char* str)
-{
-    Q_UNUSED(t);
-    // OutputDebugString is not threadsafe.
-
-    // cannot use QMutex here, because qWarning()s in the QMutex
-    // implementation may cause this function to recurse
-    static QWinMsgHandlerCriticalSection staticCriticalSection;
-
-    if (!str)
-        str = "(null)";
-
-    staticCriticalSection.lock();
-
-    QString s(QString::fromLocal8Bit(str));
-    s += QLatin1Char('\n');
-    OutputDebugString((wchar_t*)s.utf16());
-
-    staticCriticalSection.unlock();
-}
-
-
-/*****************************************************************************
-  qWinMain() - Initializes Windows. Called from WinMain() in qtmain_win.cpp
- *****************************************************************************/
-
-#if defined(Q_OS_WINCE)
-Q_CORE_EXPORT void __cdecl qWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdParam,
-               int cmdShow, int &argc, QVector<char *> &argv)
-#else
-Q_CORE_EXPORT
-void qWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdParam,
-               int cmdShow, int &argc, QVector<char *> &argv)
-#endif
-{
-    static bool already_called = false;
-
-    if (already_called) {
-        qWarning("Qt: Internal error: qWinMain should be called only once");
-        return;
-    }
-    already_called = true;
-    usingWinMain = true;
-
-    // Install default debug handler
-    qInstallMsgHandler(qWinMsgHandler);
-
-    // Create command line
-    argv = qWinCmdLine<char>(cmdParam, int(strlen(cmdParam)), argc);
-
-    appCmdShow = cmdShow;
-
-    // Ignore Windows parameters
-    Q_UNUSED(instance);
-    Q_UNUSED(prevInstance);
-}
-
-/*!
-    The message procedure calls this function for every message
-    received. Reimplement this function if you want to process window
-    messages \a msg that are not processed by Qt. If you don't want
-    the event to be processed by Qt, then return true and set \a result
-    to the value that the window procedure should return. Otherwise
-    return false.
-
-    It is only directly addressed messages that are filtered. To
-    handle system wide messages, such as messages from a registered
-    hot key, you need to install an event filter on the event
-    dispatcher, which is returned from
-    QAbstractEventDispatcher::instance().
-*/
-bool QCoreApplication::winEventFilter(MSG *msg, long *result)        // Windows event filter
-{
-    Q_UNUSED(msg);
-    Q_UNUSED(result);
-    return false;
-}
-
-void QCoreApplicationPrivate::removePostedTimerEvent(QObject *object, int timerId)
-{
-    QThreadData *data = object->d_func()->threadData;
-
-    QMutexLocker locker(&data->postEventList.mutex);
-    if (data->postEventList.size() == 0)
-        return;
-    for (int i = 0; i < data->postEventList.size(); ++i) {
-        const QPostEvent & pe = data->postEventList.at(i);
-        if (pe.receiver == object
-            && pe.event
-            && (pe.event->type() == QEvent::Timer || pe.event->type() == QEvent::ZeroTimerEvent)
-            && static_cast<QTimerEvent *>(pe.event)->timerId() == timerId) {
-                --pe.receiver->d_func()->postedEvents;
-                pe.event->posted = false;
-                delete pe.event;
-                const_cast<QPostEvent &>(pe).event = 0;
-                return;
-            }
-    }
-}
-
-#if defined(Q_WS_WIN) && !defined(QT_NO_DEBUG_STREAM)
-/*****************************************************************************
-  Convenience functions for convert WM_* messages into human readable strings,
-  including a nifty QDebug operator<< for simpel QDebug() << msg output.
- *****************************************************************************/
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <windowsx.h>
-#include "qdebug.h"
-QT_END_INCLUDE_NAMESPACE
-
-#if !defined(GET_X_LPARAM)
-#  define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
-#  define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
-#endif
-#ifdef _WIN32_WCE
-#  ifndef WM_NCACTIVATE
-#    define WM_NCACTIVATE 0x86
-#  endif
-#endif
-
-// The values below should never change. Note that none of the usual
-// WM_...FIRST & WM_...LAST values are in the list, as they normally have other
-// WM_... representations
-struct KnownWM {
-    uint WM;
-    const char* str;
-} knownWM[] =
-{{ 0x0000, "WM_NULL" },
- { 0x0001, "WM_CREATE" },
- { 0x0002, "WM_DESTROY" },
- { 0x0003, "WM_MOVE" },
- { 0x0005, "WM_SIZE" },
- { 0x0006, "WM_ACTIVATE" },
- { 0x0007, "WM_SETFOCUS" },
- { 0x0008, "WM_KILLFOCUS" },
- { 0x000A, "WM_ENABLE" },
- { 0x000B, "WM_SETREDRAW" },
- { 0x000C, "WM_SETTEXT" },
- { 0x000D, "WM_GETTEXT" },
- { 0x000E, "WM_GETTEXTLENGTH" },
- { 0x000F, "WM_PAINT" },
- { 0x0010, "WM_CLOSE" },
- { 0x0011, "WM_QUERYENDSESSION" },
- { 0x0013, "WM_QUERYOPEN" },
- { 0x0016, "WM_ENDSESSION" },
- { 0x0012, "WM_QUIT" },
- { 0x0014, "WM_ERASEBKGND" },
- { 0x0015, "WM_SYSCOLORCHANGE" },
- { 0x0018, "WM_SHOWWINDOW" },
- { 0x001A, "WM_WININICHANGE" },
- { 0x001B, "WM_DEVMODECHANGE" },
- { 0x001C, "WM_ACTIVATEAPP" },
- { 0x001D, "WM_FONTCHANGE" },
- { 0x001E, "WM_TIMECHANGE" },
- { 0x001F, "WM_CANCELMODE" },
- { 0x0020, "WM_SETCURSOR" },
- { 0x0021, "WM_MOUSEACTIVATE" },
- { 0x0022, "WM_CHILDACTIVATE" },
- { 0x0023, "WM_QUEUESYNC" },
- { 0x0024, "WM_GETMINMAXINFO" },
- { 0x0026, "WM_PAINTICON" },
- { 0x0027, "WM_ICONERASEBKGND" },
- { 0x0028, "WM_NEXTDLGCTL" },
- { 0x002A, "WM_SPOOLERSTATUS" },
- { 0x002B, "WM_DRAWITEM" },
- { 0x002C, "WM_MEASUREITEM" },
- { 0x002D, "WM_DELETEITEM" },
- { 0x002E, "WM_VKEYTOITEM" },
- { 0x002F, "WM_CHARTOITEM" },
- { 0x0030, "WM_SETFONT" },
- { 0x0031, "WM_GETFONT" },
- { 0x0032, "WM_SETHOTKEY" },
- { 0x0033, "WM_GETHOTKEY" },
- { 0x0037, "WM_QUERYDRAGICON" },
- { 0x0039, "WM_COMPAREITEM" },
- { 0x003D, "WM_GETOBJECT" },
- { 0x0041, "WM_COMPACTING" },
- { 0x0044, "WM_COMMNOTIFY" },
- { 0x0046, "WM_WINDOWPOSCHANGING" },
- { 0x0047, "WM_WINDOWPOSCHANGED" },
- { 0x0048, "WM_POWER" },
- { 0x004A, "WM_COPYDATA" },
- { 0x004B, "WM_CANCELJOURNAL" },
- { 0x004E, "WM_NOTIFY" },
- { 0x0050, "WM_INPUTLANGCHANGEREQUEST" },
- { 0x0051, "WM_INPUTLANGCHANGE" },
- { 0x0052, "WM_TCARD" },
- { 0x0053, "WM_HELP" },
- { 0x0054, "WM_USERCHANGED" },
- { 0x0055, "WM_NOTIFYFORMAT" },
- { 0x007B, "WM_CONTEXTMENU" },
- { 0x007C, "WM_STYLECHANGING" },
- { 0x007D, "WM_STYLECHANGED" },
- { 0x007E, "WM_DISPLAYCHANGE" },
- { 0x007F, "WM_GETICON" },
- { 0x0080, "WM_SETICON" },
- { 0x0081, "WM_NCCREATE" },
- { 0x0082, "WM_NCDESTROY" },
- { 0x0083, "WM_NCCALCSIZE" },
- { 0x0084, "WM_NCHITTEST" },
- { 0x0085, "WM_NCPAINT" },
- { 0x0086, "WM_NCACTIVATE" },
- { 0x0087, "WM_GETDLGCODE" },
- { 0x0088, "WM_SYNCPAINT" },
- { 0x00A0, "WM_NCMOUSEMOVE" },
- { 0x00A1, "WM_NCLBUTTONDOWN" },
- { 0x00A2, "WM_NCLBUTTONUP" },
- { 0x00A3, "WM_NCLBUTTONDBLCLK" },
- { 0x00A4, "WM_NCRBUTTONDOWN" },
- { 0x00A5, "WM_NCRBUTTONUP" },
- { 0x00A6, "WM_NCRBUTTONDBLCLK" },
- { 0x00A7, "WM_NCMBUTTONDOWN" },
- { 0x00A8, "WM_NCMBUTTONUP" },
- { 0x00A9, "WM_NCMBUTTONDBLCLK" },
- { 0x00AB, "WM_NCXBUTTONDOWN" },
- { 0x00AC, "WM_NCXBUTTONUP" },
- { 0x00AD, "WM_NCXBUTTONDBLCLK" },
- { 0x00FF, "WM_INPUT" },
- { 0x0100, "WM_KEYDOWN" },
- { 0x0101, "WM_KEYUP" },
- { 0x0102, "WM_CHAR" },
- { 0x0103, "WM_DEADCHAR" },
- { 0x0104, "WM_SYSKEYDOWN" },
- { 0x0105, "WM_SYSKEYUP" },
- { 0x0106, "WM_SYSCHAR" },
- { 0x0107, "WM_SYSDEADCHAR" },
- { 0x0109, "WM_UNICHAR" },
- { 0x010D, "WM_IME_STARTCOMPOSITION" },
- { 0x010E, "WM_IME_ENDCOMPOSITION" },
- { 0x010F, "WM_IME_COMPOSITION" },
- { 0x0110, "WM_INITDIALOG" },
- { 0x0111, "WM_COMMAND" },
- { 0x0112, "WM_SYSCOMMAND" },
- { 0x0113, "WM_TIMER" },
- { 0x0114, "WM_HSCROLL" },
- { 0x0115, "WM_VSCROLL" },
- { 0x0116, "WM_INITMENU" },
- { 0x0117, "WM_INITMENUPOPUP" },
- { 0x011F, "WM_MENUSELECT" },
- { 0x0120, "WM_MENUCHAR" },
- { 0x0121, "WM_ENTERIDLE" },
- { 0x0122, "WM_MENURBUTTONUP" },
- { 0x0123, "WM_MENUDRAG" },
- { 0x0124, "WM_MENUGETOBJECT" },
- { 0x0125, "WM_UNINITMENUPOPUP" },
- { 0x0126, "WM_MENUCOMMAND" },
- { 0x0127, "WM_CHANGEUISTATE" },
- { 0x0128, "WM_UPDATEUISTATE" },
- { 0x0129, "WM_QUERYUISTATE" },
- { 0x0132, "WM_CTLCOLORMSGBOX" },
- { 0x0133, "WM_CTLCOLOREDIT" },
- { 0x0134, "WM_CTLCOLORLISTBOX" },
- { 0x0135, "WM_CTLCOLORBTN" },
- { 0x0136, "WM_CTLCOLORDLG" },
- { 0x0137, "WM_CTLCOLORSCROLLBAR" },
- { 0x0138, "WM_CTLCOLORSTATIC" },
- { 0x0200, "WM_MOUSEMOVE" },
- { 0x0201, "WM_LBUTTONDOWN" },
- { 0x0202, "WM_LBUTTONUP" },
- { 0x0203, "WM_LBUTTONDBLCLK" },
- { 0x0204, "WM_RBUTTONDOWN" },
- { 0x0205, "WM_RBUTTONUP" },
- { 0x0206, "WM_RBUTTONDBLCLK" },
- { 0x0207, "WM_MBUTTONDOWN" },
- { 0x0208, "WM_MBUTTONUP" },
- { 0x0209, "WM_MBUTTONDBLCLK" },
- { 0x020A, "WM_MOUSEWHEEL" },
- { 0x020B, "WM_XBUTTONDOWN" },
- { 0x020C, "WM_XBUTTONUP" },
- { 0x020D, "WM_XBUTTONDBLCLK" },
- { 0x020E, "WM_MOUSEHWHEEL" },
- { 0x0210, "WM_PARENTNOTIFY" },
- { 0x0211, "WM_ENTERMENULOOP" },
- { 0x0212, "WM_EXITMENULOOP" },
- { 0x0213, "WM_NEXTMENU" },
- { 0x0214, "WM_SIZING" },
- { 0x0215, "WM_CAPTURECHANGED" },
- { 0x0216, "WM_MOVING" },
- { 0x0218, "WM_POWERBROADCAST" },
- { 0x0219, "WM_DEVICECHANGE" },
- { 0x0220, "WM_MDICREATE" },
- { 0x0221, "WM_MDIDESTROY" },
- { 0x0222, "WM_MDIACTIVATE" },
- { 0x0223, "WM_MDIRESTORE" },
- { 0x0224, "WM_MDINEXT" },
- { 0x0225, "WM_MDIMAXIMIZE" },
- { 0x0226, "WM_MDITILE" },
- { 0x0227, "WM_MDICASCADE" },
- { 0x0228, "WM_MDIICONARRANGE" },
- { 0x0229, "WM_MDIGETACTIVE" },
- { 0x0230, "WM_MDISETMENU" },
- { 0x0231, "WM_ENTERSIZEMOVE" },
- { 0x0232, "WM_EXITSIZEMOVE" },
- { 0x0233, "WM_DROPFILES" },
- { 0x0234, "WM_MDIREFRESHMENU" },
- { 0x0281, "WM_IME_SETCONTEXT" },
- { 0x0282, "WM_IME_NOTIFY" },
- { 0x0283, "WM_IME_CONTROL" },
- { 0x0284, "WM_IME_COMPOSITIONFULL" },
- { 0x0285, "WM_IME_SELECT" },
- { 0x0286, "WM_IME_CHAR" },
- { 0x0288, "WM_IME_REQUEST" },
- { 0x0290, "WM_IME_KEYDOWN" },
- { 0x0291, "WM_IME_KEYUP" },
- { 0x02A0, "WM_NCMOUSEHOVER" },
- { 0x02A1, "WM_MOUSEHOVER" },
- { 0x02A2, "WM_NCMOUSELEAVE" },
- { 0x02A3, "WM_MOUSELEAVE" },
- { 0x02B1, "WM_WTSSESSION_CHANGE" },
- { 0x02C0, "WM_TABLET_FIRST" },
- { 0x02C1, "WM_TABLET_FIRST + 1" },
- { 0x02C2, "WM_TABLET_FIRST + 2" },
- { 0x02C3, "WM_TABLET_FIRST + 3" },
- { 0x02C4, "WM_TABLET_FIRST + 4" },
- { 0x02C5, "WM_TABLET_FIRST + 5" },
- { 0x02C6, "WM_TABLET_FIRST + 6" },
- { 0x02C7, "WM_TABLET_FIRST + 7" },
- { 0x02C8, "WM_TABLET_FIRST + 8" },
- { 0x02C9, "WM_TABLET_FIRST + 9" },
- { 0x02CA, "WM_TABLET_FIRST + 10" },
- { 0x02CB, "WM_TABLET_FIRST + 11" },
- { 0x02CC, "WM_TABLET_FIRST + 12" },
- { 0x02CD, "WM_TABLET_FIRST + 13" },
- { 0x02CE, "WM_TABLET_FIRST + 14" },
- { 0x02CF, "WM_TABLET_FIRST + 15" },
- { 0x02D0, "WM_TABLET_FIRST + 16" },
- { 0x02D1, "WM_TABLET_FIRST + 17" },
- { 0x02D2, "WM_TABLET_FIRST + 18" },
- { 0x02D3, "WM_TABLET_FIRST + 19" },
- { 0x02D4, "WM_TABLET_FIRST + 20" },
- { 0x02D5, "WM_TABLET_FIRST + 21" },
- { 0x02D6, "WM_TABLET_FIRST + 22" },
- { 0x02D7, "WM_TABLET_FIRST + 23" },
- { 0x02D8, "WM_TABLET_FIRST + 24" },
- { 0x02D9, "WM_TABLET_FIRST + 25" },
- { 0x02DA, "WM_TABLET_FIRST + 26" },
- { 0x02DB, "WM_TABLET_FIRST + 27" },
- { 0x02DC, "WM_TABLET_FIRST + 28" },
- { 0x02DD, "WM_TABLET_FIRST + 29" },
- { 0x02DE, "WM_TABLET_FIRST + 30" },
- { 0x02DF, "WM_TABLET_LAST" },
- { 0x0300, "WM_CUT" },
- { 0x0301, "WM_COPY" },
- { 0x0302, "WM_PASTE" },
- { 0x0303, "WM_CLEAR" },
- { 0x0304, "WM_UNDO" },
- { 0x0305, "WM_RENDERFORMAT" },
- { 0x0306, "WM_RENDERALLFORMATS" },
- { 0x0307, "WM_DESTROYCLIPBOARD" },
- { 0x0308, "WM_DRAWCLIPBOARD" },
- { 0x0309, "WM_PAINTCLIPBOARD" },
- { 0x030A, "WM_VSCROLLCLIPBOARD" },
- { 0x030B, "WM_SIZECLIPBOARD" },
- { 0x030C, "WM_ASKCBFORMATNAME" },
- { 0x030D, "WM_CHANGECBCHAIN" },
- { 0x030E, "WM_HSCROLLCLIPBOARD" },
- { 0x030F, "WM_QUERYNEWPALETTE" },
- { 0x0310, "WM_PALETTEISCHANGING" },
- { 0x0311, "WM_PALETTECHANGED" },
- { 0x0312, "WM_HOTKEY" },
- { 0x0317, "WM_PRINT" },
- { 0x0318, "WM_PRINTCLIENT" },
- { 0x0319, "WM_APPCOMMAND" },
- { 0x031A, "WM_THEMECHANGED" },
- { 0x0358, "WM_HANDHELDFIRST" },
- { 0x0359, "WM_HANDHELDFIRST + 1" },
- { 0x035A, "WM_HANDHELDFIRST + 2" },
- { 0x035B, "WM_HANDHELDFIRST + 3" },
- { 0x035C, "WM_HANDHELDFIRST + 4" },
- { 0x035D, "WM_HANDHELDFIRST + 5" },
- { 0x035E, "WM_HANDHELDFIRST + 6" },
- { 0x035F, "WM_HANDHELDLAST" },
- { 0x0360, "WM_AFXFIRST" },
- { 0x0361, "WM_AFXFIRST + 1" },
- { 0x0362, "WM_AFXFIRST + 2" },
- { 0x0363, "WM_AFXFIRST + 3" },
- { 0x0364, "WM_AFXFIRST + 4" },
- { 0x0365, "WM_AFXFIRST + 5" },
- { 0x0366, "WM_AFXFIRST + 6" },
- { 0x0367, "WM_AFXFIRST + 7" },
- { 0x0368, "WM_AFXFIRST + 8" },
- { 0x0369, "WM_AFXFIRST + 9" },
- { 0x036A, "WM_AFXFIRST + 10" },
- { 0x036B, "WM_AFXFIRST + 11" },
- { 0x036C, "WM_AFXFIRST + 12" },
- { 0x036D, "WM_AFXFIRST + 13" },
- { 0x036E, "WM_AFXFIRST + 14" },
- { 0x036F, "WM_AFXFIRST + 15" },
- { 0x0370, "WM_AFXFIRST + 16" },
- { 0x0371, "WM_AFXFIRST + 17" },
- { 0x0372, "WM_AFXFIRST + 18" },
- { 0x0373, "WM_AFXFIRST + 19" },
- { 0x0374, "WM_AFXFIRST + 20" },
- { 0x0375, "WM_AFXFIRST + 21" },
- { 0x0376, "WM_AFXFIRST + 22" },
- { 0x0377, "WM_AFXFIRST + 23" },
- { 0x0378, "WM_AFXFIRST + 24" },
- { 0x0379, "WM_AFXFIRST + 25" },
- { 0x037A, "WM_AFXFIRST + 26" },
- { 0x037B, "WM_AFXFIRST + 27" },
- { 0x037C, "WM_AFXFIRST + 28" },
- { 0x037D, "WM_AFXFIRST + 29" },
- { 0x037E, "WM_AFXFIRST + 30" },
- { 0x037F, "WM_AFXLAST" },
- { 0x0380, "WM_PENWINFIRST" },
- { 0x0381, "WM_PENWINFIRST + 1" },
- { 0x0382, "WM_PENWINFIRST + 2" },
- { 0x0383, "WM_PENWINFIRST + 3" },
- { 0x0384, "WM_PENWINFIRST + 4" },
- { 0x0385, "WM_PENWINFIRST + 5" },
- { 0x0386, "WM_PENWINFIRST + 6" },
- { 0x0387, "WM_PENWINFIRST + 7" },
- { 0x0388, "WM_PENWINFIRST + 8" },
- { 0x0389, "WM_PENWINFIRST + 9" },
- { 0x038A, "WM_PENWINFIRST + 10" },
- { 0x038B, "WM_PENWINFIRST + 11" },
- { 0x038C, "WM_PENWINFIRST + 12" },
- { 0x038D, "WM_PENWINFIRST + 13" },
- { 0x038E, "WM_PENWINFIRST + 14" },
- { 0x038F, "WM_PENWINLAST" },
- { 0x0400, "WM_USER" },
- { 0x8000, "WM_APP" },
- { 0,0 }}; // End of known messages
-
-// Looks up the WM_ message in the table above
-static const char* findWMstr(uint msg)
-{
-    uint i = 0;
-    const char* result = 0;
-    // Known WM_'s
-    while (knownWM[i].str && (knownWM[i].WM != msg))
-        ++i;
-    result = knownWM[i].str;
-    return result;
-};
-
-// Convenience function for converting flags and values into readable strings
-struct FLAG_STRING_STRUCT
-{
-    uint value;
-    const char* str;
-};
-
-FLAG_STRING_STRUCT FLAG_STRING(uint value = 0, const char *c = 0)
-{
-    FLAG_STRING_STRUCT s = {value, c};
-    return s;
-}
-
-#define FLGSTR(x) FLAG_STRING(x, #x)
-
-// Returns an ORed (" | ") together string for the flags active in the actual
-// value. (...) must consist of FLAG_STRING, with a FLAG_STRING() as the last
-// value in the list passed to the function
-QString flagCheck(uint actual, ...)
-{
-    va_list ap;
-    va_start(ap, actual);
-
-    QString result;
-    int count = 0;
-    FLAG_STRING_STRUCT v;
-    while((v=va_arg(ap,FLAG_STRING_STRUCT)).str) {
-        if ((actual & v.value) == v.value) {
-            if (count++)
-                result += QLatin1String(" | ");
-            result += QString::fromLatin1(v.str);
-        }
-    }
-    va_end(ap);
-    return result;
-};
-
-// Returns the string representation of the value in 'actual'. (...) must
-// consist of FLAG_STRING, with a FLAG_STRING() as the last value in the list
-// passed to the function
-QString valueCheck(uint actual, ...)
-{
-    va_list ap;
-    va_start(ap, actual);
-
-    QString result;
-    FLAG_STRING_STRUCT v;
-    while((v=va_arg(ap,FLAG_STRING_STRUCT)).str && (actual != v.value))
-        ;
-    result = QString::fromLatin1(v.str);
-
-    va_end(ap);
-    return result;
-};
-
-#ifdef Q_CC_BOR
-
-QString decodeMSG(const MSG& msg)
-{
-    return QString::fromLatin1("THis is not supported on Borland");
-}
-
-#else
-
-// Returns a "human readable" string representation of the MSG and the
-// information it points to
-QString decodeMSG(const MSG& msg)
-{
-    const WPARAM wParam = msg.wParam;
-    const LPARAM lParam = msg.lParam;
-    QString wmmsg = QString::fromLatin1(findWMstr(msg.message));
-    // Unknown WM_, so use number
-    if (wmmsg.isEmpty())
-        wmmsg = QString::fromLatin1("WM_(%1)").arg(msg.message);
-
-    QString rawParameters;
-    rawParameters.sprintf("hwnd(0x%p) ", (void *)msg.hwnd);
-
-    // Custom WM_'s
-    if (msg.message > WM_APP)
-        wmmsg = QString::fromLatin1("WM_APP + %1").arg(msg.message - WM_APP);
-    else if (msg.message > WM_USER)
-        wmmsg = QString::fromLatin1("WM_USER + %1").arg(msg.message - WM_USER);
-
-    QString parameters;
-    switch (msg.message) {
-#ifdef WM_ACTIVATE
-        case WM_ACTIVATE:
-            {
-                QString activation = valueCheck(wParam,
-                                                FLAG_STRING(WA_ACTIVE,      "Activate"),
-                                                FLAG_STRING(WA_INACTIVE,    "Deactivate"),
-                                                FLAG_STRING(WA_CLICKACTIVE, "Activate by mouseclick"),
-                                                FLAG_STRING());
-                parameters.sprintf("%s Hwnd (0x%p)", activation.toLatin1().data(), (void *)msg.hwnd);
-            }
-            break;
-#endif
-#ifdef WM_CAPTURECHANGED
-        case WM_CAPTURECHANGED:
-            parameters.sprintf("Hwnd gaining capture (0x%p)", (void *)lParam);
-            break;
-#endif
-#ifdef WM_CREATE
-        case WM_CREATE:
-            {
-                LPCREATESTRUCT lpcs = (LPCREATESTRUCT)lParam;
-                QString styles = flagCheck(lpcs->style,
-                                           FLGSTR(WS_BORDER),
-                                           FLGSTR(WS_CAPTION),
-                                           FLGSTR(WS_CHILD),
-                                           FLGSTR(WS_CLIPCHILDREN),
-                                           FLGSTR(WS_CLIPSIBLINGS),
-                                           FLGSTR(WS_DISABLED),
-                                           FLGSTR(WS_DLGFRAME),
-                                           FLGSTR(WS_GROUP),
-                                           FLGSTR(WS_HSCROLL),
-                                           FLGSTR(WS_OVERLAPPED),
-#if defined(WS_OVERLAPPEDWINDOW) && (WS_OVERLAPPEDWINDOW != 0)
-                                           FLGSTR(WS_OVERLAPPEDWINDOW),
-#endif
-#ifdef WS_ICONIC
-                                           FLGSTR(WS_ICONIC),
-#endif
-                                           FLGSTR(WS_MAXIMIZE),
-                                           FLGSTR(WS_MAXIMIZEBOX),
-                                           FLGSTR(WS_MINIMIZE),
-                                           FLGSTR(WS_MINIMIZEBOX),
-                                           FLGSTR(WS_OVERLAPPEDWINDOW),
-                                           FLGSTR(WS_POPUP),
-#ifdef WS_POPUPWINDOW
-                                           FLGSTR(WS_POPUPWINDOW),
-#endif
-                                           FLGSTR(WS_SIZEBOX),
-                                           FLGSTR(WS_SYSMENU),
-                                           FLGSTR(WS_TABSTOP),
-                                           FLGSTR(WS_THICKFRAME),
-#ifdef WS_TILED
-                                           FLGSTR(WS_TILED),
-#endif
-#ifdef WS_TILEDWINDOW
-                                           FLGSTR(WS_TILEDWINDOW),
-#endif
-                                           FLGSTR(WS_VISIBLE),
-                                           FLGSTR(WS_VSCROLL),
-                                           FLAG_STRING());
-
-                QString exStyles = flagCheck(lpcs->dwExStyle,
-#ifdef WS_EX_ACCEPTFILES
-                                           FLGSTR(WS_EX_ACCEPTFILES),
-#endif
-#ifdef WS_EX_APPWINDOW
-                                           FLGSTR(WS_EX_APPWINDOW),
-#endif
-                                           FLGSTR(WS_EX_CLIENTEDGE),
-                                           FLGSTR(WS_EX_DLGMODALFRAME),
-#ifdef WS_EX_LEFT
-                                           FLGSTR(WS_EX_LEFT),
-#endif
-                                           FLGSTR(WS_EX_LEFTSCROLLBAR),
-#ifdef WS_EX_LTRREADING
-                                           FLGSTR(WS_EX_LTRREADING),
-#endif
-#ifdef WS_EX_MDICHILD
-                                           FLGSTR(WS_EX_MDICHILD),
-#endif
-#ifdef WS_EX_NOACTIVATE
-                                           FLGSTR(WS_EX_NOACTIVATE),
-#endif
-#ifdef WS_EX_NOANIMATION
-                                           FLGSTR(WS_EX_NOANIMATION),
-#endif
-                                           FLGSTR(WS_EX_NOPARENTNOTIFY),
-                                           FLGSTR(WS_EX_OVERLAPPEDWINDOW),
-#ifdef WS_EX_PALETTEWINDOW
-                                           FLGSTR(WS_EX_PALETTEWINDOW),
-#endif
-#ifdef WS_EX_RIGHT
-                                           FLGSTR(WS_EX_RIGHT),
-#endif
-#ifdef WS_EX_RIGHTSCROLLBAR
-                                           FLGSTR(WS_EX_RIGHTSCROLLBAR),
-#endif
-#ifdef WS_EX_RTLREADING
-                                           FLGSTR(WS_EX_RTLREADING),
-#endif
-                                           FLGSTR(WS_EX_STATICEDGE),
-                                           FLGSTR(WS_EX_TOOLWINDOW),
-                                           FLGSTR(WS_EX_TOPMOST),
-#ifdef WS_EX_TRANSPARENT
-                                           FLGSTR(WS_EX_TRANSPARENT),
-#endif
-                                           FLGSTR(WS_EX_WINDOWEDGE),
-#ifdef WS_EX_CAPTIONOKBTN
-                                           FLGSTR(WS_EX_CAPTIONOKBTN),
-#endif
-                                           FLAG_STRING());
-
-                QString className;
-                if (lpcs->lpszClass != 0) {
-                    if (HIWORD(lpcs->lpszClass) == 0) // Atom
-                        className = QString::number(LOWORD(lpcs->lpszClass), 16);
-                    else                              // String
-                        className = QString((QChar*)lpcs->lpszClass,
-                                            (int)wcslen(reinterpret_cast<const wchar_t *>(lpcs->lpszClass)));
-                }
-
-                QString windowName;
-                if (lpcs->lpszName != 0)
-                    windowName = QString((QChar*)lpcs->lpszName,
-                                         (int)wcslen(reinterpret_cast<const wchar_t *>(lpcs->lpszName)));
-
-                parameters.sprintf("x,y(%4d,%4d) w,h(%4d,%4d) className(%s) windowName(%s) parent(0x%p) style(%s) exStyle(%s)",
-                                   lpcs->x, lpcs->y, lpcs->cx, lpcs->cy, className.toLatin1().data(),
-                                   windowName.toLatin1().data(), (void *)lpcs->hwndParent,
-                                   styles.toLatin1().data(), exStyles.toLatin1().data());
-            }
-            break;
-#endif
-#ifdef WM_DESTROY
-        case WM_DESTROY:
-            parameters.sprintf("Destroy hwnd (0x%p)", (void *)msg.hwnd);
-            break;
-#endif
-#ifdef WM_IME_NOTIFY
-        case WM_IME_NOTIFY:
-            {
-                QString imnCommand = valueCheck(wParam,
-                                            FLGSTR(IMN_CHANGECANDIDATE),
-                                            FLGSTR(IMN_CLOSECANDIDATE),
-                                            FLGSTR(IMN_CLOSESTATUSWINDOW),
-                                            FLGSTR(IMN_GUIDELINE),
-                                            FLGSTR(IMN_OPENCANDIDATE),
-                                            FLGSTR(IMN_OPENSTATUSWINDOW),
-                                            FLGSTR(IMN_SETCANDIDATEPOS),
-                                            FLGSTR(IMN_SETCOMPOSITIONFONT),
-                                            FLGSTR(IMN_SETCOMPOSITIONWINDOW),
-                                            FLGSTR(IMN_SETCONVERSIONMODE),
-                                            FLGSTR(IMN_SETOPENSTATUS),
-                                            FLGSTR(IMN_SETSENTENCEMODE),
-                                            FLGSTR(IMN_SETSTATUSWINDOWPOS),
-                                            FLAG_STRING());
-                parameters.sprintf("Command(%s : 0x%p)", imnCommand.toLatin1().data(), (void *)lParam);
-            }
-            break;
-#endif
-#ifdef WM_IME_SETCONTEXT
-        case WM_IME_SETCONTEXT:
-            {
-                bool fSet = (BOOL)wParam;
-                DWORD fShow = (DWORD)lParam;
-                QString showFlgs = flagCheck(fShow,
-#ifdef ISC_SHOWUICOMPOSITIONWINDOW
-                                             FLGSTR(ISC_SHOWUICOMPOSITIONWINDOW),
-#endif
-#ifdef ISC_SHOWUIGUIDWINDOW
-                                             FLGSTR(ISC_SHOWUIGUIDWINDOW),
-#endif
-#ifdef ISC_SHOWUISOFTKBD
-                                             FLGSTR(ISC_SHOWUISOFTKBD),
-#endif
-                                             FLGSTR(ISC_SHOWUICANDIDATEWINDOW),
-                                             FLGSTR(ISC_SHOWUICANDIDATEWINDOW << 1),
-                                             FLGSTR(ISC_SHOWUICANDIDATEWINDOW << 2),
-                                             FLGSTR(ISC_SHOWUICANDIDATEWINDOW << 3),
-                                             FLAG_STRING());
-                parameters.sprintf("Input context(%s) Show flags(%s)", (fSet? "Active" : "Inactive"), showFlgs.toLatin1().data());
-            }
-            break;
-#endif
-#ifdef WM_KILLFOCUS
-        case WM_KILLFOCUS:
-            parameters.sprintf("Hwnd gaining keyboard focus (0x%p)", (void *)wParam);
-            break;
-#endif
-#ifdef WM_CHAR
-        case WM_CHAR:
-#endif
-#ifdef WM_IME_CHAR
-        case WM_IME_CHAR:
-#endif
-#ifdef WM_KEYDOWN
-        case WM_KEYDOWN:
-#endif
-#ifdef WM_KEYUP
-        case WM_KEYUP:
-            {
-                int nVirtKey     = (int)wParam;
-                long lKeyData    = (long)lParam;
-                int repCount     = (lKeyData & 0xffff);        // Bit 0-15
-                int scanCode     = (lKeyData & 0xf0000) >> 16; // Bit 16-23
-                bool contextCode = (lKeyData && 0x20000000);   // Bit 29
-                bool prevState   = (lKeyData && 0x40000000);   // Bit 30
-                bool transState  = (lKeyData && 0x80000000);   // Bit 31
-                parameters.sprintf("Virual-key(0x%x) Scancode(%d) Rep(%d) Contextcode(%d), Prev state(%d), Trans state(%d)",
-                                   nVirtKey, scanCode, repCount, contextCode, prevState, transState);
-            }
-            break;
-#endif
-#ifdef WM_INPUTLANGCHANGE
-        case WM_INPUTLANGCHANGE:
-            parameters = QLatin1String("Keyboard layout changed");
-            break;
-#endif // WM_INPUTLANGCHANGE
-#ifdef WM_NCACTIVATE
-        case WM_NCACTIVATE:
-            {
-            parameters = (msg.wParam? QLatin1String("Active Titlebar") : QLatin1String("Inactive Titlebar"));
-            }
-            break;
-#endif
-#ifdef WM_MOUSEACTIVATE
-        case WM_MOUSEACTIVATE:
-            {
-                QString mouseMsg = QString::fromLatin1(findWMstr(HIWORD(lParam)));
-                parameters.sprintf("TLW(0x%p) HittestCode(0x%x) MouseMsg(%s)", (void *)wParam, LOWORD(lParam), mouseMsg.toLatin1().data());
-            }
-            break;
-#endif
-#ifdef WM_MOUSELEAVE
-        case WM_MOUSELEAVE:
-            break; // wParam & lParam not used
-#endif
-#ifdef WM_MOUSEHOVER
-        case WM_MOUSEHOVER:
-#endif
-#ifdef WM_MOUSEWHEEL
-        case WM_MOUSEWHEEL:
-#endif
-#ifdef WM_MOUSEHWHEEL
-        case WM_MOUSEHWHEEL:
-#endif
-#ifdef WM_LBUTTONDBLCLK
-        case WM_LBUTTONDBLCLK:
-#endif
-#ifdef WM_LBUTTONDOWN
-        case WM_LBUTTONDOWN:
-#endif
-#ifdef WM_LBUTTONUP
-        case WM_LBUTTONUP:
-#endif
-#ifdef WM_MBUTTONDBLCLK
-        case WM_MBUTTONDBLCLK:
-#endif
-#ifdef WM_MBUTTONDOWN
-        case WM_MBUTTONDOWN:
-#endif
-#ifdef WM_MBUTTONUP
-        case WM_MBUTTONUP:
-#endif
-#ifdef WM_RBUTTONDBLCLK
-        case WM_RBUTTONDBLCLK:
-#endif
-#ifdef WM_RBUTTONDOWN
-        case WM_RBUTTONDOWN:
-#endif
-#ifdef WM_RBUTTONUP
-        case WM_RBUTTONUP:
-#endif
-#ifdef WM_MOUSEMOVE
-        case WM_MOUSEMOVE:
-            {
-                QString vrtKeys = flagCheck(wParam,
-                                            FLGSTR(MK_CONTROL),
-                                            FLGSTR(MK_LBUTTON),
-                                            FLGSTR(MK_MBUTTON),
-                                            FLGSTR(MK_RBUTTON),
-                                            FLGSTR(MK_SHIFT),
-#ifdef MK_XBUTTON1
-                                            FLGSTR(MK_XBUTTON1),
-#endif
-#ifdef MK_XBUTTON2
-                                            FLGSTR(MK_XBUTTON2),
-#endif
-                                            FLAG_STRING());
-                parameters.sprintf("x,y(%4d,%4d) Virtual Keys(%s)", GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), vrtKeys.toLatin1().data());
-            }
-            break;
-#endif
-#ifdef WM_MOVE
-        case WM_MOVE:
-            parameters.sprintf("x,y(%4d,%4d)", LOWORD(lParam), HIWORD(lParam));
-            break;
-#endif
-#if defined(WM_PAINT) && defined(WM_ERASEBKGND)
-        case WM_ERASEBKGND:
-        case WM_PAINT:
-            parameters.sprintf("hdc(0x%p)", (void *)wParam);
-            break;
-#endif
-#ifdef WM_QUERYNEWPALETTE
-        case WM_QUERYNEWPALETTE:
-            break; // lParam & wParam are unused
-#endif
-#ifdef WM_SETCURSOR
-        case WM_SETCURSOR:
-            {
-                QString mouseMsg = QString::fromLatin1(findWMstr(HIWORD(lParam)));
-                parameters.sprintf("HitTestCode(0x%x) MouseMsg(%s)", LOWORD(lParam), mouseMsg.toLatin1().data());
-            }
-            break;
-#endif
-#ifdef WM_SETFOCUS
-        case WM_SETFOCUS:
-            parameters.sprintf("Lost Focus (0x%p)", (void *)wParam);
-            break;
-#endif
-#ifdef WM_SETTEXT
-        case WM_SETTEXT:
-            parameters.sprintf("Set Text (%s)", QString((QChar*)lParam, (int)wcslen(reinterpret_cast<const wchar_t *>(lParam))).toLatin1().data()); //Unicode string
-            break;
-#endif
-#ifdef WM_SIZE
-        case WM_SIZE:
-            {
-                QString showMode = valueCheck(wParam,
-                                              FLGSTR(SIZE_MAXHIDE),
-                                              FLGSTR(SIZE_MAXIMIZED),
-                                              FLGSTR(SIZE_MAXSHOW),
-                                              FLGSTR(SIZE_MINIMIZED),
-                                              FLGSTR(SIZE_RESTORED),
-                                              FLAG_STRING());
-
-                parameters.sprintf("w,h(%4d,%4d) showmode(%s)", LOWORD(lParam), HIWORD(lParam), showMode.toLatin1().data());
-            }
-            break;
-#endif
-#ifdef WM_WINDOWPOSCHANGED
-        case WM_WINDOWPOSCHANGED:
-            {
-                LPWINDOWPOS winPos = (LPWINDOWPOS)lParam;
-                if (!winPos)
-                    break;
-                QString hwndAfter = valueCheck(quint64(winPos->hwndInsertAfter),
-                                          FLAG_STRING((qptrdiff)HWND_BOTTOM,    "HWND_BOTTOM"),
-                                          FLAG_STRING((qptrdiff)HWND_NOTOPMOST, "HWND_NOTOPMOST"),
-                                          FLAG_STRING((qptrdiff)HWND_TOP,       "HWND_TOP"),
-                                          FLAG_STRING((qptrdiff)HWND_TOPMOST,   "HWND_TOPMOST"),
-                                          FLAG_STRING());
-                if (hwndAfter.isEmpty())
-                    hwndAfter = QString::number((quintptr)winPos->hwndInsertAfter, 16);
-                QString flags = flagCheck(winPos->flags,
-                                          FLGSTR(SWP_DRAWFRAME),
-                                          FLGSTR(SWP_FRAMECHANGED),
-                                          FLGSTR(SWP_HIDEWINDOW),
-                                          FLGSTR(SWP_NOACTIVATE),
-#ifdef SWP_NOCOPYBITS
-                                          FLGSTR(SWP_NOCOPYBITS),
-#endif
-                                          FLGSTR(SWP_NOMOVE),
-                                          FLGSTR(SWP_NOOWNERZORDER),
-                                          FLGSTR(SWP_NOREDRAW),
-                                          FLGSTR(SWP_NOREPOSITION),
-#ifdef SWP_NOSENDCHANGING
-                                          FLGSTR(SWP_NOSENDCHANGING),
-#endif
-                                          FLGSTR(SWP_NOSIZE),
-                                          FLGSTR(SWP_NOZORDER),
-                                          FLGSTR(SWP_SHOWWINDOW),
-                                          FLAG_STRING());
-                parameters.sprintf("x,y(%4d,%4d) w,h(%4d,%4d) flags(%s) hwndAfter(%s)", winPos->x, winPos->y, winPos->cx, winPos->cy, flags.toLatin1().data(), hwndAfter.toLatin1().data());
-            }
-            break;
-#endif
-        default:
-            parameters.sprintf("wParam(0x%p) lParam(0x%p)", (void *)wParam, (void *)lParam);
-            break;
-    }
-    // Yes, we want to give the WM_ names 20 chars of space before showing the
-    // decoded message, since some of the common messages are quite long, and
-    // we don't want the decoded information to vary in output position
-    QString message = QString::fromLatin1("%1: ").arg(wmmsg, 20);
-    message += rawParameters;
-    message += parameters;
-    return message;
-}
-
-#endif
-
-QDebug operator<<(QDebug dbg, const MSG &msg)
-{
-    dbg << decodeMSG(msg);
-    return dbg.nospace();
-}
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/core/kernel/qeventdispatcher_blackberry.cpp b/src/core/kernel/qeventdispatcher_blackberry.cpp
deleted file mode 100644 (file)
index af7f9cc..0000000
+++ /dev/null
@@ -1,508 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Research In Motion <blackberry-qt@qnx.com>
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qeventdispatcher_blackberry_p.h"
-#include "qsocketnotifier.h"
-#include "qdebug.h"
-#include "qelapsedtimer.h"
-#include "qthread_p.h"
-
-#include <bps/bps.h>
-#include <bps/event.h>
-
-//#define QEVENTDISPATCHERBLACKBERRY_DEBUG
-
-#ifdef QEVENTDISPATCHERBLACKBERRY_DEBUG
-#define qEventDispatcherDebug qDebug() << QThread::currentThread()
-#else
-#define qEventDispatcherDebug QT_NO_QDEBUG_MACRO()
-#endif
-
-class BpsChannelScopeSwitcher
-{
-public:
-    BpsChannelScopeSwitcher(int scopeChannel) : innerChannel(scopeChannel)
-    {
-        outerChannel = bps_channel_get_active();
-        if (outerChannel != innerChannel)
-            bps_channel_set_active(innerChannel);
-    }
-
-    ~BpsChannelScopeSwitcher()
-    {
-        if (outerChannel != innerChannel)
-            bps_channel_set_active(outerChannel);
-    }
-
-private:
-    int innerChannel;
-    int outerChannel;
-};
-
-class BBScopedLoopLevelCounter
-{
-    QEventDispatcherBlackberryPrivate *d;
-
-public:
-    inline BBScopedLoopLevelCounter(QEventDispatcherBlackberryPrivate *p)
-        : d(p)
-    { ++d->loop_level; }
-
-    inline ~BBScopedLoopLevelCounter()
-    { --d->loop_level; }
-};
-
-struct bpsIOHandlerData
-{
-    bpsIOHandlerData()
-        : count(0), readfds(0), writefds(0), exceptfds(0)
-    {
-    }
-
-    int count;
-    fd_set *readfds;
-    fd_set *writefds;
-    fd_set *exceptfds;
-};
-
-static int bpsUnblockDomain = -1;
-
-static int bpsIOHandler(int fd, int io_events, void *data)
-{
-    qEventDispatcherDebug << Q_FUNC_INFO;
-    // decode callback payload
-    bpsIOHandlerData *ioData = static_cast<bpsIOHandlerData*>(data);
-
-    // check if first file is ready
-    bool firstReady = (ioData->count == 0);
-
-    // update ready state of file
-    if (io_events & BPS_IO_INPUT) {
-        qEventDispatcherDebug << fd << "ready for Read";
-        FD_SET(fd, ioData->readfds);
-        ioData->count++;
-    }
-
-    if (io_events & BPS_IO_OUTPUT) {
-        qEventDispatcherDebug << fd << "ready for Write";
-        FD_SET(fd, ioData->writefds);
-        ioData->count++;
-    }
-
-    if (io_events & BPS_IO_EXCEPT) {
-        qEventDispatcherDebug << fd << "ready for Exception";
-        FD_SET(fd, ioData->exceptfds);
-        ioData->count++;
-    }
-
-    // force bps_get_event() to return immediately by posting an event to ourselves;
-    // but this only needs to happen once if multiple files become ready at the same time
-    if (firstReady) {
-        qEventDispatcherDebug << "Sending bpsIOReadyDomain event";
-        // create unblock event
-        bps_event_t *event;
-        int result = bps_event_create(&event, bpsUnblockDomain, 0, NULL, NULL);
-        if (Q_UNLIKELY(result != BPS_SUCCESS)) {
-            qWarning("QEventDispatcherBlackberry: bps_event_create failed");
-            return BPS_FAILURE;
-        }
-
-        // post unblock event to our thread; in this callback the bps channel is
-        // guaranteed to be the same that was active when bps_add_fd was called
-        result = bps_push_event(event);
-        if (Q_UNLIKELY(result != BPS_SUCCESS)) {
-            qWarning("QEventDispatcherBlackberry: bps_push_event failed");
-            bps_event_destroy(event);
-            return BPS_FAILURE;
-        }
-    }
-
-    return BPS_SUCCESS;
-}
-
-QEventDispatcherBlackberryPrivate::QEventDispatcherBlackberryPrivate()
-    : loop_level(0)
-    , ioData(new bpsIOHandlerData)
-{
-    // prepare to use BPS
-    int result = bps_initialize();
-    if (Q_UNLIKELY(result != BPS_SUCCESS))
-        qFatal("QEventDispatcherBlackberry: bps_initialize failed");
-
-    bps_channel = bps_channel_get_active();
-
-    if (bps_channel_create(&holding_channel, 0) != BPS_SUCCESS) {
-        qWarning("QEventDispatcherBlackberry: bps_channel_create failed");
-        holding_channel = -1;
-    }
-
-    // get domain for IO ready and wake up events - ignoring race condition here for now
-    if (bpsUnblockDomain == -1) {
-        bpsUnblockDomain = bps_register_domain();
-        if (Q_UNLIKELY(bpsUnblockDomain == -1))
-            qWarning("QEventDispatcherBlackberry: bps_register_domain failed");
-    }
-}
-
-QEventDispatcherBlackberryPrivate::~QEventDispatcherBlackberryPrivate()
-{
-    if ((holding_channel != -1) &&
-        (bps_channel_destroy(holding_channel) != BPS_SUCCESS)) {
-        qWarning("QEventDispatcherBlackberry: bps_channel_destroy failed");
-    }
-
-    // we're done using BPS
-    bps_shutdown();
-}
-
-int QEventDispatcherBlackberryPrivate::initThreadWakeUp()
-{
-    return -1;  // no fd's used
-}
-
-int QEventDispatcherBlackberryPrivate::processThreadWakeUp(int nsel)
-{
-    Q_UNUSED(nsel);
-    return wakeUps.fetchAndStoreRelaxed(0);
-}
-
-/////////////////////////////////////////////////////////////////////////////
-
-QEventDispatcherBlackberry::QEventDispatcherBlackberry(QObject *parent)
-    : QEventDispatcherUNIX(*new QEventDispatcherBlackberryPrivate, parent)
-{
-}
-
-QEventDispatcherBlackberry::QEventDispatcherBlackberry(QEventDispatcherBlackberryPrivate &dd, QObject *parent)
-    : QEventDispatcherUNIX(dd, parent)
-{
-}
-
-QEventDispatcherBlackberry::~QEventDispatcherBlackberry()
-{
-}
-
-void QEventDispatcherBlackberry::registerSocketNotifier(QSocketNotifier *notifier)
-{
-    Q_ASSERT(notifier);
-    Q_D(QEventDispatcherBlackberry);
-
-    int sockfd = notifier->socket();
-    int type = notifier->type();
-
-    qEventDispatcherDebug << Q_FUNC_INFO << "fd =" << sockfd;
-
-    if (Q_UNLIKELY(sockfd >= FD_SETSIZE)) {
-        qWarning() << "QEventDispatcherBlackberry: cannot register QSocketNotifier (fd too high)"
-                   << sockfd;
-        return;
-    }
-
-    // Register the fd with bps
-    BpsChannelScopeSwitcher channelSwitcher(d->bps_channel);
-    int io_events = ioEvents(sockfd);
-    if (io_events)
-        bps_remove_fd(sockfd);
-
-    switch (type) {
-    case QSocketNotifier::Read:
-        qEventDispatcherDebug << "Registering" << sockfd << "for Reads";
-        io_events |= BPS_IO_INPUT;
-        break;
-    case QSocketNotifier::Write:
-        qEventDispatcherDebug << "Registering" << sockfd << "for Writes";
-        io_events |= BPS_IO_OUTPUT;
-        break;
-    case QSocketNotifier::Exception:
-    default:
-        qEventDispatcherDebug << "Registering" << sockfd << "for Exceptions";
-        io_events |= BPS_IO_EXCEPT;
-        break;
-    }
-
-    const int result = bps_add_fd(sockfd, io_events, &bpsIOHandler, d->ioData.data());
-    if (Q_UNLIKELY(result != BPS_SUCCESS))
-        qWarning() << "QEventDispatcherBlackberry: bps_add_fd failed";
-
-    // Call the base Unix implementation. Needed to allow select() to be called correctly
-    QEventDispatcherUNIX::registerSocketNotifier(notifier);
-}
-
-void QEventDispatcherBlackberry::unregisterSocketNotifier(QSocketNotifier *notifier)
-{
-    Q_D(QEventDispatcherBlackberry);
-
-    int sockfd = notifier->socket();
-
-    qEventDispatcherDebug << Q_FUNC_INFO << "fd =" << sockfd;
-
-    if (Q_UNLIKELY(sockfd >= FD_SETSIZE)) {
-        qWarning() << "QEventDispatcherBlackberry: cannot unregister QSocketNotifier" << sockfd;
-        return;
-    }
-
-    // Allow the base Unix implementation to unregister the fd too (before call to ioEvents()!)
-    QEventDispatcherUNIX::unregisterSocketNotifier(notifier);
-
-    // Unregister the fd with bps
-    BpsChannelScopeSwitcher channelSwitcher(d->bps_channel);
-    int result = bps_remove_fd(sockfd);
-    if (Q_UNLIKELY(result != BPS_SUCCESS))
-        qWarning() << "QEventDispatcherBlackberry: bps_remove_fd failed" << sockfd;
-
-    const int io_events = ioEvents(sockfd);
-    // if other socket notifier is watching sockfd, readd it
-    if (io_events) {
-        result = bps_add_fd(sockfd, io_events, &bpsIOHandler, d->ioData.data());
-        if (Q_UNLIKELY(result != BPS_SUCCESS))
-            qWarning("QEventDispatcherBlackberry: bps_add_fd error");
-    }
-}
-
-static inline int timevalToMillisecs(const timeval &tv)
-{
-    return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
-}
-
-static inline void destroyHeldBpsEvent(int holding_channel)
-{
-    // Switch to the holding channel and use bps_get_event() to trigger its destruction.  We
-    // don't care about the return value from this call to bps_get_event().
-    BpsChannelScopeSwitcher holdingChannelSwitcher(holding_channel);
-    bps_event_t *held_event = 0;
-    (void)bps_get_event(&held_event, 0);
- }
-
-int QEventDispatcherBlackberry::select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
-                                       timeval *timeout)
-{
-    Q_UNUSED(nfds);
-    Q_D(QEventDispatcherBlackberry);
-    const BBScopedLoopLevelCounter bbLoopCounter(d);
-
-    BpsChannelScopeSwitcher channelSwitcher(d->bps_channel);
-
-    // prepare file sets for bps callback
-    d->ioData->count = 0;
-    d->ioData->readfds = readfds;
-    d->ioData->writefds = writefds;
-    d->ioData->exceptfds = exceptfds;
-
-    // reset all file sets
-    if (readfds)
-        FD_ZERO(readfds);
-
-    if (writefds)
-        FD_ZERO(writefds);
-
-    if (exceptfds)
-        FD_ZERO(exceptfds);
-
-    bps_event_t *event = 0;
-    unsigned int eventCount = 0;
-
-    // If an event handler called through filterEvent() starts a nested event loop by creating a
-    // new QEventLoop, we will recursively enter this function again.  However, each time
-    // bps_get_event() is called, it destroys the last event it handed out before returning the
-    // next event.  We don't want it to destroy the event that triggered the nested event loop,
-    // since there may still be more handlers that need to get that event, once the nested event
-    // loop is done and control returns to the outer event loop.
-    //
-    // So we move an event to a holding channel, which takes ownership of the event.  Putting
-    // the event on our own channel allows us to manage when it is destroyed, keeping it alive
-    // until we know we are done with it.  Each recursive call of this function needs to have
-    // it's own holding channel, since a channel is a queue, not a stack.
-    //
-    // However, a recursive call into this function happens very rarely compared to the many
-    // times this function is called.  We don't want to create a holding channel for each time
-    // this function is called, only when it is called recursively.  Thus we have the instance
-    // variable d->holding_channel to use in the common case.  We keep track of recursive calls
-    // with d->loop_level.  If we are in a recursive call, then we create a new holding channel
-    // for this run.
-    int holding_channel = d->holding_channel;
-    if ((d->loop_level > 1) &&
-        Q_UNLIKELY(bps_channel_create(&holding_channel, 0) != BPS_SUCCESS)) {
-        qWarning("QEventDispatcherBlackberry: bps_channel_create failed");
-        holding_channel = -1;
-    }
-
-    // Convert timeout to milliseconds
-    int timeoutTotal = -1;
-    if (timeout)
-        timeoutTotal = timevalToMillisecs(*timeout);
-    int timeoutLeft = timeoutTotal;
-    timeval startTime = qt_gettime();
-
-    // This loop exists such that we can drain the bps event queue of all native events
-    // more efficiently than if we were to return control to Qt after each event. This
-    // is important for handling touch events which can come in rapidly.
-    forever {
-        // Only emit the awake() and aboutToBlock() signals in the second iteration. For the
-        // first iteration, the UNIX event dispatcher will have taken care of that already.
-        // Also native events are actually processed one loop iteration after they were
-        // retrieved with bps_get_event().
-
-        // Filtering the native event should happen between the awake() and aboutToBlock()
-        // signal emissions. The calls awake() - filterNativeEvent() - aboutToBlock() -
-        // bps_get_event() need not to be interrupted by a break or return statement.
-        if (eventCount > 0) {
-            if (event) {
-                emit awake();
-                filterEvent(static_cast<void*>(event));
-                emit aboutToBlock();
-
-                if (Q_LIKELY(holding_channel != -1)) {
-                    // We are now done with this BPS event.  Destroy it.
-                    destroyHeldBpsEvent(holding_channel);
-                }
-            }
-
-            // Update the timeout
-            // Clock source is monotonic, so we can recalculate how much timeout is left
-            if (timeoutTotal != -1) {
-                timeval t2 = qt_gettime();
-                timeoutLeft = timeoutTotal
-                              - (timevalToMillisecs(t2) - timevalToMillisecs(startTime));
-                if (timeoutLeft < 0)
-                    timeoutLeft = 0;
-            }
-
-            timeval tnext;
-            if (d->timerList.timerWait(tnext)) {
-                int timeoutNext = timevalToMillisecs(tnext);
-                if (timeoutNext < timeoutLeft || timeoutTotal == -1) {
-                    timeoutTotal = timeoutLeft = timeoutNext;
-                    startTime = qt_gettime();
-                }
-            }
-        }
-
-        event = 0;
-        {   // We need to increase loop level in this scope,
-            // because bps_get_event can also invoke callbacks
-            QScopedLoopLevelCounter loopLevelCounter(d->threadData);
-
-            // Wait for event or file to be ready
-            const int result = bps_get_event(&event, timeoutLeft);
-            if (Q_UNLIKELY(result != BPS_SUCCESS))
-                qWarning("QEventDispatcherBlackberry: bps_get_event failed");
-        }
-
-        if (!event)    // In case of !event, we break out of the loop to let Qt process the timers
-            break;     // (since timeout has expired) and socket notifiers that are now ready.
-
-        if (bps_event_get_domain(event) == bpsUnblockDomain) {
-            timeoutTotal = 0;   // in order to immediately drain the event queue of native events
-            event = 0;          // (especially touch move events) we don't break out here
-        } else {
-            // Move the event to our holding channel so we can manage when it is destroyed.
-            if (Q_LIKELY(holding_channel != 1) &&
-                Q_UNLIKELY(bps_channel_push_event(holding_channel, event) != BPS_SUCCESS)) {
-                qWarning("QEventDispatcherBlackberry: bps_channel_push_event failed");
-            }
-        }
-
-        ++eventCount;
-
-        // Make sure we are not trapped in this loop due to continuous native events
-        // also we cannot recalculate the timeout without a monotonic clock as the time may have changed
-        const unsigned int maximumEventCount = 12;
-        if (Q_UNLIKELY((eventCount > maximumEventCount && timeoutLeft == 0)
-                       || !QElapsedTimer::isMonotonic())) {
-            if (event) {
-                filterEvent(static_cast<void*>(event));
-
-                if (Q_LIKELY(holding_channel != -1)) {
-                    // We are now done with this BPS event.  Destroy it.
-                    destroyHeldBpsEvent(holding_channel);
-                }
-            }
-            break;
-        }
-    }
-
-    // If this was a recursive call into this function, a new holding channel was created for
-    // this run, so destroy it now.
-    if ((holding_channel != d->holding_channel) &&
-        Q_LIKELY(holding_channel != -1) &&
-        Q_UNLIKELY(bps_channel_destroy(holding_channel) != BPS_SUCCESS)) {
-        qWarning("QEventDispatcherBlackberry: bps_channel_destroy failed");
-    }
-
-    // the number of bits set in the file sets
-    return d->ioData->count;
-}
-
-void QEventDispatcherBlackberry::wakeUp()
-{
-    Q_D(QEventDispatcherBlackberry);
-    if (d->wakeUps.testAndSetAcquire(0, 1)) {
-        bps_event_t *event;
-        if (Q_LIKELY(bps_event_create(&event, bpsUnblockDomain, 0, 0, 0) == BPS_SUCCESS)) {
-            if (Q_LIKELY(bps_channel_push_event(d->bps_channel, event) == BPS_SUCCESS))
-                return;
-            else
-                bps_event_destroy(event);
-        }
-        qWarning("QEventDispatcherBlackberry: wakeUp failed");
-    }
-}
-
-int QEventDispatcherBlackberry::ioEvents(int fd)
-{
-    int io_events = 0;
-
-    Q_D(QEventDispatcherBlackberry);
-
-    if (FD_ISSET(fd, &d->sn_vec[0].enabled_fds))
-        io_events |= BPS_IO_INPUT;
-
-    if (FD_ISSET(fd, &d->sn_vec[1].enabled_fds))
-        io_events |= BPS_IO_OUTPUT;
-
-    if (FD_ISSET(fd, &d->sn_vec[2].enabled_fds))
-        io_events |= BPS_IO_EXCEPT;
-
-    return io_events;
-}
-
-QT_END_NAMESPACE
-#include "moc_qeventdispatcher_blackberry_p.h"
diff --git a/src/core/kernel/qeventdispatcher_blackberry_p.h b/src/core/kernel/qeventdispatcher_blackberry_p.h
deleted file mode 100644 (file)
index e710f83..0000000
+++ /dev/null
@@ -1,105 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Research In Motion <blackberry-qt@qnx.com>
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QEVENTDISPATCHER_BLACKBERRY_P_H
-#define QEVENTDISPATCHER_BLACKBERRY_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 "qeventdispatcher_unix_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QEventDispatcherBlackberryPrivate;
-
-class Q_CORE_EXPORT QEventDispatcherBlackberry : public QEventDispatcherUNIX
-{
-    Q_OBJECT
-    Q_DECLARE_PRIVATE(QEventDispatcherBlackberry)
-
-public:
-    explicit QEventDispatcherBlackberry(QObject *parent = 0);
-    ~QEventDispatcherBlackberry();
-
-    void registerSocketNotifier(QSocketNotifier *notifier);
-    void unregisterSocketNotifier(QSocketNotifier *notifier);
-
-    void wakeUp();
-
-protected:
-    QEventDispatcherBlackberry(QEventDispatcherBlackberryPrivate &dd, QObject *parent = 0);
-
-    int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
-               timeval *timeout);
-    int ioEvents(int fd);
-};
-
-struct bpsIOHandlerData;
-
-class Q_CORE_EXPORT QEventDispatcherBlackberryPrivate : public QEventDispatcherUNIXPrivate
-{
-    Q_DECLARE_PUBLIC(QEventDispatcherBlackberry)
-
-public:
-    QEventDispatcherBlackberryPrivate();
-    ~QEventDispatcherBlackberryPrivate();
-
-    int initThreadWakeUp();
-    int processThreadWakeUp(int nsel);
-
-    int bps_channel;
-    int holding_channel;
-    int loop_level;
-    QScopedPointer<bpsIOHandlerData> ioData;
-};
-
-QT_END_NAMESPACE
-
-#endif // QEVENTDISPATCHER_BLACKBERRY_P_H
diff --git a/src/core/kernel/qeventdispatcher_win.cpp b/src/core/kernel/qeventdispatcher_win.cpp
deleted file mode 100644 (file)
index 6db8b83..0000000
+++ /dev/null
@@ -1,1150 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qeventdispatcher_win_p.h"
-
-#include "qcoreapplication.h"
-#include "qhash.h"
-#include <qsystemlibrary_p.h>
-#include "qpair.h"
-#include "qset.h"
-#include "qsocketnotifier.h"
-#include "qvarlengtharray.h"
-#include "qwineventnotifier_p.h"
-
-#include "qabstracteventdispatcher_p.h"
-#include "qcoreapplication_p.h"
-#include <qthread_p.h>
-
-QT_BEGIN_NAMESPACE
-
-HINSTANCE qWinAppInst();
-extern uint qGlobalPostedEventsCount();
-
-#ifndef TIME_KILL_SYNCHRONOUS
-#  define TIME_KILL_SYNCHRONOUS 0x0100
-#endif
-
-#ifndef QS_RAWINPUT
-# ifdef Q_OS_WINCE
-#  define QS_RAWINPUT 0x0000
-# else
-#  define QS_RAWINPUT 0x0400
-# endif
-#endif
-
-#ifndef WM_TOUCH
-#  define WM_TOUCH 0x0240
-#endif
-#ifndef QT_NO_GESTURES
-#ifndef WM_GESTURE
-#  define WM_GESTURE 0x0119
-#endif
-#ifndef WM_GESTURENOTIFY
-#  define WM_GESTURENOTIFY 0x011A
-#endif
-#endif // QT_NO_GESTURES
-
-enum {
-    WM_QT_SOCKETNOTIFIER = WM_USER,
-    WM_QT_SENDPOSTEDEVENTS = WM_USER + 1,
-    SendPostedEventsWindowsTimerId = ~1u
-};
-
-#if defined(Q_OS_WINCE)
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <winsock.h>
-// Asynchronous Winsocks ------------------------------------------
-#ifndef QT_NO_THREAD
-#include <qthread.h>
-#include <qmap.h>
-#include <qmutex.h>
-QT_END_INCLUDE_NAMESPACE
-
-//#define QCE_ASYNC_DEBUG
-
-namespace {
-    class SocketAsyncHandler;
-
-    class SocketAsyncHandler : public QThread
-    {
-    public:
-        SocketAsyncHandler();
-        ~SocketAsyncHandler();
-        void run();
-        void select(SOCKET sock, HWND handle, unsigned int msg, long ev);
-        void removeSelect(SOCKET sock);
-        void safeRemove(SOCKET sock);
-    private:
-        struct SockInfo {
-            HWND handle;
-            unsigned int msg;
-            long ev;
-        };
-        QMap<SOCKET, SockInfo> sockets;
-        QMutex mutex;
-        QWaitCondition cond;
-        bool supposedToDie;
-    };
-
-    SocketAsyncHandler::SocketAsyncHandler()
-        : supposedToDie(false)
-    {
-    }
-
-    SocketAsyncHandler::~SocketAsyncHandler()
-    {
-        mutex.lock();
-        supposedToDie = true;
-        mutex.unlock();
-        cond.wakeOne();
-        wait();
-        while (sockets.size() > 0)
-            removeSelect(sockets.begin().key());
-    }
-
-    void SocketAsyncHandler::removeSelect(SOCKET sock)
-    {
-        if (!sockets.contains(sock))
-            return;
-        sockets.remove(sock);
-        return;
-    }
-
-    void SocketAsyncHandler::safeRemove(SOCKET sock)
-    {
-        QMutexLocker locker(&mutex);
-        removeSelect(sock);
-    }
-
-    void SocketAsyncHandler::select(SOCKET sock, HWND handle, unsigned int msg, long ev)
-    {
-        QMutexLocker locker(&mutex);
-
-        if (sockets.contains(sock))
-            sockets.remove(sock);
-
-        SockInfo info;
-        info.handle = handle;
-        info.msg = msg;
-        info.ev = ev;
-        sockets.insert(sock, info);
-        cond.wakeOne();
-    }
-
-    void SocketAsyncHandler::run()
-    {
-        do {
-            mutex.lock();
-
-            while (!supposedToDie && sockets.isEmpty()) {
-                cond.wait(&mutex);
-            }
-
-            if (supposedToDie) {
-                mutex.unlock();
-                break;
-            }
-
-            // Copy current items to reduce lock time
-            // and to be able to use SendMessage
-            QMap<SOCKET, SockInfo> currentSockets = sockets;
-            mutex.unlock();
-
-            fd_set readS, writeS, exS;
-            FD_ZERO(&readS);
-            FD_ZERO(&writeS);
-            FD_ZERO(&exS);
-
-            int maxFd = 0;
-
-            for (QMap<SOCKET, SockInfo>::iterator it = currentSockets.begin(); it != currentSockets.end(); ++it) {
-                const SockInfo &info = it.value();
-                int socket = it.key();
-                maxFd = qMax(maxFd, socket);
-
-                if ((info.ev & FD_READ) || (info.ev & FD_CLOSE) || (info.ev & FD_ACCEPT))
-                    FD_SET(socket, &readS);
-                if ((info.ev & FD_WRITE)|| (info.ev & FD_CONNECT))
-                    FD_SET(socket, &writeS);
-                if (info.ev & FD_OOB)
-                    FD_SET(socket, &exS);
-            }
-
-            timeval timeout;
-            timeout.tv_sec = 0;
-            timeout.tv_usec = 50000;
-            int result = ::select(maxFd + 1, &readS, &writeS, &exS, &timeout);
-            if (result > 0) {
-                HWND handle;
-                unsigned int tmpMsg;
-                SOCKET sock;
-                HRESULT ret;
-                for (QMap<SOCKET, SockInfo>::const_iterator it = currentSockets.constBegin();
-                    it != currentSockets.constEnd(); ++it) {
-                        handle = (*it).handle;
-                        tmpMsg = (*it).msg;
-                        sock = it.key();
-                        if (FD_ISSET(sock, &readS))
-                            ret = SendMessage(handle, tmpMsg, sock, FD_READ);
-
-                        if (FD_ISSET(sock, &writeS))
-                            ret = SendMessage(handle, tmpMsg, sock, FD_WRITE);
-
-                        if (FD_ISSET(sock, &exS))
-                            ret = SendMessage(handle, tmpMsg, sock, FD_OOB);
-                }
-            }
-
-#ifdef QCE_ASYNC_DEBUG
-            else if (result == 0) { //timeout
-                qDebug("    WSAAsync select timeout");
-            } else if (result < 0) { // SocketError
-                // This might happen because of two reasons
-                // 1. We already closed a socket in between the copy and the select
-                //    and thus select() returns an error
-                // 2. Something is really wrong, then
-                //    ### Loop on all descriptors, try to select and remove the
-                //    ### broken one.
-                qWarning("WSAAsync select error %d", WSAGetLastError());
-            }
-#endif
-        } while(true);
-    }
-} // namespace
-
-Q_GLOBAL_STATIC(SocketAsyncHandler, qt_async_handler)
-
-int WSAAsyncSelect(SOCKET sock, HWND handle, unsigned int msg, long ev)
-{
-    if (sock == 0 || handle == 0 || handle == INVALID_HANDLE_VALUE) {
-        WSASetLastError(WSAEINVAL);
-        return SOCKET_ERROR;
-    }
-
-    if (msg == 0 && ev == 0)
-        qt_async_handler()->safeRemove(sock);
-    else
-        qt_async_handler()->select(sock, handle, msg, ev);
-
-    qt_async_handler()->start(QThread::LowPriority);
-    WSASetLastError(0);
-    return 0;
-}
-#else // QT_NO_THREAD
-int WSAAsyncSelect(SOCKET, HWND, unsigned int, long)
-{
-    return SOCKET_ERROR;
-}
-#endif
-#endif // Q_OS_WINCE
-
-class QEventDispatcherWin32Private;
-
-struct QSockNot {
-    QSocketNotifier *obj;
-    int fd;
-};
-typedef QHash<int, QSockNot *> QSNDict;
-
-struct WinTimerInfo {                           // internal timer info
-    QObject *dispatcher;
-    int timerId;
-    int interval;
-    QObject *obj;                               // - object to receive events
-    bool inTimerEvent;
-    int fastTimerId;
-};
-
-class QZeroTimerEvent : public QTimerEvent
-{
-public:
-    inline QZeroTimerEvent(int timerId)
-        : QTimerEvent(timerId)
-    { t = QEvent::ZeroTimerEvent; }
-};
-
-typedef QList<WinTimerInfo*>  WinTimerVec;      // vector of TimerInfo structs
-typedef QHash<int, WinTimerInfo*> WinTimerDict; // fast dict of timers
-
-#if !defined(DWORD_PTR) && !defined(Q_WS_WIN64)
-#define DWORD_PTR DWORD
-#endif
-
-typedef MMRESULT(WINAPI *ptimeSetEvent)(UINT, UINT, LPTIMECALLBACK, DWORD_PTR, UINT);
-typedef MMRESULT(WINAPI *ptimeKillEvent)(UINT);
-
-static ptimeSetEvent qtimeSetEvent = 0;
-static ptimeKillEvent qtimeKillEvent = 0;
-
-LRESULT QT_WIN_CALLBACK qt_internal_proc(HWND hwnd, UINT message, WPARAM wp, LPARAM lp);
-
-static void resolveTimerAPI()
-{
-    static bool triedResolve = false;
-    if (!triedResolve) {
-#ifdef Q_OS_WINCE
-        QSystemLibrary library(QLatin1String("Mmtimer"));
-#else
-        QSystemLibrary library(QLatin1String("winmm"));
-#endif
-        if (library.load()) {
-            qtimeSetEvent = (ptimeSetEvent)library.resolve("timeSetEvent");
-            qtimeKillEvent = (ptimeKillEvent)library.resolve("timeKillEvent");
-        }
-
-        triedResolve = true;
-    }
-}
-
-
-class QEventDispatcherWin32Private : public QAbstractEventDispatcherPrivate
-{
-    Q_DECLARE_PUBLIC(QEventDispatcherWin32)
-public:
-    QEventDispatcherWin32Private();
-    ~QEventDispatcherWin32Private();
-
-    DWORD threadId;
-
-    bool interrupt;
-
-    // internal window handle used for socketnotifiers/timers/etc
-    HWND internalHwnd;
-    HHOOK getMessageHook;
-
-    // for controlling when to send posted events
-    QAtomicInt serialNumber;
-    int lastSerialNumber, sendPostedEventsWindowsTimerId;
-    QAtomicInt wakeUps;
-
-    // timers
-    WinTimerVec timerVec;
-    WinTimerDict timerDict;
-    void registerTimer(WinTimerInfo *t);
-    void unregisterTimer(WinTimerInfo *t, bool closingDown = false);
-    void sendTimerEvent(int timerId);
-
-    // socket notifiers
-    QSNDict sn_read;
-    QSNDict sn_write;
-    QSNDict sn_except;
-    void doWsaAsyncSelect(int socket);
-
-    QList<QWinEventNotifier *> winEventNotifierList;
-    void activateEventNotifier(QWinEventNotifier * wen);
-
-    QList<MSG> queuedUserInputEvents;
-    QList<MSG> queuedSocketEvents;
-};
-
-QEventDispatcherWin32Private::QEventDispatcherWin32Private()
-    : threadId(GetCurrentThreadId()), interrupt(false), internalHwnd(0), getMessageHook(0),
-      serialNumber(0), lastSerialNumber(0), sendPostedEventsWindowsTimerId(0), wakeUps(0)
-{
-    resolveTimerAPI();
-}
-
-QEventDispatcherWin32Private::~QEventDispatcherWin32Private()
-{
-    if (internalHwnd)
-        DestroyWindow(internalHwnd);
-    QString className = QLatin1String("QEventDispatcherWin32_Internal_Widget") + QString::number(quintptr(qt_internal_proc));
-    UnregisterClass((wchar_t*)className.utf16(), qWinAppInst());
-}
-
-void QEventDispatcherWin32Private::activateEventNotifier(QWinEventNotifier * wen)
-{
-    QEvent event(QEvent::WinEventAct);
-    QCoreApplication::sendEvent(wen, &event);
-}
-
-// This function is called by a workerthread
-void WINAPI QT_WIN_CALLBACK qt_fast_timer_proc(uint timerId, uint /*reserved*/, DWORD_PTR user, DWORD_PTR /*reserved*/, DWORD_PTR /*reserved*/)
-{
-    if (!timerId) // sanity check
-        return;
-    WinTimerInfo *t = (WinTimerInfo*)user;
-    Q_ASSERT(t);
-    QCoreApplication::postEvent(t->dispatcher, new QTimerEvent(t->timerId));
-}
-
-LRESULT QT_WIN_CALLBACK qt_internal_proc(HWND hwnd, UINT message, WPARAM wp, LPARAM lp)
-{
-    if (message == WM_NCCREATE)
-        return true;
-
-    MSG msg;
-    msg.hwnd = hwnd;
-    msg.message = message;
-    msg.wParam = wp;
-    msg.lParam = lp;
-    QCoreApplication *app = QCoreApplication::instance();
-    long result;
-    if (!app) {
-        if (message == WM_TIMER)
-            KillTimer(hwnd, wp);
-        return 0;
-    } else if (app->filterEvent(&msg, &result)) {
-        return result;
-    }
-
-#ifdef GWLP_USERDATA
-    QEventDispatcherWin32 *q = (QEventDispatcherWin32 *) GetWindowLongPtr(hwnd, GWLP_USERDATA);
-#else
-    QEventDispatcherWin32 *q = (QEventDispatcherWin32 *) GetWindowLong(hwnd, GWL_USERDATA);
-#endif
-    QEventDispatcherWin32Private *d = 0;
-    if (q != 0)
-        d = q->d_func();
-
-    if (message == WM_QT_SOCKETNOTIFIER) {
-        // socket notifier message
-        int type = -1;
-        switch (WSAGETSELECTEVENT(lp)) {
-        case FD_READ:
-        case FD_CLOSE:
-        case FD_ACCEPT:
-            type = 0;
-            break;
-        case FD_WRITE:
-        case FD_CONNECT:
-            type = 1;
-            break;
-        case FD_OOB:
-            type = 2;
-            break;
-        }
-        if (type >= 0) {
-            Q_ASSERT(d != 0);
-            QSNDict *sn_vec[3] = { &d->sn_read, &d->sn_write, &d->sn_except };
-            QSNDict *dict = sn_vec[type];
-
-            QSockNot *sn = dict ? dict->value(wp) : 0;
-            if (sn) {
-                QEvent event(QEvent::SockAct);
-                QCoreApplication::sendEvent(sn->obj, &event);
-            }
-        }
-        return 0;
-    } else if (message == WM_QT_SENDPOSTEDEVENTS
-               // we also use a Windows timer to send posted events when the message queue is full
-               || (message == WM_TIMER
-                   && d->sendPostedEventsWindowsTimerId != 0
-                   && wp == (uint)d->sendPostedEventsWindowsTimerId)) {
-        int localSerialNumber = d->serialNumber;
-        if (localSerialNumber != d->lastSerialNumber) {
-            d->lastSerialNumber = localSerialNumber;
-            QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
-        }
-        return 0;
-    } else if (message == WM_TIMER) {
-        Q_ASSERT(d != 0);
-        d->sendTimerEvent(wp);
-        return 0;
-    }
-
-    return DefWindowProc(hwnd, message, wp, lp);
-}
-
-static inline UINT inputTimerMask()
-{
-    UINT result = QS_TIMER | QS_INPUT | QS_RAWINPUT;
-    // QTBUG 28513, QTBUG-29097, QTBUG-29435: QS_TOUCH, QS_POINTER became part of
-    // QS_INPUT in Windows Kit 8. They should not be used when running on pre-Windows 8.
-#if WINVER > 0x0601
-    if (QSysInfo::WindowsVersion < QSysInfo::WV_WINDOWS8)
-        result &= ~(QS_TOUCH | QS_POINTER);
-#endif // WINVER > 0x0601
-    return result;
-}
-
-LRESULT QT_WIN_CALLBACK qt_GetMessageHook(int code, WPARAM wp, LPARAM lp)
-{
-    if (wp == PM_REMOVE) {
-        QEventDispatcherWin32 *q = qobject_cast<QEventDispatcherWin32 *>(QAbstractEventDispatcher::instance());
-        Q_ASSERT(q != 0);
-        if (q) {
-            MSG *msg = (MSG *) lp;
-            QEventDispatcherWin32Private *d = q->d_func();
-            int localSerialNumber = d->serialNumber;
-            static const UINT mask = inputTimerMask();
-            if (HIWORD(GetQueueStatus(mask)) == 0) {
-                // no more input or timer events in the message queue, we can allow posted events to be sent normally now
-                if (d->sendPostedEventsWindowsTimerId != 0) {
-                    // stop the timer to send posted events, since we now allow the WM_QT_SENDPOSTEDEVENTS message
-                    KillTimer(d->internalHwnd, d->sendPostedEventsWindowsTimerId);
-                    d->sendPostedEventsWindowsTimerId = 0;
-                }
-                (void) d->wakeUps.fetchAndStoreRelease(0);
-                if (localSerialNumber != d->lastSerialNumber
-                    // if this message IS the one that triggers sendPostedEvents(), no need to post it again
-                    && (msg->hwnd != d->internalHwnd
-                        || msg->message != WM_QT_SENDPOSTEDEVENTS)) {
-                    PostMessage(d->internalHwnd, WM_QT_SENDPOSTEDEVENTS, 0, 0);
-                }
-            } else if (d->sendPostedEventsWindowsTimerId == 0
-                       && localSerialNumber != d->lastSerialNumber) {
-                // start a special timer to continue delivering posted events while
-                // there are still input and timer messages in the message queue
-                d->sendPostedEventsWindowsTimerId = SetTimer(d->internalHwnd,
-                                                             SendPostedEventsWindowsTimerId,
-                                                             0, // we specify zero, but Windows uses USER_TIMER_MINIMUM
-                                                             NULL);
-                // we don't check the return value of SetTimer()... if creating the timer failed, there's little
-                // we can do. we just have to accept that posted events will be starved
-            }
-        }
-    }
-#ifdef Q_OS_WINCE
-    Q_UNUSED(code);
-    return 0;
-#else
-    return CallNextHookEx(0, code, wp, lp);
-#endif
-}
-
-static HWND qt_create_internal_window(const QEventDispatcherWin32 *eventDispatcher)
-{
-    // make sure that multiple Qt's can coexist in the same process
-    QString className = QLatin1String("QEventDispatcherWin32_Internal_Widget") + QString::number(quintptr(qt_internal_proc));
-
-    WNDCLASS wc;
-    wc.style = 0;
-    wc.lpfnWndProc = qt_internal_proc;
-    wc.cbClsExtra = 0;
-    wc.cbWndExtra = 0;
-    wc.hInstance = qWinAppInst();
-    wc.hIcon = 0;
-    wc.hCursor = 0;
-    wc.hbrBackground = 0;
-    wc.lpszMenuName = NULL;
-    wc.lpszClassName = reinterpret_cast<const wchar_t *> (className.utf16());
-
-    RegisterClass(&wc);
-    HWND wnd = CreateWindow(wc.lpszClassName,  // classname
-                            wc.lpszClassName,  // window name
-                            0,                 // style
-                            0, 0, 0, 0,        // geometry
-                            0,                 // parent
-                            0,                 // menu handle
-                            qWinAppInst(),     // application
-                            0);                // windows creation data.
-
-    if (!wnd) {
-        qWarning("QEventDispatcher: Failed to create QEventDispatcherWin32 internal window: %d\n", (int)GetLastError());
-    }
-
-#ifdef GWLP_USERDATA
-    SetWindowLongPtr(wnd, GWLP_USERDATA, (LONG_PTR)eventDispatcher);
-#else
-    SetWindowLong(wnd, GWL_USERDATA, (LONG)eventDispatcher);
-#endif
-
-    return wnd;
-}
-
-void QEventDispatcherWin32Private::registerTimer(WinTimerInfo *t)
-{
-    Q_ASSERT(internalHwnd);
-
-    Q_Q(QEventDispatcherWin32);
-
-    int ok = 0;
-    if (t->interval > 20 || !t->interval || !qtimeSetEvent) {
-        ok = 1;
-        if (!t->interval)  // optimization for single-shot-zero-timer
-            QCoreApplication::postEvent(q, new QZeroTimerEvent(t->timerId));
-        else
-            ok = SetTimer(internalHwnd, t->timerId, (uint) t->interval, 0);
-    } else {
-        ok = t->fastTimerId = qtimeSetEvent(t->interval, 1, qt_fast_timer_proc, (DWORD_PTR)t,
-                                            TIME_CALLBACK_FUNCTION | TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);
-        if (ok == 0) { // fall back to normal timer if no more multimedia timers available
-            ok = SetTimer(internalHwnd, t->timerId, (uint) t->interval, 0);
-        }
-    }
-
-    if (ok == 0)
-        qErrnoWarning("QEventDispatcherWin32::registerTimer: Failed to create a timer");
-}
-
-void QEventDispatcherWin32Private::unregisterTimer(WinTimerInfo *t, bool closingDown)
-{
-    // mark timer as unused
-    if (!QObjectPrivate::get(t->obj)->inThreadChangeEvent && !closingDown)
-        QAbstractEventDispatcherPrivate::releaseTimerId(t->timerId);
-
-    if (t->interval == 0) {
-        QCoreApplicationPrivate::removePostedTimerEvent(t->dispatcher, t->timerId);
-    } else if (t->fastTimerId != 0) {
-        qtimeKillEvent(t->fastTimerId);
-        QCoreApplicationPrivate::removePostedTimerEvent(t->dispatcher, t->timerId);
-    } else if (internalHwnd) {
-        KillTimer(internalHwnd, t->timerId);
-    }
-    delete t;
-}
-
-void QEventDispatcherWin32Private::sendTimerEvent(int timerId)
-{
-    WinTimerInfo *t = timerDict.value(timerId);
-    if (t && !t->inTimerEvent) {
-        // send event, but don't allow it to recurse
-        t->inTimerEvent = true;
-
-        QTimerEvent e(t->timerId);
-        QCoreApplication::sendEvent(t->obj, &e);
-
-        // timer could have been removed
-        t = timerDict.value(timerId);
-        if (t) {
-            t->inTimerEvent = false;
-        }
-    }
-}
-
-void QEventDispatcherWin32Private::doWsaAsyncSelect(int socket)
-{
-    Q_ASSERT(internalHwnd);
-    int sn_event = 0;
-    if (sn_read.contains(socket))
-        sn_event |= FD_READ | FD_CLOSE | FD_ACCEPT;
-    if (sn_write.contains(socket))
-        sn_event |= FD_WRITE | FD_CONNECT;
-    if (sn_except.contains(socket))
-        sn_event |= FD_OOB;
-    // BoundsChecker may emit a warning for WSAAsyncSelect when sn_event == 0
-    // This is a BoundsChecker bug and not a Qt bug
-    WSAAsyncSelect(socket, internalHwnd, sn_event ? unsigned(WM_QT_SOCKETNOTIFIER) : unsigned(0), sn_event);
-}
-
-void QEventDispatcherWin32::createInternalHwnd()
-{
-    Q_D(QEventDispatcherWin32);
-
-    Q_ASSERT(!d->internalHwnd);
-    if (d->internalHwnd)
-        return;
-    d->internalHwnd = qt_create_internal_window(this);
-
-#ifndef Q_OS_WINCE
-    // setup GetMessage hook needed to drive our posted events
-    d->getMessageHook = SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC) qt_GetMessageHook, NULL, GetCurrentThreadId());
-    if (!d->getMessageHook) {
-        qFatal("Qt: INTERNALL ERROR: failed to install GetMessage hook");
-    }
-#endif
-
-    // register all socket notifiers
-    QList<int> sockets = (d->sn_read.keys().toSet()
-                          + d->sn_write.keys().toSet()
-                          + d->sn_except.keys().toSet()).toList();
-    for (int i = 0; i < sockets.count(); ++i)
-        d->doWsaAsyncSelect(sockets.at(i));
-
-    // start all normal timers
-    for (int i = 0; i < d->timerVec.count(); ++i)
-        d->registerTimer(d->timerVec.at(i));
-
-    // trigger a call to sendPostedEvents()
-    wakeUp();
-}
-
-QEventDispatcherWin32::QEventDispatcherWin32(QObject *parent)
-    : QAbstractEventDispatcher(*new QEventDispatcherWin32Private, parent)
-{
-}
-
-QEventDispatcherWin32::~QEventDispatcherWin32()
-{
-}
-
-bool QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
-{
-    Q_D(QEventDispatcherWin32);
-
-    if (!d->internalHwnd)
-        createInternalHwnd();
-
-    d->interrupt = false;
-    emit awake();
-
-    bool canWait;
-    bool retVal = false;
-    bool seenWM_QT_SENDPOSTEDEVENTS = false;
-    bool needWM_QT_SENDPOSTEDEVENTS = false;
-    do {
-        DWORD waitRet = 0;
-        HANDLE pHandles[MAXIMUM_WAIT_OBJECTS - 1];
-        QVarLengthArray<MSG> processedTimers;
-        while (!d->interrupt) {
-            DWORD nCount = d->winEventNotifierList.count();
-            Q_ASSERT(nCount < MAXIMUM_WAIT_OBJECTS - 1);
-
-            MSG msg;
-            bool haveMessage;
-
-            if (!(flags & QEventLoop::ExcludeUserInputEvents) && !d->queuedUserInputEvents.isEmpty()) {
-                // process queued user input events
-                haveMessage = true;
-                msg = d->queuedUserInputEvents.takeFirst();
-            } else if(!(flags & QEventLoop::ExcludeSocketNotifiers) && !d->queuedSocketEvents.isEmpty()) {
-                // process queued socket events
-                haveMessage = true;
-                msg = d->queuedSocketEvents.takeFirst();
-            } else {
-                haveMessage = PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
-                if (haveMessage && (flags & QEventLoop::ExcludeUserInputEvents)
-                    && ((msg.message >= WM_KEYFIRST
-                         && msg.message <= WM_KEYLAST)
-                        || (msg.message >= WM_MOUSEFIRST
-                            && msg.message <= WM_MOUSELAST)
-                        || msg.message == WM_MOUSEWHEEL
-                        || msg.message == WM_MOUSEHWHEEL
-                        || msg.message == WM_TOUCH
-#ifndef QT_NO_GESTURES
-                        || msg.message == WM_GESTURE
-                        || msg.message == WM_GESTURENOTIFY
-#endif
-                        || msg.message == WM_CLOSE)) {
-                    // queue user input events for later processing
-                    haveMessage = false;
-                    d->queuedUserInputEvents.append(msg);
-                }
-                if (haveMessage && (flags & QEventLoop::ExcludeSocketNotifiers)
-                    && (msg.message == WM_QT_SOCKETNOTIFIER && msg.hwnd == d->internalHwnd)) {
-                    // queue socket events for later processing
-                    haveMessage = false;
-                    d->queuedSocketEvents.append(msg);
-                }
-            }
-            if (!haveMessage) {
-                // no message - check for signalled objects
-                for (int i=0; i<(int)nCount; i++)
-                    pHandles[i] = d->winEventNotifierList.at(i)->handle();
-                waitRet = MsgWaitForMultipleObjectsEx(nCount, pHandles, 0, QS_ALLINPUT, MWMO_ALERTABLE);
-                if ((haveMessage = (waitRet == WAIT_OBJECT_0 + nCount))) {
-                    // a new message has arrived, process it
-                    continue;
-                }
-            }
-            if (haveMessage) {
-#ifdef Q_OS_WINCE
-                // WinCE doesn't support hooks at all, so we have to call this by hand :(
-                (void) qt_GetMessageHook(0, PM_REMOVE, (LPARAM) &msg);
-#endif
-
-                if (d->internalHwnd == msg.hwnd && msg.message == WM_QT_SENDPOSTEDEVENTS) {
-                    if (seenWM_QT_SENDPOSTEDEVENTS) {
-                        // when calling processEvents() "manually", we only want to send posted
-                        // events once
-                        needWM_QT_SENDPOSTEDEVENTS = true;
-                        continue;
-                    }
-                    seenWM_QT_SENDPOSTEDEVENTS = true;
-                } else if (msg.message == WM_TIMER) {
-                    // avoid live-lock by keeping track of the timers we've already sent
-                    bool found = false;
-                    for (int i = 0; !found && i < processedTimers.count(); ++i) {
-                        const MSG processed = processedTimers.constData()[i];
-                        found = (processed.wParam == msg.wParam && processed.hwnd == msg.hwnd && processed.lParam == msg.lParam);
-                    }
-                    if (found)
-                        continue;
-                    processedTimers.append(msg);
-                } else if (msg.message == WM_QUIT) {
-                    if (QCoreApplication::instance())
-                        QCoreApplication::instance()->quit();
-                    return false;
-                }
-
-                if (!filterEvent(&msg)) {
-                    TranslateMessage(&msg);
-                    DispatchMessage(&msg);
-                }
-            } else if (waitRet < WAIT_OBJECT_0 + nCount) {
-                d->activateEventNotifier(d->winEventNotifierList.at(waitRet - WAIT_OBJECT_0));
-            } else {
-                // nothing todo so break
-                break;
-            }
-            retVal = true;
-        }
-
-        // still nothing - wait for message or signalled objects
-        canWait = (!retVal
-                   && !d->interrupt
-                   && (flags & QEventLoop::WaitForMoreEvents));
-        if (canWait) {
-            DWORD nCount = d->winEventNotifierList.count();
-            Q_ASSERT(nCount < MAXIMUM_WAIT_OBJECTS - 1);
-            for (int i=0; i<(int)nCount; i++)
-                pHandles[i] = d->winEventNotifierList.at(i)->handle();
-
-            emit aboutToBlock();
-            waitRet = MsgWaitForMultipleObjectsEx(nCount, pHandles, INFINITE, QS_ALLINPUT, MWMO_ALERTABLE | MWMO_INPUTAVAILABLE);
-            emit awake();
-            if (waitRet < WAIT_OBJECT_0 + nCount) {
-                d->activateEventNotifier(d->winEventNotifierList.at(waitRet - WAIT_OBJECT_0));
-                retVal = true;
-            }
-        }
-    } while (canWait);
-
-    if (!seenWM_QT_SENDPOSTEDEVENTS && (flags & QEventLoop::EventLoopExec) == 0) {
-        // when called "manually", always send posted events
-        QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
-    }
-
-    if (needWM_QT_SENDPOSTEDEVENTS)
-        PostMessage(d->internalHwnd, WM_QT_SENDPOSTEDEVENTS, 0, 0);
-
-    return retVal;
-}
-
-bool QEventDispatcherWin32::hasPendingEvents()
-{
-    MSG msg;
-    return qGlobalPostedEventsCount() || PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
-}
-
-void QEventDispatcherWin32::registerSocketNotifier(QSocketNotifier *notifier)
-{
-    Q_ASSERT(notifier);
-    int sockfd = notifier->socket();
-    int type = notifier->type();
-#ifndef QT_NO_DEBUG
-    if (sockfd < 0) {
-        qWarning("QSocketNotifier: Internal error");
-        return;
-    } else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
-        qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
-        return;
-    }
-#endif
-
-    Q_D(QEventDispatcherWin32);
-    QSNDict *sn_vec[3] = { &d->sn_read, &d->sn_write, &d->sn_except };
-    QSNDict *dict = sn_vec[type];
-
-    if (QCoreApplication::closingDown()) // ### d->exitloop?
-        return; // after sn_cleanup, don't reinitialize.
-
-    if (dict->contains(sockfd)) {
-        const char *t[] = { "Read", "Write", "Exception" };
-    /* Variable "socket" below is a function pointer. */
-        qWarning("QSocketNotifier: Multiple socket notifiers for "
-                 "same socket %d and type %s", sockfd, t[type]);
-    }
-
-    QSockNot *sn = new QSockNot;
-    sn->obj = notifier;
-    sn->fd  = sockfd;
-    dict->insert(sn->fd, sn);
-
-    if (d->internalHwnd)
-        d->doWsaAsyncSelect(sockfd);
-}
-
-void QEventDispatcherWin32::unregisterSocketNotifier(QSocketNotifier *notifier)
-{
-    Q_ASSERT(notifier);
-    int sockfd = notifier->socket();
-    int type = notifier->type();
-#ifndef QT_NO_DEBUG
-    if (sockfd < 0) {
-        qWarning("QSocketNotifier: Internal error");
-        return;
-    } else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
-        qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
-        return;
-    }
-#endif
-
-    Q_D(QEventDispatcherWin32);
-    QSNDict *sn_vec[3] = { &d->sn_read, &d->sn_write, &d->sn_except };
-    QSNDict *dict = sn_vec[type];
-    QSockNot *sn = dict->value(sockfd);
-    if (!sn)
-        return;
-
-    dict->remove(sockfd);
-    delete sn;
-
-    if (d->internalHwnd)
-        d->doWsaAsyncSelect(sockfd);
-}
-
-void QEventDispatcherWin32::registerTimer(int timerId, int interval, QObject *object)
-{
-    if (timerId < 1 || interval < 0 || !object) {
-        qWarning("QEventDispatcherWin32::registerTimer: invalid arguments");
-        return;
-    } else if (object->thread() != thread() || thread() != QThread::currentThread()) {
-        qWarning("QObject::startTimer: timers cannot be started from another thread");
-        return;
-    }
-
-    Q_D(QEventDispatcherWin32);
-
-    register WinTimerInfo *t = new WinTimerInfo;
-    t->dispatcher = this;
-    t->timerId  = timerId;
-    t->interval = interval;
-    t->obj  = object;
-    t->inTimerEvent = false;
-    t->fastTimerId = 0;
-
-    if (d->internalHwnd)
-        d->registerTimer(t);
-
-    d->timerVec.append(t);                      // store in timer vector
-    d->timerDict.insert(t->timerId, t);          // store timers in dict
-}
-
-bool QEventDispatcherWin32::unregisterTimer(int timerId)
-{
-    if (timerId < 1) {
-        qWarning("QEventDispatcherWin32::unregisterTimer: invalid argument");
-        return false;
-    }
-    QThread *currentThread = QThread::currentThread();
-    if (thread() != currentThread) {
-        qWarning("QObject::killTimer: timers cannot be stopped from another thread");
-        return false;
-    }
-
-    Q_D(QEventDispatcherWin32);
-    if (d->timerVec.isEmpty() || timerId <= 0)
-        return false;
-
-    WinTimerInfo *t = d->timerDict.value(timerId);
-    if (!t)
-        return false;
-
-    d->timerDict.remove(t->timerId);
-    d->timerVec.removeAll(t);
-    d->unregisterTimer(t);
-    return true;
-}
-
-bool QEventDispatcherWin32::unregisterTimers(QObject *object)
-{
-    if (!object) {
-        qWarning("QEventDispatcherWin32::unregisterTimers: invalid argument");
-        return false;
-    }
-    QThread *currentThread = QThread::currentThread();
-    if (object->thread() != thread() || thread() != currentThread) {
-        qWarning("QObject::killTimers: timers cannot be stopped from another thread");
-        return false;
-    }
-
-    Q_D(QEventDispatcherWin32);
-    if (d->timerVec.isEmpty())
-        return false;
-    register WinTimerInfo *t;
-    for (int i=0; i<d->timerVec.size(); i++) {
-        t = d->timerVec.at(i);
-        if (t && t->obj == object) {                // object found
-            d->timerDict.remove(t->timerId);
-            d->timerVec.removeAt(i);
-            d->unregisterTimer(t);
-            --i;
-        }
-    }
-    return true;
-}
-
-QList<QEventDispatcherWin32::TimerInfo>
-QEventDispatcherWin32::registeredTimers(QObject *object) const
-{
-    if (!object) {
-        qWarning("QEventDispatcherWin32:registeredTimers: invalid argument");
-        return QList<TimerInfo>();
-    }
-
-    Q_D(const QEventDispatcherWin32);
-    QList<TimerInfo> list;
-    for (int i = 0; i < d->timerVec.size(); ++i) {
-        const WinTimerInfo *t = d->timerVec.at(i);
-        if (t && t->obj == object)
-            list << TimerInfo(t->timerId, t->interval);
-    }
-    return list;
-}
-
-bool QEventDispatcherWin32::registerEventNotifier(QWinEventNotifier *notifier)
-{
-    if (!notifier) {
-        qWarning("QWinEventNotifier: Internal error");
-        return false;
-    } else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
-        qWarning("QWinEventNotifier: event notifiers cannot be enabled from another thread");
-        return false;
-    }
-
-    Q_D(QEventDispatcherWin32);
-
-    if (d->winEventNotifierList.contains(notifier))
-        return true;
-
-    if (d->winEventNotifierList.count() >= MAXIMUM_WAIT_OBJECTS - 2) {
-        qWarning("QWinEventNotifier: Cannot have more than %d enabled at one time", MAXIMUM_WAIT_OBJECTS - 2);
-        return false;
-    }
-    d->winEventNotifierList.append(notifier);
-    return true;
-}
-
-void QEventDispatcherWin32::unregisterEventNotifier(QWinEventNotifier *notifier)
-{
-    if (!notifier) {
-        qWarning("QWinEventNotifier: Internal error");
-        return;
-    } else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
-        qWarning("QWinEventNotifier: event notifiers cannot be disabled from another thread");
-        return;
-    }
-
-    Q_D(QEventDispatcherWin32);
-
-    int i = d->winEventNotifierList.indexOf(notifier);
-    if (i != -1)
-        d->winEventNotifierList.takeAt(i);
-}
-
-void QEventDispatcherWin32::activateEventNotifiers()
-{
-    Q_D(QEventDispatcherWin32);
-    //### this could break if events are removed/added in the activation
-    for (int i=0; i<d->winEventNotifierList.count(); i++) {
-#if !defined(Q_OS_WINCE)
-        if (WaitForSingleObjectEx(d->winEventNotifierList.at(i)->handle(), 0, TRUE) == WAIT_OBJECT_0)
-            d->activateEventNotifier(d->winEventNotifierList.at(i));
-#else
-        if (WaitForSingleObject(d->winEventNotifierList.at(i)->handle(), 0) == WAIT_OBJECT_0)
-            d->activateEventNotifier(d->winEventNotifierList.at(i));
-#endif
-    }
-}
-
-void QEventDispatcherWin32::wakeUp()
-{
-    Q_D(QEventDispatcherWin32);
-    d->serialNumber.ref();
-    if (d->internalHwnd && d->wakeUps.testAndSetAcquire(0, 1)) {
-        // post a WM_QT_SENDPOSTEDEVENTS to this thread if there isn't one already pending
-        PostMessage(d->internalHwnd, WM_QT_SENDPOSTEDEVENTS, 0, 0);
-    }
-}
-
-void QEventDispatcherWin32::interrupt()
-{
-    Q_D(QEventDispatcherWin32);
-    d->interrupt = true;
-    wakeUp();
-}
-
-void QEventDispatcherWin32::flush()
-{ }
-
-void QEventDispatcherWin32::startingUp()
-{ }
-
-void QEventDispatcherWin32::closingDown()
-{
-    Q_D(QEventDispatcherWin32);
-
-    // clean up any socketnotifiers
-    while (!d->sn_read.isEmpty())
-        unregisterSocketNotifier((*(d->sn_read.begin()))->obj);
-    while (!d->sn_write.isEmpty())
-        unregisterSocketNotifier((*(d->sn_write.begin()))->obj);
-    while (!d->sn_except.isEmpty())
-        unregisterSocketNotifier((*(d->sn_except.begin()))->obj);
-
-    // clean up any timers
-    for (int i = 0; i < d->timerVec.count(); ++i)
-        d->unregisterTimer(d->timerVec.at(i), true);
-    d->timerVec.clear();
-    d->timerDict.clear();
-
-#ifndef Q_OS_WINCE
-    if (d->getMessageHook)
-        UnhookWindowsHookEx(d->getMessageHook);
-    d->getMessageHook = 0;
-#endif
-}
-
-bool QEventDispatcherWin32::event(QEvent *e)
-{
-    Q_D(QEventDispatcherWin32);
-    if (e->type() == QEvent::ZeroTimerEvent) {
-        QZeroTimerEvent *zte = static_cast<QZeroTimerEvent*>(e);
-        WinTimerInfo *t = d->timerDict.value(zte->timerId());
-        if (t) {
-            t->inTimerEvent = true;
-
-            QTimerEvent te(zte->timerId());
-            QCoreApplication::sendEvent(t->obj, &te);
-
-            t = d->timerDict.value(zte->timerId());
-            if (t) {
-                if (t->interval == 0 && t->inTimerEvent) {
-                    // post the next zero timer event as long as the timer was not restarted
-                    QCoreApplication::postEvent(this, new QZeroTimerEvent(zte->timerId()));
-                }
-
-                t->inTimerEvent = false;
-            }
-        }
-        return true;
-    } else if (e->type() == QEvent::Timer) {
-        QTimerEvent *te = static_cast<QTimerEvent*>(e);
-        d->sendTimerEvent(te->timerId());
-    }
-    return QAbstractEventDispatcher::event(e);
-}
-
-QT_END_NAMESPACE
-#include "moc_qeventdispatcher_win_p.h"
diff --git a/src/core/kernel/qeventdispatcher_win_p.h b/src/core/kernel/qeventdispatcher_win_p.h
deleted file mode 100644 (file)
index d2204dc..0000000
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QEVENTDISPATCHER_WIN_P_H
-#define QEVENTDISPATCHER_WIN_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/qabstracteventdispatcher.h"
-#include "QtCore/qt_windows.h"
-
-QT_BEGIN_NAMESPACE
-
-class QWinEventNotifier;
-class QEventDispatcherWin32Private;
-
-// forward declaration
-LRESULT QT_WIN_CALLBACK qt_internal_proc(HWND hwnd, UINT message, WPARAM wp, LPARAM lp);
-
-class Q_CORE_EXPORT QEventDispatcherWin32 : public QAbstractEventDispatcher
-{
-    Q_OBJECT
-    Q_DECLARE_PRIVATE(QEventDispatcherWin32)
-
-    void createInternalHwnd();
-    friend class QGuiEventDispatcherWin32;
-
-public:
-    explicit QEventDispatcherWin32(QObject *parent = 0);
-    ~QEventDispatcherWin32();
-
-    bool QT_ENSURE_STACK_ALIGNED_FOR_SSE processEvents(QEventLoop::ProcessEventsFlags flags);
-    bool hasPendingEvents();
-
-    void registerSocketNotifier(QSocketNotifier *notifier);
-    void unregisterSocketNotifier(QSocketNotifier *notifier);
-
-    void registerTimer(int timerId, int interval, QObject *object);
-    bool unregisterTimer(int timerId);
-    bool unregisterTimers(QObject *object);
-    QList<TimerInfo> registeredTimers(QObject *object) const;
-
-    bool registerEventNotifier(QWinEventNotifier *notifier);
-    void unregisterEventNotifier(QWinEventNotifier *notifier);
-    void activateEventNotifiers();
-
-    void wakeUp();
-    void interrupt();
-    void flush();
-
-    void startingUp();
-    void closingDown();
-
-    bool event(QEvent *e);
-
-private:
-    friend LRESULT QT_WIN_CALLBACK qt_internal_proc(HWND hwnd, UINT message, WPARAM wp, LPARAM lp);
-    friend LRESULT QT_WIN_CALLBACK qt_GetMessageHook(int, WPARAM, LPARAM);
-};
-
-QT_END_NAMESPACE
-
-#endif // QEVENTDISPATCHER_WIN_P_H
diff --git a/src/core/kernel/qfunctions_wince.cpp b/src/core/kernel/qfunctions_wince.cpp
deleted file mode 100644 (file)
index 789b054..0000000
+++ /dev/null
@@ -1,451 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifdef _WIN32_WCE //Q_OS_WINCE
-
-#include <windows.h>
-#include <winbase.h>
-#include <kfuncs.h>
-#include <stdio.h>
-#include <altcecrt.h>
-
-#include "qplatformdefs.h"
-#include "qfunctions_wince.h"
-#include "qstring.h"
-#include "qbytearray.h"
-#include "qhash.h"
-
-QT_USE_NAMESPACE
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-wchar_t* CEPrivConvCharToWide(const char* string)
-{
-    size_t length = strlen(string);
-    wchar_t* wString = new wchar_t[length +1];
-    for (unsigned int i = 0; i < (length +1); i++)
-        wString[i] = string[i];
-    return wString;
-}
-
-// Time -------------------------------------------------------------
-time_t qt_wince_ftToTime_t( const FILETIME ft )
-{
-    ULARGE_INTEGER li;
-    li.LowPart  = ft.dwLowDateTime;
-    li.HighPart = ft.dwHighDateTime;
-
-    // 100-nanosec to seconds
-    li.QuadPart /= 10000000;
-
-    // FILETIME is from 1601-01-01 T 00:00:00
-    // time_t   is from 1970-01-01 T 00:00:00
-    // 1970 - 1601 = 369 year (89 leap years)
-    //
-    // ((369y*365d) + 89d) *24h *60min *60sec
-    // = 11644473600 seconds
-    li.QuadPart -= 11644473600;
-    return li.LowPart;
-}
-
-FILETIME qt_wince_time_tToFt( time_t tt )
-{
-    ULARGE_INTEGER li;
-    li.QuadPart  = tt;
-    li.QuadPart += 11644473600;
-    li.QuadPart *= 10000000;
-
-    FILETIME ft;
-    ft.dwLowDateTime = li.LowPart;
-    ft.dwHighDateTime = li.HighPart;
-    return ft;
-}
-
-// File I/O ---------------------------------------------------------
-int errno = 0;
-
-int qt_wince__getdrive( void )
-{
-    return 1;
-}
-
-int qt_wince__waccess( const wchar_t *path, int pmode )
-{
-    DWORD res = GetFileAttributes( path );
-    if ( 0xFFFFFFFF == res )
-        return -1;
-
-    if ( (pmode & W_OK) && (res & FILE_ATTRIBUTE_READONLY) )
-        return -1;
-
-    if ( (pmode & X_OK) && !(res & FILE_ATTRIBUTE_DIRECTORY) ) {
-        QString file = QString::fromWCharArray(path);
-        if ( !(file.endsWith(QString::fromLatin1(".exe")) ||
-           file.endsWith(QString::fromLatin1(".com"))) )
-        return -1;
-    }
-
-    return 0;
-}
-
-int qt_wince_open( const char *filename, int oflag, int pmode )
-{
-    QString fn( QString::fromLatin1(filename) );
-    return _wopen( (wchar_t*)fn.utf16(), oflag, pmode );
-}
-
-int qt_wince__wopen( const wchar_t *filename, int oflag, int /*pmode*/ )
-{
-    wchar_t *flag;
-
-    if ( oflag & _O_APPEND ) {
-        if ( oflag & _O_WRONLY ) {
-            flag = L"a";
-        } else if ( oflag & _O_RDWR ) {
-            flag = L"a+";
-        }
-    } else if (oflag & _O_BINARY) {
-        if ( oflag & _O_WRONLY ) {
-            flag = L"wb";
-        } else if ( oflag & _O_RDWR ) {
-            flag = L"w+b"; // slightly different from "r+" where the file must exist
-        } else if ( oflag & _O_RDONLY ) {
-            flag = L"rb";
-        } else {
-            flag = L"b";
-        }
-    } else {
-        if ( oflag & _O_WRONLY ) {
-            flag = L"wt";
-        } else if ( oflag & _O_RDWR ) {
-            flag = L"w+t"; // slightly different from "r+" where the file must exist
-        } else if ( oflag & _O_RDONLY ) {
-            flag = L"rt";
-        } else {
-            flag = L"t";
-        }
-    }
-
-    int retval = (int)_wfopen( filename, flag );
-    return (retval == NULL) ? -1 : retval;
-}
-
-long qt_wince__lseek( int handle, long offset, int origin )
-{
-    return fseek( (FILE*)handle, offset, origin );
-}
-
-int qt_wince__read( int handle, void *buffer, unsigned int count )
-{
-    return fread( buffer, 1, count, (FILE*)handle );
-}
-
-int qt_wince__write( int handle, const void *buffer, unsigned int count )
-{
-    return fwrite( buffer, 1, count, (FILE*)handle );
-}
-
-int qt_wince__close( int handle )
-{
-    if (!handle)
-        return 0;
-    return fclose( (FILE*)handle );
-}
-
-FILE *qt_wince__fdopen(int handle, const char* /*mode*/)
-{
-    return (FILE*)handle;
-}
-
-FILE *qt_wince_fdopen( int handle, const char* /*mode*/ )
-{
-    return (FILE*)handle;
-}
-
-void qt_wince_rewind( FILE *stream )
-{
-    fseek( stream, 0L, SEEK_SET );
-}
-
-int qt_wince___fileno(FILE *f)
-{
-    return (int) _fileno(f);
-}
-
-FILE *qt_wince_tmpfile( void )
-{
-    static long i = 0;
-    char name[16];
-    sprintf( name, "tmp%i", i++ );
-    return fopen( name, "r+" );
-}
-
-int qt_wince__mkdir(const char *dirname)
-{
-    return CreateDirectory(reinterpret_cast<const wchar_t *> (QString(QString::fromLatin1(dirname)).utf16()), 0) ? 0 : -1;
-}
-
-int qt_wince__rmdir(const char *dirname)
-{
-    return RemoveDirectory(reinterpret_cast<const wchar_t *> (QString::fromLatin1(dirname).utf16())) ? 0 : -1;
-}
-
-int qt_wince__access( const char *path, int pmode )
-{
-    return _waccess(reinterpret_cast<const wchar_t *> (QString::fromLatin1(path).utf16()),pmode);
-}
-
-int qt_wince__rename( const char *oldname, const char *newname )
-{
-    return !MoveFile(reinterpret_cast<const wchar_t *> (QString::fromLatin1(oldname).utf16()), reinterpret_cast<const wchar_t *> (QString::fromLatin1(newname).utf16()));
-}
-
-int qt_wince__remove( const char *name )
-{
-    return !DeleteFile(reinterpret_cast<const wchar_t *> (QString::fromLatin1(name).utf16()));
-}
-
-int qt_wince_stat( const char *path, struct stat *buffer )
-{
-    WIN32_FIND_DATA finfo;
-    HANDLE ff = FindFirstFile( reinterpret_cast<const wchar_t *> (QString::fromLatin1(path).utf16()), &finfo );
-
-    if ( ff == INVALID_HANDLE_VALUE )
-        return -1;
-
-    buffer->st_ctime = qt_wince_ftToTime_t( finfo.ftCreationTime );
-    buffer->st_atime = qt_wince_ftToTime_t( finfo.ftLastAccessTime );
-    buffer->st_mtime = qt_wince_ftToTime_t( finfo.ftLastWriteTime );
-    buffer->st_nlink = 0;
-    buffer->st_size  = finfo.nFileSizeLow; // ### missing high!
-    buffer->st_mode  = (finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? _S_IFDIR : _S_IFREG;
-    buffer->st_mode |= (finfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? _O_RDONLY : _O_RDWR;
-    return (FindClose(ff) == 0);
-}
-
-int qt_wince__fstat( int handle, struct stat *buffer)
-{
-    BY_HANDLE_FILE_INFORMATION fInfo;
-    BOOL res = GetFileInformationByHandle((HANDLE)handle, &fInfo);
-
-    buffer->st_ctime = qt_wince_ftToTime_t( fInfo.ftCreationTime );
-    buffer->st_atime = qt_wince_ftToTime_t( fInfo.ftLastAccessTime );
-    buffer->st_mtime = qt_wince_ftToTime_t( fInfo.ftLastWriteTime );
-    buffer->st_nlink = 0;
-    buffer->st_size  = fInfo.nFileSizeLow; // ### missing high!
-    buffer->st_mode  = (fInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? _S_IFDIR : _S_IFREG;
-    buffer->st_mode |= (fInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? _O_RDONLY : _O_RDWR;
-    return (res == 0);
-}
-
-int qt_wince_SetErrorMode(int newValue)
-{
-    static int oldValue;
-    int result = oldValue;
-    oldValue = newValue;
-    return result;
-}
-
-bool qt_wince__chmod(const char *file, int mode)
-{
-    return _wchmod( reinterpret_cast<const wchar_t *> (QString::fromLatin1(file).utf16()), mode);
-}
-
-bool qt_wince__wchmod(const wchar_t *file, int mode)
-{
-    BOOL success = FALSE;
-    // ### Does not work properly, what about just adding one property?
-    if(mode&_S_IWRITE) {
-        success = SetFileAttributes(file, FILE_ATTRIBUTE_NORMAL);
-    } else if((mode&_S_IREAD) && !(mode&_S_IWRITE)) {
-        success = SetFileAttributes(file, FILE_ATTRIBUTE_READONLY);
-    }
-    return success ? 0 : -1;
-}
-
-HANDLE qt_wince_CreateFileA(LPCSTR filename, DWORD access, DWORD share, LPSECURITY_ATTRIBUTES attr, DWORD dispo, DWORD flags, HANDLE tempFile)
-{
-    return CreateFileW( reinterpret_cast<const wchar_t *>(QString::fromLatin1(filename).utf16()), access, share, attr, dispo, flags, tempFile);
-}
-
-// Graphics ---------------------------------------------------------
-BOOL qt_wince_SetWindowOrgEx( HDC /*hdc*/, int /*X*/, int /*Y*/, LPPOINT /*lpPoint*/) {
-    return TRUE;
-}
-
-// Threading --------------------------------------------------------
-HANDLE qt_wince__beginthread(void( *start_address )( void * ), unsigned stack_size, void *arglist)
-{
-    unsigned initflag = 0;
-    if (stack_size > 0)
-        initflag |= STACK_SIZE_PARAM_IS_A_RESERVATION;
-    return CreateThread(NULL, stack_size, (LPTHREAD_START_ROUTINE)start_address, arglist, initflag, NULL);
-}
-
-unsigned long qt_wince__beginthreadex( void *security,
-                  unsigned stack_size,
-                  unsigned (__stdcall *start_address)(void *),
-                  void *arglist,
-                  unsigned initflag,
-                  unsigned *thrdaddr)
-{
-    if (stack_size > 0)
-        initflag |= STACK_SIZE_PARAM_IS_A_RESERVATION;
-    return (unsigned long)
-            CreateThread( (LPSECURITY_ATTRIBUTES)security,
-                          (DWORD)stack_size,
-                          (LPTHREAD_START_ROUTINE)start_address,
-                          (LPVOID)arglist,
-                          (DWORD)initflag | CREATE_SUSPENDED,
-                          (LPDWORD)thrdaddr);
-}
-
-void qt_wince__endthreadex(unsigned nExitCode) {
-    ExitThread((DWORD)nExitCode);
-}
-
-void *qt_wince_bsearch(const void *key,
-           const void *base,
-           size_t num,
-           size_t size,
-           int (__cdecl *compare)(const void *, const void *))
-{
-    size_t low = 0;
-    size_t high = num - 1;
-    while (low <= high) {
-        size_t mid = (low + high) >> 1;
-        int c = compare(key, (char*)base + mid * size);
-        if (c < 0) {
-            if (!mid)
-                break;
-            high = mid - 1;
-        } else if (c > 0)
-            low = mid + 1;
-        else
-            return (char*) base + mid * size;
-    }
-    return 0;
-}
-
-void *lfind(const void* key, const void* base, size_t* elements, size_t size,
-            int (__cdecl *compare)(const void*, const void*))
-{
-    const char* current = (char*) base;
-    const char* const end = (char*) (current + (*elements) * size);
-    while (current != end) {
-        if (compare(current, key) == 0)
-            return (void*)current;
-        current += size;
-    }
-    return 0;
-}
-
-DWORD qt_wince_GetThreadLocale(void)
-{
-    return GetUserDefaultLCID();
-}
-
-void *qt_wince_calloc( size_t num, size_t size )
-{
-    void *ptr = malloc( num * size );
-    if( ptr )
-        memset( ptr, 0, num * size );
-    return ptr;
-}
-
-// _getpid is currently only used for creating a temporary filename
-int qt_wince__getpid()
-{
-    return qAbs((int)GetCurrentProcessId());
-}
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-// Environment ------------------------------------------------------
-inline QHash<QByteArray, QByteArray>& qt_app_environment()
-{
-    static QHash<QByteArray, QByteArray> internalEnvironment;
-    return internalEnvironment;
-}
-
-errno_t qt_wince_getenv_s(size_t* sizeNeeded, char* buffer, size_t bufferSize, const char* varName)
-{
-    if (!sizeNeeded)
-        return EINVAL;
-
-    if (!qt_app_environment().contains(varName)) {
-        if (buffer)
-            buffer[0] = '\0';
-        return ENOENT;
-    }
-
-    QByteArray value = qt_app_environment().value(varName);
-    if (!value.endsWith('\0')) // win32 guarantees terminated string
-        value.append('\0');
-
-    if (bufferSize < (size_t)value.size()) {
-        *sizeNeeded = value.size();
-        return 0;
-    }
-
-    strcpy(buffer, value.constData());
-    return 0;
-}
-
-errno_t qt_wince__putenv_s(const char* varName, const char* value)
-{
-    QByteArray input = value;
-    if (input.isEmpty()) {
-        if (qt_app_environment().contains(varName))
-            qt_app_environment().remove(varName);
-    } else {
-        // win32 guarantees terminated string
-        if (!input.endsWith('\0'))
-            input.append('\0');
-        qt_app_environment()[varName] = input;
-    }
-
-    return 0;
-}
-
-#endif // Q_OS_WINCE
diff --git a/src/core/kernel/qfunctions_wince.h b/src/core/kernel/qfunctions_wince.h
deleted file mode 100644 (file)
index 152e34c..0000000
+++ /dev/null
@@ -1,401 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QFUNCTIONS_WCE_H
-#define QFUNCTIONS_WCE_H
-#ifdef Q_OS_WINCE
-#include <stdio.h>
-#include <stdlib.h>
-#include <windows.h>
-#include <winuser.h>
-#include <winbase.h>
-#include <objbase.h>
-#include <kfuncs.h>
-#include <ctype.h>
-#include <time.h>
-#include <crtdefs.h>
-#include <altcecrt.h>
-#include <winsock.h>
-#include <ceconfig.h>
-
-// The standard SDK misses this define...
-#define _control87 _controlfp
-
-#if !defined __cplusplus
-#define bool int
-#define true 1
-#define false 0
-#endif
-
-// Environment ------------------------------------------------------
-errno_t qt_wince_getenv_s(size_t*, char*, size_t, const char*);
-errno_t qt_wince__putenv_s(const char*, const char*);
-
-// Std --------------------------------------------------------------
-#ifdef __cplusplus // have this as tiff plugin is written in C
-namespace std {
-    template <class T> inline T floor(const T& a) {return ::floor(a);}
-}
-
-extern "C" {
-#endif
-
-#if !defined(NO_ERRNO_H)
-#define NO_ERRNO_H
-#endif
-
-// Environment ------------------------------------------------------
-int qt_wince__getpid(void);
-
-
-// Time -------------------------------------------------------------
-#ifndef _TM_DEFINED
-#define _TM_DEFINED
-struct tm {
-    int tm_sec;     /* seconds after the minute - [0,59] */
-    int tm_min;     /* minutes after the hour - [0,59] */
-    int tm_hour;    /* hours since midnight - [0,23] */
-    int tm_mday;    /* day of the month - [1,31] */
-    int tm_mon;     /* months since January - [0,11] */
-    int tm_year;    /* years since 1900 */
-    int tm_wday;    /* days since Sunday - [0,6] */
-    int tm_yday;    /* days since January 1 - [0,365] */
-    int tm_isdst;   /* daylight savings time flag */
-};
-#endif // _TM_DEFINED
-
-FILETIME qt_wince_time_tToFt( time_t tt );
-
-// File I/O ---------------------------------------------------------
-#define _O_RDONLY       0x0001
-#define _O_RDWR         0x0002
-#define _O_WRONLY       0x0004
-#define _O_CREAT        0x0008
-#define _O_TRUNC        0x0010
-#define _O_APPEND       0x0020
-#define _O_EXCL         0x0040
-
-#define O_RDONLY        _O_RDONLY
-#define O_RDWR          _O_RDWR
-#define O_WRONLY        _O_WRONLY
-#define O_CREAT         _O_CREAT
-#define O_TRUNC         _O_TRUNC
-#define O_APPEND        _O_APPEND
-#define O_EXCL          _O_EXCL
-
-#define _S_IFMT         0x0600
-#define _S_IFDIR        0x0200
-#define _S_IFCHR        0x0100
-#define _S_IFREG        0x0400
-#define _S_IREAD        0x0010
-#define _S_IWRITE       0x0008
-
-#define S_IFMT          _S_IFMT
-#define S_IFDIR         _S_IFDIR
-#define S_IFCHR         _S_IFCHR
-#define S_IFREG         _S_IFREG
-#define S_IREAD         _S_IREAD
-#define S_IWRITE        _S_IWRITE
-
-#ifndef _IOFBF
-#define _IOFBF          0x0000
-#endif
-
-#ifndef _IOLBF
-#define _IOLBF          0x0040
-#endif
-
-#ifndef _IONBF
-#define _IONBF          0x0004
-#endif
-
-// Regular Berkeley error constants
-#ifndef _STAT_DEFINED
-#define _STAT_DEFINED
-struct stat
-{
-    int st_mode;
-    int st_size;
-    int st_nlink;
-    time_t st_mtime;
-    time_t st_atime;
-    time_t st_ctime;
-};
-#endif
-
-typedef int mode_t;
-extern int errno;
-
-int     qt_wince__getdrive( void );
-int     qt_wince__waccess( const wchar_t *path, int pmode );
-int     qt_wince__wopen( const wchar_t *filename, int oflag, int pmode );
-long    qt_wince__lseek( int handle, long offset, int origin );
-int     qt_wince__read( int handle, void *buffer, unsigned int count );
-int     qt_wince__write( int handle, const void *buffer, unsigned int count );
-int     qt_wince__close( int handle );
-FILE   *qt_wince__fdopen(int handle, const char *mode);
-FILE   *qt_wince_fdopen(int handle, const char *mode);
-void    qt_wince_rewind( FILE *stream );
-int     qt_wince___fileno(FILE *);
-FILE   *qt_wince_tmpfile( void );
-
-//For zlib we need these helper functions, but they break the build when
-//set globally, so just set them for zlib use
-#ifdef ZLIB_H
-#define open qt_wince_open
-#define close qt_wince__close
-#define lseek qt_wince__lseek
-#define read qt_wince__read
-#define write qt_wince__write
-#endif
-
-int qt_wince__mkdir(const char *dirname);
-int qt_wince__rmdir(const char *dirname);
-int qt_wince__access( const char *path, int pmode );
-int qt_wince__rename( const char *oldname, const char *newname );
-int qt_wince__remove( const char *name );
-#ifdef __cplusplus
-int qt_wince_open( const char *filename, int oflag, int pmode = 0 );
-#else
-int qt_wince_open( const char *filename, int oflag, int pmode );
-#endif
-int qt_wince_stat( const char *path, struct stat *buffer );
-int qt_wince__fstat( int handle, struct stat *buffer);
-
-#define SEM_FAILCRITICALERRORS 0x0001
-#define SEM_NOOPENFILEERRORBOX 0x0002
-int qt_wince_SetErrorMode(int);
-#ifndef CoInitialize
-#define CoInitialize(x) CoInitializeEx(x, COINIT_MULTITHREADED)
-#endif
-
-bool qt_wince__chmod(const char *file, int mode);
-bool qt_wince__wchmod(const wchar_t *file, int mode);
-
-#pragma warning(disable: 4273)
-HANDLE qt_wince_CreateFileA(LPCSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE);
-
-// Printer ----------------------------------------------------------
-#define ETO_GLYPH_INDEX     0x0010
-
-// Graphics ---------------------------------------------------------
-#ifndef SM_CXCURSOR
-#  define SM_CXCURSOR       13
-#endif
-#ifndef SM_CYCURSOR
-#  define SM_CYCURSOR      14
-#endif
-BOOL qt_wince_SetWindowOrgEx( HDC hdc, int X, int Y, LPPOINT lpPoint );
-
-// Other stuff ------------------------------------------------------
-#define MWMO_ALERTABLE 0x0002
-// ### not the real values
-#define CREATE_NO_WINDOW        2
-#define CF_HDROP                15
-
-void *qt_wince_calloc(size_t num, size_t size);
-#if !defined(TLS_OUT_OF_INDEXES)
-#  define TLS_OUT_OF_INDEXES 0xffffffff
-#endif
-DWORD qt_wince_GetThreadLocale(void);
-
-HANDLE qt_wince__beginthread(void( *start_address )( void * ), unsigned stack_size, void *arglist);
-
-unsigned long qt_wince__beginthreadex( void *security,
-                              unsigned stack_size,
-                              unsigned (__stdcall *start_address)(void *),
-                              void *arglist,
-                              unsigned initflag,
-                              unsigned *thrdaddr );
-void qt_wince__endthreadex(unsigned nExitCode);
-
-
-// bsearch is needed for building the tiff plugin
-// otherwise it could go into qguifunctions_wce
-void *qt_wince_bsearch(const void *key,
-               const void *base,
-               size_t num,
-               size_t size,
-               int (__cdecl *compare)(const void *, const void *));
-
-// Missing typedefs
-#ifndef _TIME_T_DEFINED
-typedef unsigned long time_t;
-#define _TIME_T_DEFINED
-#endif
-typedef HANDLE HDROP;
-
-#ifndef WS_THICKFRAME
-#define WS_THICKFRAME   WS_DLGFRAME
-#endif
-
-typedef UINT    UWORD;
-
-// Missing definitions: not necessary equal to their Win32 values
-// (the goal is to just have a clean compilation of MFC)
-#define WS_MAXIMIZE               0
-#define WS_MINIMIZE               0
-#ifndef WS_EX_TOOLWINDOW
-#define WS_EX_TOOLWINDOW          0
-#endif
-#define WS_EX_NOPARENTNOTIFY      0
-#define WM_ENTERIDLE              0x0121
-#define WM_PRINT                  WM_PAINT
-#define WM_NCCREATE               (0x0081)
-#define WM_PARENTNOTIFY           0
-#define WM_NCDESTROY              (WM_APP-1)
-#ifndef SW_RESTORE
-#define SW_RESTORE                (SW_SHOWNORMAL)
-#endif
-#define SW_NORMAL                 (SW_SHOWNORMAL)
-#define WAIT_OBJECT_0             0x00000000L
-#define DEFAULT_GUI_FONT          SYSTEM_FONT
-#ifndef SWP_NOREDRAW
-#define SWP_NOREDRAW               0
-#endif
-#define WSAGETSELECTEVENT(lParam) LOWORD(lParam)
-#define HWND_TOPMOST              ((HWND)-1)
-#define HWND_NOTOPMOST            ((HWND)-2)
-#define PS_DOT                    2
-#define PD_ALLPAGES               0
-#define PD_USEDEVMODECOPIES       0
-#define PD_NOSELECTION            0
-#define PD_HIDEPRINTTOFILE        0
-#define PD_NOPAGENUMS             0
-#define CF_METAFILEPICT           3
-#define MM_ANISOTROPIC            8
-#define KF_ALTDOWN                0x2000
-#define SPI_GETWORKAREA           48
-
-#ifndef WM_SETCURSOR
-        #define WM_SETCURSOR 0x0020
-        #define IDC_ARROW           MAKEINTRESOURCE(32512)
-        #define IDC_IBEAM           MAKEINTRESOURCE(32513)
-        #define IDC_WAIT            MAKEINTRESOURCE(32514)
-        #define IDC_CROSS           MAKEINTRESOURCE(32515)
-        #define IDC_UPARROW         MAKEINTRESOURCE(32516)
-        #define IDC_SIZE            MAKEINTRESOURCE(32646)
-        #define IDC_ICON            MAKEINTRESOURCE(32512)
-        #define IDC_SIZENWSE        MAKEINTRESOURCE(32642)
-        #define IDC_SIZENESW        MAKEINTRESOURCE(32643)
-        #define IDC_SIZEWE          MAKEINTRESOURCE(32644)
-        #define IDC_SIZENS          MAKEINTRESOURCE(32645)
-        #define IDC_SIZEALL         MAKEINTRESOURCE(32646)
-        #define IDC_NO              MAKEINTRESOURCE(32648)
-        #define IDC_APPSTARTING     MAKEINTRESOURCE(32650)
-        #define IDC_HELP            MAKEINTRESOURCE(32651)
-        #define IDC_HAND            MAKEINTRESOURCE(32649)
-#endif
-
-#define GMEM_MOVEABLE             LMEM_MOVEABLE
-#define GPTR                      LPTR
-
-// WinCE: CESYSGEN prunes the following FRP defines,
-// and INTERNET_TRANSFER_TYPE_ASCII breaks in wininet.h
-#undef FTP_TRANSFER_TYPE_ASCII
-#define FTP_TRANSFER_TYPE_ASCII 0x00000001
-#undef FTP_TRANSFER_TYPE_BINARY
-#define FTP_TRANSFER_TYPE_BINARY 0x00000002
-
-typedef DWORD OLE_COLOR;
-
-// Define the Windows Styles which are not defined by MS
-#ifndef WS_POPUPWINDOW
-#define WS_POPUPWINDOW WS_POPUP|WS_BORDER|WS_SYSMENU|WS_CAPTION
-#endif
-
-#ifndef WS_OVERLAPPEDWINDOW
-#define WS_OVERLAPPEDWINDOW WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_THICKFRAME|WS_MINIMIZEBOX|WS_MAXIMIZEBOX
-#endif
-
-#ifndef WS_TILED
-#define WS_TILED WS_OVERLAPPED
-#endif
-
-#ifndef WS_TILEDWINDOW
-#define WS_TILEDWINDOW WS_OVERLAPPEDWINDOW
-#endif
-
-#ifndef WS_EX_CAPTIONOKBTN
-#define WS_EX_CAPTIONOKBTN 0x80000000L
-#endif
-
-#ifndef WS_EX_NODRAG
-#define WS_EX_NODRAG       0x40000000L
-#endif
-
-// As Windows CE lacks some standard functions used in Qt, these got
-// reimplented. Other projects do this as well and to not fill the
-// global namespace with this implementation, prepend qt_wince* and use
-// these versions inside of Qt.
-// The other declarations available in this file are being used per
-// define inside qplatformdefs.h of the corresponding WinCE mkspec.
-#define getenv_s(a,b,c,d)       qt_wince_getenv_s(a,b,c,d)
-#define _putenv_s(a,b)          qt_wince__putenv_s(a,b)
-#define _getpid()               qt_wince__getpid()
-#define time_tToFt(a)           qt_wince_time_tToFt(a)
-#define _getdrive()             qt_wince__getdrive()
-#define _waccess(a,b)           qt_wince__waccess(a,b)
-#define _wopen(a,b,c)           qt_wince__wopen(a,b,c)
-#define _fdopen(a,b)            qt_wince__fdopen(a,b)
-#define fdopen(a,b)             qt_wince_fdopen(a,b)
-#define rewind(a)               qt_wince_rewind(a)
-#define tmpfile()               qt_wince_tmpfile()
-#define _rename(a,b)            qt_wince__rename(a,b)
-#define _remove(a)              qt_wince__remove(a)
-#define SetErrorMode(a)         qt_wince_SetErrorMode(a)
-#define _chmod(a,b)             qt_wince__chmod(a,b)
-#define _wchmod(a,b)            qt_wince__wchmod(a,b)
-#define CreateFileA(a,b,c,d,e,f,g) qt_wince_CreateFileA(a,b,c,d,e,f,g)
-#define SetWindowOrgEx(a,b,c,d) qt_wince_SetWindowOrgEx(a,b,c,d)
-#define calloc(a,b)             qt_wince_calloc(a,b)
-#define GetThreadLocale()       qt_wince_GetThreadLocale()
-#define _beginthread(a,b,c)     qt_wince__beginthread(a,b,c)
-#define _beginthreadex(a,b,c,d,e,f) qt_wince__beginthreadex(a,b,c,d,e,f)
-#define _endthreadex(a)         qt_wince__endthreadex(a)
-#define bsearch(a,b,c,d,e)      qt_wince_bsearch(a,b,c,d,e)
-
-#ifdef __cplusplus
-} // Extern C.
-#endif
-
-#endif // Q_OS_WINCE
-#endif // QFUNCTIONS_WCE_H
diff --git a/src/core/kernel/qsharedmemory_win.cpp b/src/core/kernel/qsharedmemory_win.cpp
deleted file mode 100644 (file)
index 1443133..0000000
+++ /dev/null
@@ -1,194 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsharedmemory.h"
-#include "qsharedmemory_p.h"
-
-#include <qdebug.h>
-
-#ifndef QT_NO_SHAREDMEMORY
-
-//#define QSHAREDMEMORY_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-QSharedMemoryPrivate::QSharedMemoryPrivate()
-    : QObjectPrivate(), memory(0), size(0), error(QSharedMemory::NoError),
-#ifndef QT_NO_SYSTEMSEMAPHORE
-      systemSemaphore(QString()), lockedByMe(false),
-#endif
-      hand(0)
-{
-}
-
-void QSharedMemoryPrivate::setErrorString(const QString &function)
-{
-    DWORD windowsError = GetLastError();
-    if (windowsError == 0)
-        return;
-
-    switch (windowsError) {
-    case ERROR_ALREADY_EXISTS:
-        error = QSharedMemory::AlreadyExists;
-        errorString = QSharedMemory::tr("%1: already exists").arg(function);
-    break;
-    case ERROR_FILE_NOT_FOUND:
-#ifdef Q_OS_WINCE
-        // This happens on CE only if no file is present as CreateFileMappingW
-        // bails out with this error code
-    case ERROR_INVALID_PARAMETER:
-#endif
-        error = QSharedMemory::NotFound;
-        errorString = QSharedMemory::tr("%1: doesn't exist").arg(function);
-        break;
-    case ERROR_COMMITMENT_LIMIT:
-        error = QSharedMemory::InvalidSize;
-        errorString = QSharedMemory::tr("%1: invalid size").arg(function);
-        break;
-    case ERROR_NO_SYSTEM_RESOURCES:
-    case ERROR_NOT_ENOUGH_MEMORY:
-        error = QSharedMemory::OutOfResources;
-        errorString = QSharedMemory::tr("%1: out of resources").arg(function);
-        break;
-    case ERROR_ACCESS_DENIED:
-        error = QSharedMemory::PermissionDenied;
-        errorString = QSharedMemory::tr("%1: permission denied").arg(function);
-        break;
-    default:
-        errorString = QSharedMemory::tr("%1: unknown error %2").arg(function).arg(windowsError);
-        error = QSharedMemory::UnknownError;
-#ifdef QSHAREDMEMORY_DEBUG
-        qDebug() << errorString << "key" << key;
-#endif
-        break;
-    }
-}
-
-HANDLE QSharedMemoryPrivate::handle()
-{
-    if (!hand) {
-        // don't allow making handles on empty keys
-        if (nativeKey.isEmpty()) {
-            error = QSharedMemory::KeyError;
-            errorString = QSharedMemory::tr("%1: key is empty").arg(QLatin1String("QSharedMemory::handle"));
-            return 0;
-        }
-#ifndef Q_OS_WINCE
-        hand = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, (wchar_t*)nativeKey.utf16());
-#else
-        // This works for opening a mapping too, but always opens it with read/write access in
-        // attach as it seems.
-        hand = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, 0, (wchar_t*)nativeKey.utf16());
-#endif
-        if (!hand)
-            setErrorString(QLatin1String("QSharedMemory::handle"));
-    }
-
-    return hand;
-}
-
-void QSharedMemoryPrivate::cleanHandle()
-{
-    if (hand != 0 && !CloseHandle(hand))
-        setErrorString(QLatin1String("QSharedMemory::cleanHandle"));
-    hand = 0;
-}
-
-bool QSharedMemoryPrivate::create(int size)
-{
-    if (nativeKey.isEmpty()) {
-        error = QSharedMemory::KeyError;
-        errorString = QSharedMemory::tr("%1: key is empty").arg(QLatin1String("QSharedMemory::create"));
-        return false;
-    }
-
-    // Create the file mapping.
-    hand = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, size, (wchar_t*)nativeKey.utf16());
-    setErrorString(QLatin1String("QSharedMemory::create"));
-
-    // hand is valid when it already exists unlike unix so explicitly check
-    return !(error == QSharedMemory::AlreadyExists || !hand);
-}
-
-bool QSharedMemoryPrivate::attach(QSharedMemory::AccessMode mode)
-{
-    // Grab a pointer to the memory block
-    int permissions = (mode == QSharedMemory::ReadOnly ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS);
-    memory = (void *)MapViewOfFile(handle(), permissions, 0, 0, 0);
-    if (0 == memory) {
-        setErrorString(QLatin1String("QSharedMemory::attach"));
-        cleanHandle();
-        return false;
-    }
-
-    // Grab the size of the memory we have been given (a multiple of 4K on windows)
-    MEMORY_BASIC_INFORMATION info;
-    if (!VirtualQuery(memory, &info, sizeof(info))) {
-        // Windows doesn't set an error code on this one,
-        // it should only be a kernel memory error.
-        error = QSharedMemory::UnknownError;
-        errorString = QSharedMemory::tr("%1: size query failed").arg(QLatin1String("QSharedMemory::attach"));
-        return false;
-    }
-    size = info.RegionSize;
-
-    return true;
-}
-
-bool QSharedMemoryPrivate::detach()
-{
-    // umap memory
-    if (!UnmapViewOfFile(memory)) {
-        setErrorString(QLatin1String("QSharedMemory::detach"));
-        return false;
-    }
-    memory = 0;
-    size = 0;
-
-    // close handle
-    cleanHandle();
-
-    return true;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SHAREDMEMORY
diff --git a/src/core/kernel/qsystemsemaphore_win.cpp b/src/core/kernel/qsystemsemaphore_win.cpp
deleted file mode 100644 (file)
index ec9dfe6..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsystemsemaphore.h"
-#include "qsystemsemaphore_p.h"
-#include "qcoreapplication.h"
-#include <qdebug.h>
-
-#ifndef QT_NO_SYSTEMSEMAPHORE
-
-//#define QSYSTEMSEMAPHORE_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-QSystemSemaphorePrivate::QSystemSemaphorePrivate() :
-    semaphore(0), error(QSystemSemaphore::NoError)
-{
-}
-
-void QSystemSemaphorePrivate::setErrorString(const QString &function)
-{
-    DWORD windowsError = GetLastError();
-    if (windowsError == 0)
-        return;
-
-    switch (windowsError) {
-    case ERROR_NO_SYSTEM_RESOURCES:
-    case ERROR_NOT_ENOUGH_MEMORY:
-        error = QSystemSemaphore::OutOfResources;
-        errorString = QCoreApplication::translate("QSystemSemaphore", "%1: out of resources").arg(function);
-        break;
-    case ERROR_ACCESS_DENIED:
-        error = QSystemSemaphore::PermissionDenied;
-        errorString = QCoreApplication::translate("QSystemSemaphore", "%1: permission denied").arg(function);
-        break;
-    default:
-        errorString = QCoreApplication::translate("QSystemSemaphore", "%1: unknown error %2").arg(function).arg(windowsError);
-        error = QSystemSemaphore::UnknownError;
-#ifdef QSYSTEMSEMAPHORE_DEBUG
-        qDebug() << errorString << "key" << key;
-#endif
-        break;
-    }
-}
-
-HANDLE QSystemSemaphorePrivate::handle(QSystemSemaphore::AccessMode)
-{
-    // don't allow making handles on empty keys
-    if (key.isEmpty())
-        return 0;
-
-    // Create it if it doesn't already exists.
-    if (semaphore == 0) {
-        semaphore = CreateSemaphore(0, initialValue, MAXLONG, (wchar_t*)fileName.utf16());
-        if (semaphore == NULL)
-            setErrorString(QLatin1String("QSystemSemaphore::handle"));
-    }
-
-    return semaphore;
-}
-
-void QSystemSemaphorePrivate::cleanHandle()
-{
-    if (semaphore && !CloseHandle(semaphore)) {
-#if defined QSYSTEMSEMAPHORE_DEBUG
-        qDebug() << QLatin1String("QSystemSemaphorePrivate::CloseHandle: sem failed");
-#endif
-    }
-    semaphore = 0;
-}
-
-bool QSystemSemaphorePrivate::modifySemaphore(int count)
-{
-    if (0 == handle())
-        return false;
-
-    if (count > 0) {
-        if (0 == ReleaseSemaphore(semaphore, count, 0)) {
-            setErrorString(QLatin1String("QSystemSemaphore::modifySemaphore"));
-#if defined QSYSTEMSEMAPHORE_DEBUG
-            qDebug() << QLatin1String("QSystemSemaphore::modifySemaphore ReleaseSemaphore failed");
-#endif
-            return false;
-        }
-    } else {
-        if (WAIT_OBJECT_0 != WaitForSingleObject(semaphore, INFINITE)) {
-            setErrorString(QLatin1String("QSystemSemaphore::modifySemaphore"));
-#if defined QSYSTEMSEMAPHORE_DEBUG
-            qDebug() << QLatin1String("QSystemSemaphore::modifySemaphore WaitForSingleObject failed");
-#endif
-            return false;
-        }
-    }
-
-    return true;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_SYSTEMSEMAPHORE
diff --git a/src/core/plugin/qlibrary_win.cpp b/src/core/plugin/qlibrary_win.cpp
deleted file mode 100644 (file)
index 9730e23..0000000
+++ /dev/null
@@ -1,180 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qplatformdefs.h"
-#include "qlibrary_p.h"
-#include "qfile.h"
-#include "qdir.h"
-#include "qfileinfo.h"
-#include "qdir.h"
-#include <qfilesystementry_p.h>
-
-#if defined(QT_NO_LIBRARY) && defined(Q_OS_WIN)
-#undef QT_NO_LIBRARY
-#pragma message("QT_NO_LIBRARY is not supported on Windows")
-#endif
-
-#include "qt_windows.h"
-
-QT_BEGIN_NAMESPACE
-
-extern QString qt_error_string(int code);
-
-bool QLibraryPrivate::load_sys()
-{
-    //avoid 'Bad Image' message box
-    UINT oldmode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
-
-    // We make the following attempts at locating the library:
-    //
-    // WinCE
-    // if (loadHints & QLibrary::ImprovedSearchHeuristics)
-    //   if (absolute)
-    //     fileName
-    //     fileName + ".dll"
-    //   else
-    //     fileName + ".dll"
-    //     fileName
-    //     QFileInfo(fileName).absoluteFilePath()
-    // else
-    //   QFileInfo(fileName).absoluteFilePath();
-    //   fileName
-    //   fileName + ".dll"
-    //
-    // Windows
-    // if (loadHints & QLibrary::ImprovedSearchHeuristics)
-    //   if (absolute)
-    //     fileName
-    //     fileName + ".dll"
-    //   else
-    //     fileName + ".dll"
-    //     fileName
-    // else
-    //   fileName
-    //   fileName + ".dll"
-    //
-    // NB If it's a plugin we do not ever try the ".dll" extension
-    QStringList attempts;
-    QFileSystemEntry fsEntry(fileName);
-    if (loadHints & QLibrary::ImprovedSearchHeuristics) {
-        if (pluginState != IsAPlugin)
-            attempts.append(fileName + QLatin1String(".dll"));
-
-        // If the fileName is an absolute path we try that first, otherwise we
-        // use the system-specific suffix first
-        if (fsEntry.isAbsolute()) {
-            attempts.prepend(fileName);
-        } else {
-            attempts.append(fileName);
-#if defined(Q_OS_WINCE)
-            attempts.append(QFileInfo(fileName).absoluteFilePath());
-#endif
-        }
-    } else {
-#ifdef Q_OS_WINCE
-        attempts.append(QFileInfo(fileName).absoluteFilePath());
-#else
-        attempts.append(fileName);
-#endif
-        if (pluginState != IsAPlugin) {
-#if defined(Q_OS_WINCE)
-            attempts.append(fileName);
-#endif
-            attempts.append(fileName + QLatin1String(".dll"));
-        }
-    }
-
-    Q_FOREACH (const QString &attempt, attempts) {
-        pHnd = LoadLibrary((wchar_t*)QDir::toNativeSeparators(attempt).utf16());
-
-        // If we have a handle or the last error is something other than "unable
-        // to find the module", then bail out
-        if (pHnd || ::GetLastError() != ERROR_MOD_NOT_FOUND)
-            break;
-    }
-
-    SetErrorMode(oldmode);
-    if (!pHnd) {
-        errorString = QLibrary::tr("Cannot load library %1: %2").arg(fileName).arg(qt_error_string());
-    } else {
-        // Query the actual name of the library that was loaded
-        errorString.clear();
-
-        wchar_t buffer[MAX_PATH];
-        ::GetModuleFileName(pHnd, buffer, MAX_PATH);
-
-        QString moduleFileName = QString::fromWCharArray(buffer);
-        moduleFileName.remove(0, 1 + moduleFileName.lastIndexOf(QLatin1Char('\\')));
-        const QDir dir(fsEntry.path());
-        if (dir.path() == QLatin1String("."))
-            qualifiedFileName = moduleFileName;
-        else
-            qualifiedFileName = dir.filePath(moduleFileName);
-    }
-    return (pHnd != 0);
-}
-
-bool QLibraryPrivate::unload_sys()
-{
-    if (!FreeLibrary(pHnd)) {
-        errorString = QLibrary::tr("Cannot unload library %1: %2").arg(fileName).arg(qt_error_string());
-        return false;
-    }
-    errorString.clear();
-    return true;
-}
-
-void* QLibraryPrivate::resolve_sys(const char* symbol)
-{
-#ifdef Q_OS_WINCE
-    void* address = (void*)GetProcAddress(pHnd, (const wchar_t*)QString::fromLatin1(symbol).utf16());
-#else
-    void* address = (void*)GetProcAddress(pHnd, symbol);
-#endif
-    if (!address) {
-        errorString = QLibrary::tr("Cannot resolve symbol \"%1\" in %2: %3").arg(
-            QString::fromAscii(symbol)).arg(fileName).arg(qt_error_string());
-    } else {
-        errorString.clear();
-    }
-    return address;
-}
-QT_END_NAMESPACE
diff --git a/src/core/plugin/qsystemlibrary.cpp b/src/core/plugin/qsystemlibrary.cpp
deleted file mode 100644 (file)
index 241455d..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsystemlibrary_p.h"
-
-#include <QtCore/qvarlengtharray.h>
-#include <QtCore/qstringlist.h>
-#include <QtCore/qfileinfo.h>
-
-/*!
-
-    \internal
-    \class QSystemLibrary
-
-    The purpose of this class is to load only libraries that are located in
-    well-known and trusted locations on the filesystem. It does not suffer from
-    the security problem that QLibrary has, therefore it will never search in
-    the current directory.
-
-    The search order is the same as the order in DLL Safe search mode Windows,
-    except that we don't search:
-    * The current directory
-    * The 16-bit system directory. (normally \c{c:\windows\system})
-    * The Windows directory.  (normally \c{c:\windows})
-
-    This means that the effective search order is:
-    1. Application path.
-    2. System libraries path.
-    3. Trying all paths inside the PATH environment variable.
-
-    Note, when onlySystemDirectory is true it will skip 1) and 3).
-
-    DLL Safe search mode is documented in the "Dynamic-Link Library Search
-    Order" document on MSDN.
-
-    Since library loading code is sometimes shared between Windows and WinCE,
-    this class can also be used on WinCE. However, its implementation just
-    calls the LoadLibrary() function. This is ok since it is documented as not
-    loading from the current directory on WinCE. This behaviour is documented
-    in the documentation for LoadLibrary for Windows CE at MSDN.
-    (http://msdn.microsoft.com/en-us/library/ms886736.aspx)
-*/
-
-QT_BEGIN_NAMESPACE
-
-#if defined(Q_OS_WINCE)
-HINSTANCE QSystemLibrary::load(const wchar_t *libraryName, bool onlySystemDirectory /* = true */)
-{
-    Q_UNUSED(onlySystemDirectory);
-    return ::LoadLibrary(libraryName);
-}
-#else
-
-#if !defined(QT_BOOTSTRAPPED)
-extern QString qAppFileName();
-#endif
-
-static inline QString qSystemDirectory()
-{
-    QVarLengthArray<wchar_t, MAX_PATH> fullPath;
-
-    UINT retLen = ::GetSystemDirectory(fullPath.data(), MAX_PATH);
-    if (retLen > MAX_PATH) {
-        fullPath.resize(retLen);
-        retLen = ::GetSystemDirectory(fullPath.data(), retLen);
-    }
-    // in some rare cases retLen might be 0
-    return QString::fromWCharArray(fullPath.constData(), int(retLen));
-}
-
-HINSTANCE QSystemLibrary::load(const wchar_t *libraryName, bool onlySystemDirectory /* = true */)
-{
-    QStringList searchOrder;
-
-#if !defined(QT_BOOTSTRAPPED)
-    if (!onlySystemDirectory)
-        searchOrder << QFileInfo(qAppFileName()).path();
-#endif
-    searchOrder << qSystemDirectory();
-
-    if (!onlySystemDirectory) {
-        const QString PATH = QString::fromWCharArray((const wchar_t *)_wgetenv(L"PATH"));
-        searchOrder << PATH.split(QLatin1Char(';'), QString::SkipEmptyParts);
-    }
-
-    const QString fileName = QString::fromWCharArray(libraryName) + QLatin1String(".dll");
-    // Start looking in the order specified
-    for (int i = 0; i < searchOrder.count(); ++i) {
-        QString fullPathAttempt = searchOrder.at(i);
-        if (!fullPathAttempt.endsWith(QLatin1Char('\\')))
-            fullPathAttempt.append(QLatin1Char('\\'));
-        fullPathAttempt.append(fileName);
-        HINSTANCE inst = ::LoadLibrary((const wchar_t *)fullPathAttempt.utf16());
-        if (inst != 0)
-            return inst;
-    }
-
-    return 0;
-}
-
-#endif // !Q_OS_WINCE
-
-QT_END_NAMESPACE
diff --git a/src/core/plugin/qsystemlibrary_p.h b/src/core/plugin/qsystemlibrary_p.h
deleted file mode 100644 (file)
index 577000d..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QSYSTEMLIBRARY_P_H
-#define QSYSTEMLIBRARY_P_H
-
-#include <QtCore/qglobal.h>
-#ifdef Q_OS_WIN
-#include <qt_windows.h>
-#include <QtCore/qstring.h>
-
-QT_BEGIN_NAMESPACE
-
-class QSystemLibrary
-{
-public:
-    explicit QSystemLibrary(const QString &libraryName)
-    {
-        m_libraryName = libraryName;
-        m_handle = 0;
-        m_didLoad = false;
-    }
-
-    explicit QSystemLibrary(const wchar_t *libraryName)
-    {
-        m_libraryName = QString::fromWCharArray(libraryName);
-        m_handle = 0;
-        m_didLoad = false;
-    }
-
-    bool load(bool onlySystemDirectory = true)
-    {
-        m_handle = load((const wchar_t *)m_libraryName.utf16(), onlySystemDirectory);
-        m_didLoad = true;
-        return (m_handle != 0);
-    }
-
-    bool isLoaded()
-    {
-        return (m_handle != 0);
-    }
-
-    void *resolve(const char *symbol)
-    {
-        if (!m_didLoad)
-            load();
-        if (!m_handle)
-            return 0;
-#ifdef Q_OS_WINCE
-        return (void*)GetProcAddress(m_handle, (const wchar_t*)QString::fromLatin1(symbol).utf16());
-#else
-        return (void*)GetProcAddress(m_handle, symbol);
-#endif
-    }
-
-    static void *resolve(const QString &libraryName, const char *symbol)
-    {
-        return QSystemLibrary(libraryName).resolve(symbol);
-    }
-
-    static Q_CORE_EXPORT HINSTANCE load(const wchar_t *lpFileName, bool onlySystemDirectory = true);
-
-private:
-    HINSTANCE m_handle;
-    QString m_libraryName;
-    bool m_didLoad;
-};
-
-QT_END_NAMESPACE
-
-#endif // Q_OS_WIN
-
-#endif // QSYSTEMLIBRARY_P_H
diff --git a/src/core/thread/qmutex_win.cpp b/src/core/thread/qmutex_win.cpp
deleted file mode 100644 (file)
index a88c64d..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qt_windows.h>
-
-#include "qmutex.h"
-#include <qatomic.h>
-#include "qmutex_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QMutexPrivate::QMutexPrivate(QMutex::RecursionMode mode)
-    : QMutexData(mode), maximumSpinTime(MaximumSpinTimeThreshold), averageWaitTime(0), owner(0), count(0)
-{
-    event = CreateEvent(0, FALSE, FALSE, 0);
-    if (!event)
-        qWarning("QMutexPrivate::QMutexPrivate: Cannot create event");
-}
-
-QMutexPrivate::~QMutexPrivate()
-{ CloseHandle(event); }
-
-bool QMutexPrivate::wait(int timeout)
-{
-    if (contenders.fetchAndAddAcquire(1) == 0) {
-        // lock acquired without waiting
-        return true;
-    }
-    bool returnValue = (WaitForSingleObject(event, timeout < 0 ? INFINITE : timeout) ==  WAIT_OBJECT_0);
-    contenders.deref();
-    return returnValue;
-}
-
-void QMutexPrivate::wakeUp()
-{ SetEvent(event); }
-
-QT_END_NAMESPACE
diff --git a/src/core/thread/qthread_win.cpp b/src/core/thread/qthread_win.cpp
deleted file mode 100644 (file)
index 2d1795d..0000000
+++ /dev/null
@@ -1,666 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//#define WINVER 0x0500
-#if _WIN32_WINNT < 0x0400
-#define _WIN32_WINNT 0x0400
-#endif
-
-
-#include "qthread.h"
-#include "qthread_p.h"
-#include "qthreadstorage.h"
-#include "qmutex.h"
-
-#include <qcoreapplication.h>
-#include <qpointer.h>
-
-#include <qcoreapplication_p.h>
-#include <qeventdispatcher_win_p.h>
-
-#include <qt_windows.h>
-
-
-#ifndef Q_OS_WINCE
-#ifndef _MT
-#define _MT
-#endif
-#include <process.h>
-#else
-#include "qfunctions_wince.h"
-#endif
-
-#ifndef QT_NO_THREAD
-QT_BEGIN_NAMESPACE
-
-void qt_watch_adopted_thread(const HANDLE adoptedThreadHandle, QThread *qthread);
-DWORD WINAPI qt_adopted_thread_watcher_function(LPVOID);
-
-static DWORD qt_current_thread_data_tls_index = TLS_OUT_OF_INDEXES;
-void qt_create_tls()
-{
-    if (qt_current_thread_data_tls_index != TLS_OUT_OF_INDEXES)
-        return;
-    static QMutex mutex;
-    QMutexLocker locker(&mutex);
-    qt_current_thread_data_tls_index = TlsAlloc();
-}
-
-static void qt_free_tls()
-{
-    if (qt_current_thread_data_tls_index != TLS_OUT_OF_INDEXES) {
-        TlsFree(qt_current_thread_data_tls_index);
-        qt_current_thread_data_tls_index = TLS_OUT_OF_INDEXES;
-    }
-}
-Q_DESTRUCTOR_FUNCTION(qt_free_tls)
-
-/*
-    QThreadData
-*/
-void QThreadData::clearCurrentThreadData()
-{
-    TlsSetValue(qt_current_thread_data_tls_index, 0);
-}
-
-QThreadData *QThreadData::current()
-{
-    qt_create_tls();
-    QThreadData *threadData = reinterpret_cast<QThreadData *>(TlsGetValue(qt_current_thread_data_tls_index));
-    if (!threadData) {
-        QThread *adopted = 0;
-        if (QInternal::activateCallbacks(QInternal::AdoptCurrentThread, (void **) &adopted)) {
-            Q_ASSERT(adopted);
-            threadData = QThreadData::get2(adopted);
-            TlsSetValue(qt_current_thread_data_tls_index, threadData);
-            adopted->d_func()->running = true;
-            adopted->d_func()->finished = false;
-            static_cast<QAdoptedThread *>(adopted)->init();
-        } else {
-            threadData = new QThreadData;
-            // This needs to be called prior to new AdoptedThread() to
-            // avoid recursion.
-            TlsSetValue(qt_current_thread_data_tls_index, threadData);
-            QT_TRY {
-                threadData->thread = new QAdoptedThread(threadData);
-            } QT_CATCH(...) {
-                TlsSetValue(qt_current_thread_data_tls_index, 0);
-                threadData->deref();
-                threadData = 0;
-                QT_RETHROW;
-            }
-            threadData->deref();
-        }
-        threadData->isAdopted = true;
-        threadData->threadId = reinterpret_cast<Qt::HANDLE>(GetCurrentThreadId());
-
-        if (!QCoreApplicationPrivate::theMainThread) {
-            QCoreApplicationPrivate::theMainThread = threadData->thread;
-        } else {
-            HANDLE realHandle = INVALID_HANDLE_VALUE;
-#if !defined(Q_OS_WINCE) || (defined(_WIN32_WCE) && (_WIN32_WCE>=0x600))
-            DuplicateHandle(GetCurrentProcess(),
-                    GetCurrentThread(),
-                    GetCurrentProcess(),
-                    &realHandle,
-                    0,
-                    FALSE,
-                    DUPLICATE_SAME_ACCESS);
-#else
-                        realHandle = reinterpret_cast<HANDLE>(GetCurrentThreadId());
-#endif
-            qt_watch_adopted_thread(realHandle, threadData->thread);
-        }
-    }
-    return threadData;
-}
-
-void QAdoptedThread::init()
-{
-    d_func()->handle = GetCurrentThread();
-    d_func()->id = GetCurrentThreadId();
-}
-
-static QVector<HANDLE> qt_adopted_thread_handles;
-static QVector<QThread *> qt_adopted_qthreads;
-static QMutex qt_adopted_thread_watcher_mutex;
-static DWORD qt_adopted_thread_watcher_id = 0;
-static HANDLE qt_adopted_thread_wakeup = 0;
-
-/*! \internal
-    Adds an adopted thread to the list of threads that Qt watches to make sure
-    the thread data is properly cleaned up. This function starts the watcher
-    thread if necessary.
-*/
-void qt_watch_adopted_thread(const HANDLE adoptedThreadHandle, QThread *qthread)
-{
-    QMutexLocker lock(&qt_adopted_thread_watcher_mutex);
-
-    if (GetCurrentThreadId() == qt_adopted_thread_watcher_id) {
-#if !defined(Q_OS_WINCE) || (defined(_WIN32_WCE) && (_WIN32_WCE>=0x600))
-        CloseHandle(adoptedThreadHandle);
-#endif
-        return;
-    }
-
-    qt_adopted_thread_handles.append(adoptedThreadHandle);
-    qt_adopted_qthreads.append(qthread);
-
-    // Start watcher thread if it is not already running.
-    if (qt_adopted_thread_watcher_id == 0) {
-        if (qt_adopted_thread_wakeup == 0) {
-            qt_adopted_thread_wakeup = CreateEvent(0, false, false, 0);
-            qt_adopted_thread_handles.prepend(qt_adopted_thread_wakeup);
-        }
-
-        CreateThread(0, 0, qt_adopted_thread_watcher_function, 0, 0, &qt_adopted_thread_watcher_id);
-    } else {
-        SetEvent(qt_adopted_thread_wakeup);
-    }
-}
-
-/*! \internal
-    This function loops and waits for native adopted threads to finish.
-    When this happens it derefs the QThreadData for the adopted thread
-    to make sure it gets cleaned up properly.
-*/
-DWORD WINAPI qt_adopted_thread_watcher_function(LPVOID)
-{
-    forever {
-        qt_adopted_thread_watcher_mutex.lock();
-
-        if (qt_adopted_thread_handles.count() == 1) {
-            qt_adopted_thread_watcher_id = 0;
-            qt_adopted_thread_watcher_mutex.unlock();
-            break;
-        }
-
-        QVector<HANDLE> handlesCopy = qt_adopted_thread_handles;
-        qt_adopted_thread_watcher_mutex.unlock();
-
-        DWORD ret = WAIT_TIMEOUT;
-        int count;
-        int offset;
-        int loops = handlesCopy.size() / MAXIMUM_WAIT_OBJECTS;
-        if (handlesCopy.size() % MAXIMUM_WAIT_OBJECTS)
-            ++loops;
-        if (loops == 1) {
-            // no need to loop, no timeout
-            offset = 0;
-            count = handlesCopy.count();
-            ret = WaitForMultipleObjects(handlesCopy.count(), handlesCopy.constData(), false, INFINITE);
-        } else {
-            int loop = 0;
-            do {
-                offset = loop * MAXIMUM_WAIT_OBJECTS;
-                count = qMin(handlesCopy.count() - offset, MAXIMUM_WAIT_OBJECTS);
-                ret = WaitForMultipleObjects(count, handlesCopy.constData() + offset, false, 100);
-                loop = (loop + 1) % loops;
-            } while (ret == WAIT_TIMEOUT);
-        }
-
-        if (ret == WAIT_FAILED || ret >= WAIT_OBJECT_0 + uint(count)) {
-            qWarning("QThread internal error while waiting for adopted threads: %d", int(GetLastError()));
-            continue;
-        }
-
-        const int handleIndex = offset + ret - WAIT_OBJECT_0;
-        if (handleIndex == 0){
-            // New handle to watch was added.
-            continue;
-        } else {
-//             printf("(qt) - qt_adopted_thread_watcher_function... called\n");
-            const int qthreadIndex = handleIndex - 1;
-
-            qt_adopted_thread_watcher_mutex.lock();
-            QThreadData *data = QThreadData::get2(qt_adopted_qthreads.at(qthreadIndex));
-            qt_adopted_thread_watcher_mutex.unlock();
-            if (data->isAdopted) {
-                QThread *thread = data->thread;
-                Q_ASSERT(thread);
-                QThreadPrivate *thread_p = static_cast<QThreadPrivate *>(QObjectPrivate::get(thread));
-                Q_ASSERT(!thread_p->finished);
-                thread_p->finish(thread);
-            }
-            data->deref();
-
-            QMutexLocker lock(&qt_adopted_thread_watcher_mutex);
-#if !defined(Q_OS_WINCE) || (defined(_WIN32_WCE) && (_WIN32_WCE>=0x600))
-            CloseHandle(qt_adopted_thread_handles.at(handleIndex));
-#endif
-            qt_adopted_thread_handles.remove(handleIndex);
-            qt_adopted_qthreads.remove(qthreadIndex);
-        }
-    }
-
-    QThreadData *threadData = reinterpret_cast<QThreadData *>(TlsGetValue(qt_current_thread_data_tls_index));
-    if (threadData)
-        threadData->deref();
-
-    return 0;
-}
-
-#if !defined(QT_NO_DEBUG) && defined(Q_CC_MSVC) && !defined(Q_OS_WINCE)
-
-#ifndef Q_OS_WIN64
-#  define ULONG_PTR DWORD
-#endif
-
-typedef struct tagTHREADNAME_INFO
-{
-    DWORD dwType;      // must be 0x1000
-    LPCSTR szName;     // pointer to name (in user addr space)
-    HANDLE dwThreadID; // thread ID (-1=caller thread)
-    DWORD dwFlags;     // reserved for future use, must be zero
-} THREADNAME_INFO;
-
-void qt_set_thread_name(HANDLE threadId, LPCSTR threadName)
-{
-    THREADNAME_INFO info;
-    info.dwType = 0x1000;
-    info.szName = threadName;
-    info.dwThreadID = threadId;
-    info.dwFlags = 0;
-
-    __try
-    {
-        RaiseException(0x406D1388, 0, sizeof(info)/sizeof(DWORD), (const ULONG_PTR*)&info);
-    }
-    __except (EXCEPTION_CONTINUE_EXECUTION)
-    {
-    }
-}
-#endif // !QT_NO_DEBUG && Q_CC_MSVC && !Q_OS_WINCE
-
-/**************************************************************************
- ** QThreadPrivate
- *************************************************************************/
-
-#endif // QT_NO_THREAD
-
-void QThreadPrivate::createEventDispatcher(QThreadData *data)
-{
-    QMutexLocker l(&data->postEventList.mutex);
-    data->eventDispatcher = new QEventDispatcherWin32;
-    l.unlock();
-    data->eventDispatcher->startingUp();
-}
-
-#ifndef QT_NO_THREAD
-
-unsigned int __stdcall QT_ENSURE_STACK_ALIGNED_FOR_SSE QThreadPrivate::start(void *arg)
-{
-    QThread *thr = reinterpret_cast<QThread *>(arg);
-    QThreadData *data = QThreadData::get2(thr);
-
-    qt_create_tls();
-    TlsSetValue(qt_current_thread_data_tls_index, data);
-    data->threadId = reinterpret_cast<Qt::HANDLE>(GetCurrentThreadId());
-
-    QThread::setTerminationEnabled(false);
-
-    {
-        QMutexLocker locker(&thr->d_func()->mutex);
-        data->quitNow = thr->d_func()->exited;
-    }
-    // ### TODO: allow the user to create a custom event dispatcher
-    createEventDispatcher(data);
-
-#if !defined(QT_NO_DEBUG) && defined(Q_CC_MSVC) && !defined(Q_OS_WINCE)
-    // sets the name of the current thread.
-    QByteArray objectName = thr->objectName().toLocal8Bit();
-    qt_set_thread_name((HANDLE)-1,
-                       objectName.isEmpty() ?
-                       thr->metaObject()->className() : objectName.constData());
-#endif
-
-    emit thr->started();
-    QThread::setTerminationEnabled(true);
-    thr->run();
-
-    finish(arg);
-    return 0;
-}
-
-void QThreadPrivate::finish(void *arg, bool lockAnyway)
-{
-    QThread *thr = reinterpret_cast<QThread *>(arg);
-    QThreadPrivate *d = thr->d_func();
-
-    QMutexLocker locker(lockAnyway ? &d->mutex : 0);
-    d->isInFinish = true;
-    d->priority = QThread::InheritPriority;
-    bool terminated = d->terminated;
-    void **tls_data = reinterpret_cast<void **>(&d->data->tls);
-    locker.unlock();
-    if (terminated)
-        emit thr->terminated();
-    emit thr->finished();
-    QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
-    QThreadStorageData::finish(tls_data);
-    locker.relock();
-
-    d->terminated = false;
-
-    QAbstractEventDispatcher *eventDispatcher = d->data->eventDispatcher;
-    if (eventDispatcher) {
-        d->data->eventDispatcher = 0;
-        locker.unlock();
-        eventDispatcher->closingDown();
-        delete eventDispatcher;
-        locker.relock();
-    }
-
-    d->running = false;
-    d->finished = true;
-    d->isInFinish = false;
-
-    if (!d->waiters) {
-        CloseHandle(d->handle);
-        d->handle = 0;
-    }
-
-    d->id = 0;
-
-}
-
-/**************************************************************************
- ** QThread
- *************************************************************************/
-
-Qt::HANDLE QThread::currentThreadId()
-{
-    return reinterpret_cast<Qt::HANDLE>(GetCurrentThreadId());
-}
-
-int QThread::idealThreadCount()
-{
-    SYSTEM_INFO sysinfo;
-    GetSystemInfo(&sysinfo);
-    return sysinfo.dwNumberOfProcessors;
-}
-
-void QThread::yieldCurrentThread()
-{
-#ifndef Q_OS_WINCE
-    SwitchToThread();
-#else
-    ::Sleep(0);
-#endif
-}
-
-void QThread::sleep(unsigned long secs)
-{
-    ::Sleep(secs * 1000);
-}
-
-void QThread::msleep(unsigned long msecs)
-{
-    ::Sleep(msecs);
-}
-
-void QThread::usleep(unsigned long usecs)
-{
-    ::Sleep((usecs / 1000) + 1);
-}
-
-
-void QThread::start(Priority priority)
-{
-    Q_D(QThread);
-    QMutexLocker locker(&d->mutex);
-
-    if (d->isInFinish) {
-        locker.unlock();
-        wait();
-        locker.relock();
-    }
-
-    if (d->running)
-        return;
-
-    d->running = true;
-    d->finished = false;
-    d->terminated = false;
-    d->exited = false;
-    d->returnCode = 0;
-
-    /*
-      NOTE: we create the thread in the suspended state, set the
-      priority and then resume the thread.
-
-      since threads are created with normal priority by default, we
-      could get into a case where a thread (with priority less than
-      NormalPriority) tries to create a new thread (also with priority
-      less than NormalPriority), but the newly created thread preempts
-      its 'parent' and runs at normal priority.
-    */
-    d->handle = (Qt::HANDLE) _beginthreadex(NULL, d->stackSize, QThreadPrivate::start,
-                                            this, CREATE_SUSPENDED, &(d->id));
-
-    if (!d->handle) {
-        qErrnoWarning(errno, "QThread::start: Failed to create thread");
-        d->running = false;
-        d->finished = true;
-        return;
-    }
-
-    int prio;
-    d->priority = priority;
-    switch (d->priority) {
-    case IdlePriority:
-        prio = THREAD_PRIORITY_IDLE;
-        break;
-
-    case LowestPriority:
-        prio = THREAD_PRIORITY_LOWEST;
-        break;
-
-    case LowPriority:
-        prio = THREAD_PRIORITY_BELOW_NORMAL;
-        break;
-
-    case NormalPriority:
-        prio = THREAD_PRIORITY_NORMAL;
-        break;
-
-    case HighPriority:
-        prio = THREAD_PRIORITY_ABOVE_NORMAL;
-        break;
-
-    case HighestPriority:
-        prio = THREAD_PRIORITY_HIGHEST;
-        break;
-
-    case TimeCriticalPriority:
-        prio = THREAD_PRIORITY_TIME_CRITICAL;
-        break;
-
-    case InheritPriority:
-    default:
-        prio = GetThreadPriority(GetCurrentThread());
-        break;
-    }
-
-    if (!SetThreadPriority(d->handle, prio)) {
-        qErrnoWarning("QThread::start: Failed to set thread priority");
-    }
-
-    if (ResumeThread(d->handle) == (DWORD) -1) {
-        qErrnoWarning("QThread::start: Failed to resume new thread");
-    }
-}
-
-void QThread::terminate()
-{
-    Q_D(QThread);
-    QMutexLocker locker(&d->mutex);
-    if (!d->running)
-        return;
-    if (!d->terminationEnabled) {
-        d->terminatePending = true;
-        return;
-    }
-    TerminateThread(d->handle, 0);
-    d->terminated = true;
-    QThreadPrivate::finish(this, false);
-}
-
-bool QThread::wait(unsigned long time)
-{
-    Q_D(QThread);
-    QMutexLocker locker(&d->mutex);
-
-    if (d->id == GetCurrentThreadId()) {
-        qWarning("QThread::wait: Thread tried to wait on itself");
-        return false;
-    }
-    if (d->finished || !d->running)
-        return true;
-
-    ++d->waiters;
-    locker.mutex()->unlock();
-
-    bool ret = false;
-    switch (WaitForSingleObject(d->handle, time)) {
-    case WAIT_OBJECT_0:
-        ret = true;
-        break;
-    case WAIT_FAILED:
-        qErrnoWarning("QThread::wait: Thread wait failure");
-        break;
-    case WAIT_ABANDONED:
-    case WAIT_TIMEOUT:
-    default:
-        break;
-    }
-
-    locker.mutex()->lock();
-    --d->waiters;
-
-    if (ret && !d->finished) {
-        // thread was terminated by someone else
-        d->terminated = true;
-        QThreadPrivate::finish(this, false);
-    }
-
-    if (d->finished && !d->waiters) {
-        CloseHandle(d->handle);
-        d->handle = 0;
-    }
-
-    return ret;
-}
-
-void QThread::setTerminationEnabled(bool enabled)
-{
-    QThread *thr = currentThread();
-    Q_ASSERT_X(thr != 0, "QThread::setTerminationEnabled()",
-               "Current thread was not started with QThread.");
-    QThreadPrivate *d = thr->d_func();
-    QMutexLocker locker(&d->mutex);
-    d->terminationEnabled = enabled;
-    if (enabled && d->terminatePending) {
-        d->terminated = true;
-        QThreadPrivate::finish(thr, false);
-        locker.unlock(); // don't leave the mutex locked!
-        _endthreadex(0);
-    }
-}
-
-void QThread::setPriority(Priority priority)
-{
-    Q_D(QThread);
-    QMutexLocker locker(&d->mutex);
-    if (!d->running) {
-        qWarning("QThread::setPriority: Cannot set priority, thread is not running");
-        return;
-    }
-
-    // copied from start() with a few modifications:
-
-    int prio;
-    d->priority = priority;
-    switch (d->priority) {
-    case IdlePriority:
-        prio = THREAD_PRIORITY_IDLE;
-        break;
-
-    case LowestPriority:
-        prio = THREAD_PRIORITY_LOWEST;
-        break;
-
-    case LowPriority:
-        prio = THREAD_PRIORITY_BELOW_NORMAL;
-        break;
-
-    case NormalPriority:
-        prio = THREAD_PRIORITY_NORMAL;
-        break;
-
-    case HighPriority:
-        prio = THREAD_PRIORITY_ABOVE_NORMAL;
-        break;
-
-    case HighestPriority:
-        prio = THREAD_PRIORITY_HIGHEST;
-        break;
-
-    case TimeCriticalPriority:
-        prio = THREAD_PRIORITY_TIME_CRITICAL;
-        break;
-
-    case InheritPriority:
-    default:
-        qWarning("QThread::setPriority: Argument cannot be InheritPriority");
-        return;
-    }
-
-    if (!SetThreadPriority(d->handle, prio)) {
-        qErrnoWarning("QThread::setPriority: Failed to set thread priority");
-    }
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qthread.h"
-
-#endif // QT_NO_THREAD
diff --git a/src/core/thread/qwaitcondition_win.cpp b/src/core/thread/qwaitcondition_win.cpp
deleted file mode 100644 (file)
index 6e454c0..0000000
+++ /dev/null
@@ -1,233 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwaitcondition.h"
-#include "qnamespace.h"
-#include "qmutex.h"
-#include "qreadwritelock.h"
-#include "qlist.h"
-#include "qalgorithms.h"
-#include "qt_windows.h"
-
-#ifndef QT_NO_THREAD
-
-#define Q_MUTEX_T void*
-#include <qmutex_p.h>
-#include <qreadwritelock_p.h>
-
-QT_BEGIN_NAMESPACE
-
-//***********************************************************************
-// QWaitConditionPrivate
-// **********************************************************************
-
-class QWaitConditionEvent
-{
-public:
-    inline QWaitConditionEvent() : priority(0), wokenUp(false)
-    {
-        event = CreateEvent(NULL, TRUE, FALSE, NULL);
-    }
-    inline ~QWaitConditionEvent() { CloseHandle(event); }
-    int priority;
-    bool wokenUp;
-    HANDLE event;
-};
-
-typedef QList<QWaitConditionEvent *> EventQueue;
-
-class QWaitConditionPrivate
-{
-public:
-    QMutex mtx;
-    EventQueue queue;
-    EventQueue freeQueue;
-
-    QWaitConditionEvent *pre();
-    bool wait(QWaitConditionEvent *wce, unsigned long time);
-    void post(QWaitConditionEvent *wce, bool ret);
-};
-
-QWaitConditionEvent *QWaitConditionPrivate::pre()
-{
-    mtx.lock();
-    QWaitConditionEvent *wce =
-        freeQueue.isEmpty() ? new QWaitConditionEvent : freeQueue.takeFirst();
-    wce->priority = GetThreadPriority(GetCurrentThread());
-    wce->wokenUp = false;
-
-    // insert 'wce' into the queue (sorted by priority)
-    int index = 0;
-    for (; index < queue.size(); ++index) {
-        QWaitConditionEvent *current = queue.at(index);
-        if (current->priority < wce->priority)
-            break;
-    }
-    queue.insert(index, wce);
-    mtx.unlock();
-
-    return wce;
-}
-
-bool QWaitConditionPrivate::wait(QWaitConditionEvent *wce, unsigned long time)
-{
-    // wait for the event
-    bool ret = false;
-    switch (WaitForSingleObject(wce->event, time)) {
-    default: break;
-
-    case WAIT_OBJECT_0:
-        ret = true;
-        break;
-    }
-    return ret;
-}
-
-void QWaitConditionPrivate::post(QWaitConditionEvent *wce, bool ret)
-{
-    mtx.lock();
-
-    // remove 'wce' from the queue
-    queue.removeAll(wce);
-    ResetEvent(wce->event);
-    freeQueue.append(wce);
-
-    // wakeups delivered after the timeout should be forwarded to the next waiter
-    if (!ret && wce->wokenUp && !queue.isEmpty()) {
-        QWaitConditionEvent *other = queue.first();
-        SetEvent(other->event);
-        other->wokenUp = true;
-    }
-
-    mtx.unlock();
-}
-
-//***********************************************************************
-// QWaitCondition implementation
-//***********************************************************************
-
-QWaitCondition::QWaitCondition()
-{
-    d = new QWaitConditionPrivate;
-}
-
-QWaitCondition::~QWaitCondition()
-{
-    if (!d->queue.isEmpty()) {
-        qWarning("QWaitCondition: Destroyed while threads are still waiting");
-        qDeleteAll(d->queue);
-    }
-
-    qDeleteAll(d->freeQueue);
-    delete d;
-}
-
-bool QWaitCondition::wait(QMutex *mutex, unsigned long time)
-{
-    if (!mutex)
-        return false;
-    if (mutex->d->recursive) {
-        qWarning("QWaitCondition::wait: Cannot wait on recursive mutexes");
-        return false;
-    }
-
-    QWaitConditionEvent *wce = d->pre();
-    mutex->unlock();
-
-    bool returnValue = d->wait(wce, time);
-
-    mutex->lock();
-    d->post(wce, returnValue);
-
-    return returnValue;
-}
-
-bool QWaitCondition::wait(QReadWriteLock *readWriteLock, unsigned long time)
-{
-    if (!readWriteLock || readWriteLock->d->accessCount == 0)
-        return false;
-    if (readWriteLock->d->accessCount < -1) {
-        qWarning("QWaitCondition: cannot wait on QReadWriteLocks with recursive lockForWrite()");
-        return false;
-    }
-
-    QWaitConditionEvent *wce = d->pre();
-    int previousAccessCount = readWriteLock->d->accessCount;
-    readWriteLock->unlock();
-
-    bool returnValue = d->wait(wce, time);
-
-    if (previousAccessCount < 0)
-        readWriteLock->lockForWrite();
-    else
-        readWriteLock->lockForRead();
-    d->post(wce, returnValue);
-
-    return returnValue;
-}
-
-void QWaitCondition::wakeOne()
-{
-    // wake up the first waiting thread in the queue
-    QMutexLocker locker(&d->mtx);
-    for (int i = 0; i < d->queue.size(); ++i) {
-        QWaitConditionEvent *current = d->queue.at(i);
-        if (current->wokenUp)
-            continue;
-        SetEvent(current->event);
-        current->wokenUp = true;
-        break;
-    }
-}
-
-void QWaitCondition::wakeAll()
-{
-    // wake up the all threads in the queue
-    QMutexLocker locker(&d->mtx);
-    for (int i = 0; i < d->queue.size(); ++i) {
-        QWaitConditionEvent *current = d->queue.at(i);
-        SetEvent(current->event);
-        current->wokenUp = true;
-    }
-}
-
-QT_END_NAMESPACE
-#endif // QT_NO_THREAD
diff --git a/src/core/tools/qelapsedtimer_mac.cpp b/src/core/tools/qelapsedtimer_mac.cpp
deleted file mode 100644 (file)
index 1aad754..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qelapsedtimer.h"
-#include <sys/time.h>
-#include <unistd.h>
-
-#include <mach/mach_time.h>
-
-QT_BEGIN_NAMESPACE
-
-QElapsedTimer::ClockType QElapsedTimer::clockType()
-{
-    return MachAbsoluteTime;
-}
-
-bool QElapsedTimer::isMonotonic()
-{
-    return true;
-}
-
-static mach_timebase_info_data_t info = {0,0};
-static qint64 absoluteToNSecs(qint64 cpuTime)
-{
-    if (info.denom == 0)
-        mach_timebase_info(&info);
-    qint64 nsecs = cpuTime * info.numer / info.denom;
-    return nsecs;
-}
-
-static qint64 absoluteToMSecs(qint64 cpuTime)
-{
-    return absoluteToNSecs(cpuTime) / 1000000;
-}
-
-timeval qt_gettime()
-{
-    timeval tv;
-
-    uint64_t cpu_time = mach_absolute_time();
-    uint64_t nsecs = absoluteToNSecs(cpu_time);
-    tv.tv_sec = nsecs / 1000000000ull;
-    tv.tv_usec = (nsecs / 1000) - (tv.tv_sec * 1000000);
-    return tv;
-}
-
-void QElapsedTimer::start()
-{
-    t1 = mach_absolute_time();
-    t2 = 0;
-}
-
-qint64 QElapsedTimer::restart()
-{
-    qint64 old = t1;
-    t1 = mach_absolute_time();
-    t2 = 0;
-
-    return absoluteToMSecs(t1 - old);
-}
-
-qint64 QElapsedTimer::nsecsElapsed() const
-{
-    uint64_t cpu_time = mach_absolute_time();
-    return absoluteToNSecs(cpu_time - t1);
-}
-
-qint64 QElapsedTimer::elapsed() const
-{
-    uint64_t cpu_time = mach_absolute_time();
-    return absoluteToMSecs(cpu_time - t1);
-}
-
-qint64 QElapsedTimer::msecsSinceReference() const
-{
-    return absoluteToMSecs(t1);
-}
-
-qint64 QElapsedTimer::msecsTo(const QElapsedTimer &other) const
-{
-    return absoluteToMSecs(other.t1 - t1);
-}
-
-qint64 QElapsedTimer::secsTo(const QElapsedTimer &other) const
-{
-    return msecsTo(other) / 1000;
-}
-
-bool operator<(const QElapsedTimer &v1, const QElapsedTimer &v2)
-{
-    return v1.t1 < v2.t1;
-}
-
-QT_END_NAMESPACE
diff --git a/src/core/tools/qelapsedtimer_win.cpp b/src/core/tools/qelapsedtimer_win.cpp
deleted file mode 100644 (file)
index 2923872..0000000
+++ /dev/null
@@ -1,183 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qelapsedtimer.h"
-#include <windows.h>
-
-#include <qsystemlibrary_p.h>
-
-typedef ULONGLONG (WINAPI *PtrGetTickCount64)(void);
-static PtrGetTickCount64 ptrGetTickCount64 = 0;
-
-QT_BEGIN_NAMESPACE
-
-// Result of QueryPerformanceFrequency, 0 indicates that the high resolution timer is unavailable
-static quint64 counterFrequency = 0;
-
-static void resolveLibs()
-{
-    static volatile bool done = false;
-    if (done)
-        return;
-
-    // try to get GetTickCount64 from the system
-    QSystemLibrary kernel32(QLatin1String("kernel32"));
-    if (!kernel32.load())
-        return;
-
-    // does this function exist on WinCE, or will ever exist?
-    ptrGetTickCount64 = (PtrGetTickCount64)kernel32.resolve("GetTickCount64");
-
-    // Retrieve the number of high-resolution performance counter ticks per second
-    LARGE_INTEGER frequency;
-    if (!QueryPerformanceFrequency(&frequency)) {
-        counterFrequency = 0;
-    } else {
-        counterFrequency = frequency.QuadPart;
-    }
-
-    done = true;
-}
-
-static inline qint64 ticksToNanoseconds(qint64 ticks)
-{
-    if (counterFrequency > 0) {
-        // QueryPerformanceCounter uses an arbitrary frequency
-        qint64 seconds = ticks / counterFrequency;
-        qint64 nanoSeconds = (ticks - seconds * counterFrequency) * 1000000000 / counterFrequency;
-        return seconds * 1000000000 + nanoSeconds;
-    } else {
-        // GetTickCount(64) return milliseconds
-        return ticks * 1000000;
-    }
-}
-
-static quint64 getTickCount()
-{
-    resolveLibs();
-
-    // This avoids a division by zero and disables the high performance counter if it's not available
-    if (counterFrequency > 0) {
-        LARGE_INTEGER counter;
-
-        if (QueryPerformanceCounter(&counter)) {
-            return counter.QuadPart;
-        } else {
-            qWarning("QueryPerformanceCounter failed, although QueryPerformanceFrequency succeeded.");
-            return 0;
-        }
-    }
-
-    if (ptrGetTickCount64)
-        return ptrGetTickCount64();
-
-    static quint32 highdword = 0;
-    static quint32 lastval = 0;
-    quint32 val = GetTickCount();
-    if (val < lastval)
-        ++highdword;
-    lastval = val;
-    return val | (quint64(highdword) << 32);
-}
-
-QElapsedTimer::ClockType QElapsedTimer::clockType()
-{
-    resolveLibs();
-
-    if (counterFrequency > 0)
-        return PerformanceCounter;
-    else
-        return TickCounter;
-}
-
-bool QElapsedTimer::isMonotonic()
-{
-    return true;
-}
-
-void QElapsedTimer::start()
-{
-    t1 = getTickCount();
-    t2 = 0;
-}
-
-qint64 QElapsedTimer::restart()
-{
-    qint64 oldt1 = t1;
-    t1 = getTickCount();
-    t2 = 0;
-    return ticksToNanoseconds(t1 - oldt1) / 1000000;
-}
-
-qint64 QElapsedTimer::nsecsElapsed() const
-{
-    qint64 elapsed = getTickCount() - t1;
-    return ticksToNanoseconds(elapsed);
-}
-
-qint64 QElapsedTimer::elapsed() const
-{
-    qint64 elapsed = getTickCount() - t1;
-    return ticksToNanoseconds(elapsed) / 1000000;
-}
-
-qint64 QElapsedTimer::msecsSinceReference() const
-{
-    return ticksToNanoseconds(t1) / 1000000;
-}
-
-qint64 QElapsedTimer::msecsTo(const QElapsedTimer &other) const
-{
-    qint64 difference = other.t1 - t1;
-    return ticksToNanoseconds(difference) / 1000000;
-}
-
-qint64 QElapsedTimer::secsTo(const QElapsedTimer &other) const
-{
-    return msecsTo(other) / 1000;
-}
-
-bool operator<(const QElapsedTimer &v1, const QElapsedTimer &v2)
-{
-    return (v1.t1 - v2.t1) < 0;
-}
-
-QT_END_NAMESPACE
diff --git a/src/core/tools/qlocale_blackberry.cpp b/src/core/tools/qlocale_blackberry.cpp
deleted file mode 100644 (file)
index 1e4a480..0000000
+++ /dev/null
@@ -1,343 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qlocale_blackberry.h"
-#include "qlocale_p.h"
-
-#include "qdatetime.h"
-
-#include "qcoreapplication.h"
-#include "qcore_unix_p.h"
-
-#include <errno.h>
-#include <sys/pps.h>
-#include <unistd.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_SYSTEMLOCALE
-
-static const char ppsUomPath[] = "/pps/services/locale/uom";
-static const char ppsRegionLocalePath[] = "/pps/services/locale/settings";
-static const char ppsLanguageLocalePath[] = "/pps/services/confstr/_CS_LOCALE";
-static const char ppsHourFormatPath[] = "/pps/system/settings";
-
-static const int MAX_PPS_SIZE = 16000;
-
-QBBSystemLocaleData::QBBSystemLocaleData()
-    : languageNotifier(0)
-    , regionNotifier(0)
-    , measurementNotifier(0)
-    , hourNotifier(0)
-{
-    // Do not use qWarning to log warnings if qt_safe_open fails to open the pps file
-    // since the user code may install a message handler that invokes QLocale API again
-    // (i.e QDate, QDateTime, ...) which will cause an infinite loop.
-    if ((measurementFd = qt_safe_open(ppsUomPath, O_RDONLY)) == -1)
-        fprintf(stderr, "Failed to open uom pps, errno=%d\n", errno);
-
-    if ((regionFd = qt_safe_open(ppsRegionLocalePath, O_RDONLY)) == -1)
-        fprintf(stderr, "Failed to open region pps, errno=%d\n", errno);
-
-    if ((languageFd = qt_safe_open(ppsLanguageLocalePath, O_RDONLY)) == -1)
-        fprintf(stderr, "Failed to open language pps, errno=%d\n", errno);
-
-    if ((hourFd = qt_safe_open(ppsHourFormatPath, O_RDONLY)) == -1)
-       fprintf(stderr, "Failed to open hour format pps, errno=%d\n", errno);
-
-    // we cannot call this directly, because by the time this constructor is
-    // called, the event dispatcher has not yet been created, causing the
-    // subsequent call to QSocketNotifier constructor to fail.
-    QMetaObject::invokeMethod(this, "installSocketNotifiers", Qt::QueuedConnection);
-
-    readLangageLocale();
-    readRegionLocale();
-    readMeasurementSystem();
-    readHourFormat();
-}
-
-QBBSystemLocaleData::~QBBSystemLocaleData()
-{
-    if (measurementFd != -1)
-        qt_safe_close(measurementFd);
-
-    if (languageFd != -1)
-        qt_safe_close(languageFd);
-
-    if (regionFd != -1)
-        qt_safe_close(regionFd);
-
-    if (hourFd != -1)
-        qt_safe_close(hourFd);
-}
-
-uint QBBSystemLocaleData::measurementSystem()
-{
-    return m_measurementSystem;
-}
-
-QVariant QBBSystemLocaleData::timeFormat(QLocale::FormatType formatType)
-{
-    return getCorrectFormat(regionLocale().timeFormat(formatType), formatType);
-}
-
-QVariant QBBSystemLocaleData::dateTimeFormat(QLocale::FormatType formatType)
-{
-    return getCorrectFormat(regionLocale().dateTimeFormat(formatType), formatType);
-}
-
-QLocale QBBSystemLocaleData::languageLocale()
-{
-    if (!lc_langage.isEmpty())
-        return QLocale(QLatin1String(lc_langage));
-
-    return QLocale::c();
-}
-
-QLocale QBBSystemLocaleData::regionLocale()
-{
-    if (!lc_region.isEmpty())
-        return QLocale(QLatin1String(lc_region));
-
-    return QLocale::c();
-}
-
-void QBBSystemLocaleData::installSocketNotifiers()
-{
-    Q_ASSERT(!languageNotifier || !regionNotifier || !measurementNotifier || !hourNotifier);
-    Q_ASSERT(QCoreApplication::instance());
-
-    languageNotifier = new QSocketNotifier(languageFd, QSocketNotifier::Read, this);
-    QObject::connect(languageNotifier, SIGNAL(activated(int)), this, SLOT(readLangageLocale()));
-
-    regionNotifier = new QSocketNotifier(regionFd, QSocketNotifier::Read, this);
-    QObject::connect(regionNotifier, SIGNAL(activated(int)), this, SLOT(readRegionLocale()));
-
-    measurementNotifier = new QSocketNotifier(measurementFd, QSocketNotifier::Read, this);
-    QObject::connect(measurementNotifier, SIGNAL(activated(int)), this, SLOT(readMeasurementSystem()));
-
-    hourNotifier = new QSocketNotifier(hourFd, QSocketNotifier::Read, this);
-    QObject::connect(hourNotifier, SIGNAL(activated(int)), this, SLOT(readHourFormat()));
-}
-
-void QBBSystemLocaleData::readLangageLocale()
-{
-    lc_langage = readPpsValue("_CS_LOCALE", languageFd);
-}
-
-void QBBSystemLocaleData::readRegionLocale()
-{
-    lc_region = readPpsValue("region", regionFd);
-}
-
-void QBBSystemLocaleData::readMeasurementSystem()
-{
-    QByteArray measurement = readPpsValue("uom", measurementFd);
-    m_measurementSystem = (qstrcmp(measurement, "imperial") == 0) ? QLocale::ImperialSystem : QLocale::MetricSystem;
-}
-
-void QBBSystemLocaleData::readHourFormat()
-{
-    QByteArray hourFormat = readPpsValue("hourFormat", hourFd);
-    is24HourFormat = (qstrcmp(hourFormat, "24") == 0);
-}
-
-QByteArray QBBSystemLocaleData::readPpsValue(const char *ppsObject, int ppsFd)
-{
-    QByteArray result;
-    if (!ppsObject || ppsFd == -1)
-        return result;
-
-
-    // PPS objects are of unknown size, but must be read all at once.
-    // Relying on the file size may not be a good idea since the size may change before reading.
-    // Let's try with an initial size (512), and if the buffer is too small try with bigger one,
-    // until we succeed or until other non buffer-size-related error occurs.
-    // Using QVarLengthArray means the first try (of size == 512) uses a buffer on the stack - no allocation necessary.
-     // Hopefully that covers most use cases.
-    int bytes;
-    QVarLengthArray<char, 512> buffer;
-    for (;;) {
-        errno = 0;
-        bytes = qt_safe_read(ppsFd, buffer.data(), buffer.capacity() - 1);
-        const bool bufferIsTooSmall = (bytes == -1 && errno == EMSGSIZE && buffer.capacity() < MAX_PPS_SIZE);
-        if (!bufferIsTooSmall)
-            break;
-
-        buffer.resize(qMin(buffer.capacity()*2, MAX_PPS_SIZE));
-    }
-
-    // This method is called in the ctor(), so do not use qWarning to log warnings
-    // if qt_safe_read fails to read the pps file
-    // since the user code may install a message handler that invokes QLocale API again
-    // (i.e QDate, QDateTime, ...) which will cause a infinite loop.
-    if (bytes == -1) {
-        fprintf(stderr, "Failed to read pps object:%s, errno=%d\n", ppsObject, errno);
-        return result;
-    }
-    // ensure data is null terminated
-    buffer[bytes] = '\0';
-
-    pps_decoder_t ppsDecoder;
-    pps_decoder_initialize(&ppsDecoder, 0);
-    if (pps_decoder_parse_pps_str(&ppsDecoder, buffer.data()) == PPS_DECODER_OK) {
-        pps_decoder_push(&ppsDecoder, 0);
-        const char *ppsBuff;
-        if (pps_decoder_get_string(&ppsDecoder, ppsObject, &ppsBuff) == PPS_DECODER_OK) {
-            result = ppsBuff;
-        } else {
-            int val;
-            if (pps_decoder_get_int(&ppsDecoder, ppsObject, &val) == PPS_DECODER_OK)
-                result = QByteArray::number(val);
-        }
-    }
-
-    pps_decoder_cleanup(&ppsDecoder);
-
-    return result;
-}
-
-QString QBBSystemLocaleData::getCorrectFormat(const QString &baseFormat, QLocale::FormatType formatType)
-{
-    QString format = baseFormat;
-    if (is24HourFormat) {
-        if (format.contains(QLatin1String("AP"), Qt::CaseInsensitive)) {
-            format.replace(QLatin1String("AP"), QLatin1String(""), Qt::CaseInsensitive);
-            format.replace(QLatin1String("h"), QLatin1String("H"), Qt::CaseSensitive);
-        }
-
-    } else {
-
-        if (!format.contains(QLatin1String("AP"), Qt::CaseInsensitive)) {
-            format.contains(QLatin1String("HH"), Qt::CaseSensitive) ?
-                format.replace(QLatin1String("HH"), QLatin1String("hh"), Qt::CaseSensitive) :
-                format.replace(QLatin1String("H"), QLatin1String("h"), Qt::CaseSensitive);
-
-            formatType == QLocale::LongFormat ? format.append(QLatin1String(" AP t")) : format.append(QLatin1String(" AP"));
-        }
-    }
-
-    return format;
-}
-
-Q_GLOBAL_STATIC(QBBSystemLocaleData, bbSysLocaleData)
-
-QLocale QSystemLocale::fallbackLocale() const
-{
-    return bbSysLocaleData()->languageLocale();
-}
-
-QVariant QSystemLocale::query(QueryType type, QVariant in) const
-{
-    QBBSystemLocaleData *d = bbSysLocaleData();
-
-    QReadLocker locker(&d->lock);
-
-    const QLocale &lc_language = d->languageLocale();
-    const QLocale &lc_region = d->regionLocale();
-
-    switch (type) {
-    case DecimalPoint:
-        return lc_region.decimalPoint();
-    case GroupSeparator:
-        return lc_region.groupSeparator();
-    case NegativeSign:
-        return lc_region.negativeSign();
-    case PositiveSign:
-        return lc_region.positiveSign();
-    case DateFormatLong:
-        return lc_region.dateFormat(QLocale::LongFormat);
-    case DateFormatShort:
-        return lc_region.dateFormat(QLocale::ShortFormat);
-    case TimeFormatLong:
-        return d->timeFormat(QLocale::LongFormat);
-    case TimeFormatShort:
-        return d->timeFormat(QLocale::ShortFormat);
-    case DateTimeFormatLong:
-        return d->dateTimeFormat(QLocale::LongFormat);
-    case DateTimeFormatShort:
-        return d->dateTimeFormat(QLocale::ShortFormat);
-    case DayNameLong:
-        return lc_language.dayName(in.toInt(), QLocale::LongFormat);
-    case DayNameShort:
-        return lc_language.dayName(in.toInt(), QLocale::ShortFormat);
-    case MonthNameLong:
-        return lc_language.monthName(in.toInt(), QLocale::LongFormat);
-    case MonthNameShort:
-        return lc_language.monthName(in.toInt(), QLocale::ShortFormat);
-    case StandaloneMonthNameLong:
-         return lc_language.standaloneMonthName(in.toInt(), QLocale::LongFormat);
-    case StandaloneMonthNameShort:
-         return lc_language.standaloneMonthName(in.toInt(), QLocale::ShortFormat);
-    case DateToStringLong:
-        return lc_region.toString(in.toDate(), QLocale::LongFormat);
-    case DateToStringShort:
-        return lc_region.toString(in.toDate(), QLocale::ShortFormat);
-    case TimeToStringLong:
-        return lc_region.toString(in.toTime(), d->timeFormat(QLocale::LongFormat).toString());
-    case TimeToStringShort:
-        return lc_region.toString(in.toTime(), d->timeFormat(QLocale::ShortFormat).toString());
-    case DateTimeToStringShort:
-        return lc_region.toString(in.toDateTime(), d->dateTimeFormat(QLocale::ShortFormat).toString());
-    case DateTimeToStringLong:
-        return lc_region.toString(in.toDateTime(), d->dateTimeFormat(QLocale::LongFormat).toString());
-    case MeasurementSystem:
-        return d->measurementSystem();
-    case ZeroDigit:
-        return lc_region.zeroDigit();
-    case CountryId:
-        return lc_region.country();
-    case LanguageId:
-        return lc_language.language();
-    case AMText:
-        return lc_language.amText();
-    case PMText:
-        return lc_language.pmText();
-    default:
-        break;
-    }
-    return QVariant();
-}
-
-#endif
-
-QT_END_NAMESPACE
-#include "moc_qlocale_blackberry.h"
diff --git a/src/core/tools/qlocale_blackberry.h b/src/core/tools/qlocale_blackberry.h
deleted file mode 100644 (file)
index ba79ed2..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QLOCALE_BLACKBERRY_H
-#define QLOCALE_BLACKBERRY_H
-
-#include "qsocketnotifier.h"
-#include "qreadwritelock.h"
-#include "qlocale.h"
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-
-#ifndef QT_NO_SYSTEMLOCALE
-
-class QBBSystemLocaleData : public QObject
-{
-    Q_OBJECT
-
-public:
-    QBBSystemLocaleData();
-    virtual ~QBBSystemLocaleData();
-    uint measurementSystem();
-    QVariant timeFormat(QLocale::FormatType);
-    QVariant dateTimeFormat(QLocale::FormatType);
-    QLocale languageLocale();
-    QLocale regionLocale();
-
-    QReadWriteLock lock;
-
-public Q_SLOTS:
-    void installSocketNotifiers();
-    void readLangageLocale();
-    void readRegionLocale();
-    void readMeasurementSystem();
-    void readHourFormat();
-
-private:
-    QByteArray readPpsValue(const char *ppsObject, int ppsFd);
-    QString getCorrectFormat(const QString &baseFormat, QLocale::FormatType typeFormat);
-
-    QByteArray lc_langage;
-    QByteArray lc_region;
-    uint m_measurementSystem;
-    bool is24HourFormat;
-
-    QSocketNotifier *languageNotifier;
-    QSocketNotifier *regionNotifier;
-    QSocketNotifier *measurementNotifier;
-    QSocketNotifier *hourNotifier;
-
-    int languageFd;
-    int regionFd;
-    int measurementFd;
-    int hourFd;
-};
-#endif // QT_NO_SYSTEMLOCALE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QLOCALE_BLACKBERRY_H
-
diff --git a/src/core/tools/qlocale_mac.mm b/src/core/tools/qlocale_mac.mm
deleted file mode 100644 (file)
index 3e9d75f..0000000
+++ /dev/null
@@ -1,519 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qlocale_p.h"
-
-#include "qstringlist.h"
-#include "qvariant.h"
-#include "qdatetime.h"
-
-#if !defined(QWS) && defined(Q_OS_MAC)
-#   include "qcore_mac_p.h"
-#   include <CoreFoundation/CoreFoundation.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-/******************************************************************************
-** Wrappers for Mac locale system functions
-*/
-
-#ifndef QT_NO_SYSTEMLOCALE
-static QByteArray envVarLocale()
-{
-    static QByteArray lang = 0;
-#ifdef Q_OS_UNIX
-    lang = qgetenv("LC_ALL");
-    if (lang.isEmpty())
-        lang = qgetenv("LC_NUMERIC");
-    if (lang.isEmpty())
-#endif
-        lang = qgetenv("LANG");
-    return lang;
-}
-
-static QByteArray getMacLocaleName()
-{
-    QByteArray result = envVarLocale();
-
-    QString lang, script, cntry;
-    if (result.isEmpty() || result != "C"
-            && !qt_splitLocaleName(QString::fromLocal8Bit(result), lang, script, cntry)) {
-        QCFType<CFLocaleRef> l = CFLocaleCopyCurrent();
-        CFStringRef locale = CFLocaleGetIdentifier(l);
-        result = QCFString::toQString(locale).toUtf8();
-    }
-    return result;
-}
-
-static QString macMonthName(int month, bool short_format)
-{
-    month -= 1;
-    if (month < 0 || month > 11)
-        return QString();
-
-    QCFType<CFDateFormatterRef> formatter
-        = CFDateFormatterCreate(0, QCFType<CFLocaleRef>(CFLocaleCopyCurrent()),
-                                kCFDateFormatterNoStyle,  kCFDateFormatterNoStyle);
-    QCFType<CFArrayRef> values
-        = static_cast<CFArrayRef>(CFDateFormatterCopyProperty(formatter,
-                                  short_format ? kCFDateFormatterShortMonthSymbols
-                                               : kCFDateFormatterMonthSymbols));
-    if (values != 0) {
-        CFStringRef cfstring = static_cast<CFStringRef>(CFArrayGetValueAtIndex(values, month));
-        return QCFString::toQString(cfstring);
-    }
-    return QString();
-}
-
-static QString macDayName(int day, bool short_format)
-{
-    if (day < 1 || day > 7)
-        return QString();
-
-    QCFType<CFDateFormatterRef> formatter
-        = CFDateFormatterCreate(0, QCFType<CFLocaleRef>(CFLocaleCopyCurrent()),
-                                kCFDateFormatterNoStyle,  kCFDateFormatterNoStyle);
-    QCFType<CFArrayRef> values = static_cast<CFArrayRef>(CFDateFormatterCopyProperty(formatter,
-                                            short_format ? kCFDateFormatterShortWeekdaySymbols
-                                                         : kCFDateFormatterWeekdaySymbols));
-    if (values != 0) {
-        CFStringRef cfstring = static_cast<CFStringRef>(CFArrayGetValueAtIndex(values, day % 7));
-        return QCFString::toQString(cfstring);
-    }
-    return QString();
-}
-
-static QString macDateToString(const QDate &date, bool short_format)
-{
-    CFGregorianDate macGDate;
-    macGDate.year = date.year();
-    macGDate.month = date.month();
-    macGDate.day = date.day();
-    macGDate.hour = 0;
-    macGDate.minute = 0;
-    macGDate.second = 0.0;
-    QCFType<CFDateRef> myDate
-        = CFDateCreate(0, CFGregorianDateGetAbsoluteTime(macGDate,
-                                                         QCFType<CFTimeZoneRef>(CFTimeZoneCopyDefault())));
-    QCFType<CFLocaleRef> mylocale = CFLocaleCopyCurrent();
-    CFDateFormatterStyle style = short_format ? kCFDateFormatterShortStyle : kCFDateFormatterLongStyle;
-    QCFType<CFDateFormatterRef> myFormatter
-        = CFDateFormatterCreate(kCFAllocatorDefault,
-                                mylocale, style,
-                                kCFDateFormatterNoStyle);
-    return QCFString(CFDateFormatterCreateStringWithDate(0, myFormatter, myDate));
-}
-
-static QString macTimeToString(const QTime &time, bool short_format)
-{
-    CFGregorianDate macGDate;
-    // Assume this is local time and the current date
-    QDate dt = QDate::currentDate();
-    macGDate.year = dt.year();
-    macGDate.month = dt.month();
-    macGDate.day = dt.day();
-    macGDate.hour = time.hour();
-    macGDate.minute = time.minute();
-    macGDate.second = time.second();
-    QCFType<CFDateRef> myDate
-        = CFDateCreate(0, CFGregorianDateGetAbsoluteTime(macGDate,
-                                                         QCFType<CFTimeZoneRef>(CFTimeZoneCopyDefault())));
-
-    QCFType<CFLocaleRef> mylocale = CFLocaleCopyCurrent();
-    CFDateFormatterStyle style = short_format ? kCFDateFormatterShortStyle :  kCFDateFormatterLongStyle;
-    QCFType<CFDateFormatterRef> myFormatter = CFDateFormatterCreate(kCFAllocatorDefault,
-                                                                    mylocale,
-                                                                    kCFDateFormatterNoStyle,
-                                                                    style);
-    return QCFString(CFDateFormatterCreateStringWithDate(0, myFormatter, myDate));
-}
-
-// Mac uses the Unicode CLDR format codes
-// http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
-// See also qtbase/util/local_database/dateconverter.py
-// Makes the assumption that input formats are always well formed and consecutive letters
-// never exceed the maximum for the format code.
-static QString macToQtFormat(const QString &sys_fmt)
-{
-    QString result;
-    int i = 0;
-
-    while (i < sys_fmt.size()) {
-        if (sys_fmt.at(i).unicode() == '\'') {
-            QString text = qt_readEscapedFormatString(sys_fmt, &i);
-            if (text == QLatin1String("'"))
-                result += QLatin1String("''");
-            else
-                result += QLatin1Char('\'') + text + QLatin1Char('\'');
-            continue;
-        }
-
-        QChar c = sys_fmt.at(i);
-        int repeat = qt_repeatCount(sys_fmt, i);
-
-        switch (c.unicode()) {
-            // Qt does not support the following options
-            case 'G': // Era (1..5): 4 = long, 1..3 = short, 5 = narrow
-            case 'Y': // Year of Week (1..n): 1..n = padded number
-            case 'U': // Cyclic Year Name (1..5): 4 = long, 1..3 = short, 5 = narrow
-            case 'Q': // Quarter (1..4): 4 = long, 3 = short, 1..2 = padded number
-            case 'q': // Standalone Quarter (1..4): 4 = long, 3 = short, 1..2 = padded number
-            case 'w': // Week of Year (1..2): 1..2 = padded number
-            case 'W': // Week of Month (1): 1 = number
-            case 'D': // Day of Year (1..3): 1..3 = padded number
-            case 'F': // Day of Week in Month (1): 1 = number
-            case 'g': // Modified Julian Day (1..n): 1..n = padded number
-            case 'A': // Milliseconds in Day (1..n): 1..n = padded number
-                break;
-
-            case 'y': // Year (1..n): 2 = short year, 1 & 3..n = padded number
-            case 'u': // Extended Year (1..n): 2 = short year, 1 & 3..n = padded number
-                // Qt only supports long (4) or short (2) year, use long for all others
-                if (repeat == 2)
-                    result += QLatin1String("yy");
-                else
-                    result += QLatin1String("yyyy");
-                break;
-            case 'M': // Month (1..5): 4 = long, 3 = short, 1..2 = number, 5 = narrow
-            case 'L': // Standalone Month (1..5): 4 = long, 3 = short, 1..2 = number, 5 = narrow
-                // Qt only supports long, short and number, use short for narrow
-                if (repeat == 5)
-                    result += QLatin1String("MMM");
-                else
-                    result += QString(repeat, QLatin1Char('M'));
-                break;
-            case 'd': // Day of Month (1..2): 1..2 padded number
-                result += QString(repeat, c);
-                break;
-            case 'E': // Day of Week (1..6): 4 = long, 1..3 = short, 5..6 = narrow
-                // Qt only supports long, short and padded number, use short for narrow
-                if (repeat == 4)
-                    result += QLatin1String("dddd");
-                else
-                    result += QLatin1String("ddd");
-                break;
-            case 'e': // Local Day of Week (1..6): 4 = long, 3 = short, 5..6 = narrow, 1..2 padded number
-            case 'c': // Standalone Local Day of Week (1..6): 4 = long, 3 = short, 5..6 = narrow, 1..2 padded number
-                // Qt only supports long, short and padded number, use short for narrow
-                if (repeat >= 5)
-                    result += QLatin1String("ddd");
-                else
-                    result += QString(repeat, QLatin1Char('d'));
-                break;
-            case 'a': // AM/PM (1): 1 = short
-                // Translate to Qt uppercase AM/PM
-                result += QLatin1String("AP");
-                break;
-            case 'h': // Hour [1..12] (1..2): 1..2 = padded number
-            case 'K': // Hour [0..11] (1..2): 1..2 = padded number
-            case 'j': // Local Hour [12 or 24] (1..2): 1..2 = padded number
-                // Qt h is local hour
-                result += QString(repeat, QLatin1Char('h'));
-                break;
-            case 'H': // Hour [0..23] (1..2): 1..2 = padded number
-            case 'k': // Hour [1..24] (1..2): 1..2 = padded number
-                // Qt H is 0..23 hour
-                result += QString(repeat, QLatin1Char('H'));
-                break;
-            case 'm': // Minutes (1..2): 1..2 = padded number
-            case 's': // Seconds (1..2): 1..2 = padded number
-                result += QString(repeat, c);
-                break;
-            case 'S': // Fractional second (1..n): 1..n = truncates to decimal places
-                // Qt uses msecs either unpadded or padded to 3 places
-                if (repeat < 3)
-                    result += QLatin1Char('z');
-                else
-                    result += QLatin1String("zzz");
-                break;
-            case 'z': // Time Zone (1..4)
-            case 'Z': // Time Zone (1..5)
-            case 'O': // Time Zone (1, 4)
-            case 'v': // Time Zone (1, 4)
-            case 'V': // Time Zone (1..4)
-            case 'X': // Time Zone (1..5)
-            case 'x': // Time Zone (1..5)
-                result += QLatin1Char('t');
-                break;
-            default:
-                // a..z and A..Z are reserved for format codes, so any occurrence of these not
-                // already processed are not known and so unsupported formats to be ignored.
-                // All other chars are allowed as literals.
-                if (c < QLatin1Char('A') || c > QLatin1Char('z') ||
-                    (c > QLatin1Char('Z') && c < QLatin1Char('a'))) {
-                    result += QString(repeat, c);
-                }
-                break;
-        }
-
-        i += repeat;
-    }
-
-    return result;
-}
-
-QString getMacDateFormat(CFDateFormatterStyle style)
-{
-    QCFType<CFLocaleRef> l = CFLocaleCopyCurrent();
-    QCFType<CFDateFormatterRef> formatter = CFDateFormatterCreate(kCFAllocatorDefault,
-                                                                  l, style, kCFDateFormatterNoStyle);
-    return macToQtFormat(QCFString::toQString(CFDateFormatterGetFormat(formatter)));
-}
-
-static QString getMacTimeFormat(CFDateFormatterStyle style)
-{
-    QCFType<CFLocaleRef> l = CFLocaleCopyCurrent();
-    QCFType<CFDateFormatterRef> formatter = CFDateFormatterCreate(kCFAllocatorDefault,
-                                                                  l, kCFDateFormatterNoStyle, style);
-    return macToQtFormat(QCFString::toQString(CFDateFormatterGetFormat(formatter)));
-}
-
-static QString getCFLocaleValue(CFStringRef key)
-{
-    QCFType<CFLocaleRef> locale = CFLocaleCopyCurrent();
-    CFTypeRef value = CFLocaleGetValue(locale, key);
-    return QCFString::toQString(CFStringRef(static_cast<CFTypeRef>(value)));
-}
-
-static QLocale::MeasurementSystem macMeasurementSystem()
-{
-    QCFType<CFLocaleRef> locale = CFLocaleCopyCurrent();
-    CFStringRef system = static_cast<CFStringRef>(CFLocaleGetValue(locale, kCFLocaleMeasurementSystem));
-    if (QCFString::toQString(system) == QLatin1String("Metric")) {
-        return QLocale::MetricSystem;
-    } else {
-        return QLocale::ImperialSystem;
-    }
-}
-
-static quint8 macFirstDayOfWeek()
-{
-    QCFType<CFCalendarRef> calendar = CFCalendarCopyCurrent();
-    quint8 day = static_cast<quint8>(CFCalendarGetFirstWeekday(calendar))-1;
-    if (day == 0)
-        day = 7;
-    return day;
-}
-
-static QString macCurrencySymbol(QLocale::CurrencySymbolFormat format)
-{
-    QCFType<CFLocaleRef> locale = CFLocaleCopyCurrent();
-    switch (format) {
-    case QLocale::CurrencyIsoCode:
-        return QCFString::toQString(static_cast<CFStringRef>(CFLocaleGetValue(locale, kCFLocaleCurrencyCode)));
-    case QLocale::CurrencySymbol:
-        return QCFString::toQString(static_cast<CFStringRef>(CFLocaleGetValue(locale, kCFLocaleCurrencySymbol)));
-    case QLocale::CurrencyDisplayName: {
-        CFStringRef code = static_cast<CFStringRef>(CFLocaleGetValue(locale, kCFLocaleCurrencyCode));
-        QCFType<CFStringRef> value = CFLocaleCopyDisplayNameForPropertyValue(locale, kCFLocaleCurrencyCode, code);
-        return QCFString::toQString(value);
-    }
-    default:
-        break;
-    }
-    return QString();
-}
-
-static QString macFormatCurrency(const QSystemLocale::CurrencyToStringArgument &arg)
-{
-    QCFType<CFNumberRef> value;
-    switch (arg.value.type()) {
-    case QVariant::Int:
-    case QVariant::UInt: {
-        int v = arg.value.toInt();
-        value = CFNumberCreate(NULL, kCFNumberIntType, &v);
-        break;
-    }
-    case QVariant::Double: {
-        double v = arg.value.toDouble();
-        value = CFNumberCreate(NULL, kCFNumberDoubleType, &v);
-        break;
-    }
-    case QVariant::LongLong:
-    case QVariant::ULongLong: {
-        qint64 v = arg.value.toLongLong();
-        value = CFNumberCreate(NULL, kCFNumberLongLongType, &v);
-        break;
-    }
-    default:
-        return QString();
-    }
-
-    QCFType<CFLocaleRef> locale = CFLocaleCopyCurrent();
-    QCFType<CFNumberFormatterRef> currencyFormatter =
-            CFNumberFormatterCreate(NULL, locale, kCFNumberFormatterCurrencyStyle);
-    if (!arg.symbol.isEmpty()) {
-        CFNumberFormatterSetProperty(currencyFormatter, kCFNumberFormatterCurrencySymbol,
-                                     QCFString::toCFStringRef(arg.symbol));
-    }
-    QCFType<CFStringRef> result = CFNumberFormatterCreateStringWithNumber(NULL, currencyFormatter, value);
-    return QCFString::toQString(result);
-}
-
-static QVariant macQuoteString(QSystemLocale::QueryType type, const QStringRef &str)
-{
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 && !defined(Q_OS_IOS)
-    if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_6)
-        return QVariant();
-
-    QString begin, end;
-    QCFType<CFLocaleRef> locale = CFLocaleCopyCurrent();
-    switch (type) {
-    case QSystemLocale::StringToStandardQuotation:
-        begin = QCFString::toQString(static_cast<CFStringRef>(CFLocaleGetValue(locale, kCFLocaleQuotationBeginDelimiterKey)));
-        end = QCFString::toQString(static_cast<CFStringRef>(CFLocaleGetValue(locale, kCFLocaleQuotationEndDelimiterKey)));
-        return QString(begin % str % end);
-    case QSystemLocale::StringToAlternateQuotation:
-        begin = QCFString::toQString(static_cast<CFStringRef>(CFLocaleGetValue(locale, kCFLocaleAlternateQuotationBeginDelimiterKey)));
-        end = QCFString::toQString(static_cast<CFStringRef>(CFLocaleGetValue(locale, kCFLocaleAlternateQuotationEndDelimiterKey)));
-        return QString(begin % str % end);
-     default:
-        break;
-    }
-#endif
-    return QVariant();
-}
-
-QLocale QSystemLocale::fallbackLocale() const
-{
-    return QLocale(QString::fromUtf8(getMacLocaleName().constData()));
-}
-
-QVariant QSystemLocale::query(QueryType type, QVariant in = QVariant()) const
-{
-    switch(type) {
-//     case Name:
-//         return getMacLocaleName();
-    case DecimalPoint: {
-        QString value = getCFLocaleValue(kCFLocaleDecimalSeparator);
-        return value.isEmpty() ? QVariant() : value;
-    }
-    case GroupSeparator: {
-        QString value = getCFLocaleValue(kCFLocaleGroupingSeparator);
-        return value.isEmpty() ? QVariant() : value;
-    }
-    case DateFormatLong:
-    case DateFormatShort:
-        return getMacDateFormat(type == DateFormatShort
-                                ? kCFDateFormatterShortStyle
-                                : kCFDateFormatterLongStyle);
-    case TimeFormatLong:
-    case TimeFormatShort:
-        return getMacTimeFormat(type == TimeFormatShort
-                                ? kCFDateFormatterShortStyle
-                                : kCFDateFormatterLongStyle);
-    case DayNameLong:
-    case DayNameShort:
-        return macDayName(in.toInt(), (type == DayNameShort));
-    case MonthNameLong:
-    case MonthNameShort:
-    case StandaloneMonthNameLong:
-    case StandaloneMonthNameShort:
-        return macMonthName(in.toInt(), (type == MonthNameShort || type == StandaloneMonthNameShort));
-    case DateToStringShort:
-    case DateToStringLong:
-        return macDateToString(in.toDate(), (type == DateToStringShort));
-    case TimeToStringShort:
-    case TimeToStringLong:
-        return macTimeToString(in.toTime(), (type == TimeToStringShort));
-
-    case NegativeSign:
-    case PositiveSign:
-    case ZeroDigit:
-        break;
-
-    case MeasurementSystem:
-        return QVariant(static_cast<int>(macMeasurementSystem()));
-
-    case AMText:
-    case PMText: {
-        QCFType<CFLocaleRef> locale = CFLocaleCopyCurrent();
-        QCFType<CFDateFormatterRef> formatter = CFDateFormatterCreate(NULL, locale, kCFDateFormatterLongStyle, kCFDateFormatterLongStyle);
-        QCFType<CFStringRef> value = static_cast<CFStringRef>(CFDateFormatterCopyProperty(formatter,
-            (type == AMText ? kCFDateFormatterAMSymbol : kCFDateFormatterPMSymbol)));
-        return QCFString::toQString(value);
-    }
-    case FirstDayOfWeek:
-        return QVariant(macFirstDayOfWeek());
-    case CurrencySymbol:
-        return QVariant(macCurrencySymbol(QLocale::CurrencySymbolFormat(in.toUInt())));
-    case CurrencyToString:
-        return macFormatCurrency(in.value<QSystemLocale::CurrencyToStringArgument>());
-    case UILanguages: {
-        QCFType<CFPropertyListRef> languages = CFPreferencesCopyValue(
-                 CFSTR("AppleLanguages"),
-                 kCFPreferencesAnyApplication,
-                 kCFPreferencesCurrentUser,
-                 kCFPreferencesAnyHost);
-        QStringList result;
-        if (!languages)
-            return QVariant(result);
-
-        CFTypeID typeId = CFGetTypeID(languages);
-        if (typeId == CFArrayGetTypeID()) {
-            const int cnt = CFArrayGetCount(languages.as<CFArrayRef>());
-            result.reserve(cnt);
-            for (int i = 0; i < cnt; ++i) {
-                const QString lang = QCFString::toQString(
-                            static_cast<CFStringRef>(CFArrayGetValueAtIndex(languages.as<CFArrayRef>(), i)));
-                result.append(lang);
-            }
-        } else if (typeId == CFStringGetTypeID()) {
-            result = QStringList(QCFString::toQString(languages.as<CFStringRef>()));
-        } else {
-            qWarning("QLocale::uiLanguages(): CFPreferencesCopyValue returned unhandled type \"%s\"; please report to http://bugreports.qt-project.org",
-                     qPrintable(QCFString::toQString(CFCopyTypeIDDescription(typeId))));
-        }
-        return QVariant(result);
-    }
-    case StringToStandardQuotation:
-    case StringToAlternateQuotation:
-        return macQuoteString(type, in.value<QStringRef>());
-    default:
-        break;
-    }
-    return QVariant();
-}
-
-#endif // QT_NO_SYSTEMLOCALE
-
-QT_END_NAMESPACE
diff --git a/src/core/tools/qlocale_win.cpp b/src/core/tools/qlocale_win.cpp
deleted file mode 100644 (file)
index 039ca68..0000000
+++ /dev/null
@@ -1,990 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qlocale_p.h"
-#include "qlocale_tools_p.h"
-
-#include "qstringlist.h"
-#include "qvariant.h"
-#include "qdatetime.h"
-
-#include "qsystemlibrary_p.h"
-
-#include "qdebug.h"
-
-#if defined(Q_OS_WIN)
-#   include "qt_windows.h"
-#   include <time.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-static QByteArray getWinLocaleName(LCID id = LOCALE_USER_DEFAULT);
-static const char *winLangCodeToIsoName(int code);
-static QString winIso639LangName(LCID id = LOCALE_USER_DEFAULT);
-static QString winIso3116CtryName(LCID id = LOCALE_USER_DEFAULT);
-
-#ifndef QT_NO_SYSTEMLOCALE
-
-#ifndef MUI_LANGUAGE_NAME
-#define MUI_LANGUAGE_NAME 0x8
-#endif
-#ifndef LOCALE_SSHORTESTDAYNAME1
-#  define LOCALE_SSHORTESTDAYNAME1 0x0060
-#  define LOCALE_SSHORTESTDAYNAME2 0x0061
-#  define LOCALE_SSHORTESTDAYNAME3 0x0062
-#  define LOCALE_SSHORTESTDAYNAME4 0x0063
-#  define LOCALE_SSHORTESTDAYNAME5 0x0064
-#  define LOCALE_SSHORTESTDAYNAME6 0x0065
-#  define LOCALE_SSHORTESTDAYNAME7 0x0066
-#endif
-#ifndef LOCALE_SNATIVELANGUAGENAME
-#  define LOCALE_SNATIVELANGUAGENAME 0x00000004
-#endif
-#ifndef LOCALE_SNATIVECOUNTRYNAME
-#  define LOCALE_SNATIVECOUNTRYNAME 0x00000008
-#endif
-
-struct QSystemLocalePrivate
-{
-    QSystemLocalePrivate();
-
-    QChar zeroDigit();
-    QChar decimalPoint();
-    QChar groupSeparator();
-    QChar negativeSign();
-    QChar positiveSign();
-    QVariant dateFormat(QLocale::FormatType);
-    QVariant timeFormat(QLocale::FormatType);
-    QVariant dateTimeFormat(QLocale::FormatType);
-    QVariant dayName(int, QLocale::FormatType);
-    QVariant monthName(int, QLocale::FormatType);
-    QVariant toString(const QDate &, QLocale::FormatType);
-    QVariant toString(const QTime &, QLocale::FormatType);
-    QVariant toString(const QDateTime &, QLocale::FormatType);
-    QVariant measurementSystem();
-    QVariant amText();
-    QVariant pmText();
-    QVariant firstDayOfWeek();
-    QVariant currencySymbol(QLocale::CurrencySymbolFormat);
-    QVariant toCurrencyString(const QSystemLocale::CurrencyToStringArgument &);
-    QVariant uiLanguages();
-    QVariant nativeLanguageName();
-    QVariant nativeCountryName();
-
-    void update();
-
-private:
-    QByteArray langEnvVar;
-
-    enum SubstitutionType {
-        SUnknown,
-        SContext,
-        SAlways,
-        SNever
-    };
-
-    // cached values:
-    LCID lcid;
-    SubstitutionType substitutionType;
-    QChar zero;
-
-    QString getLocaleInfo(LCTYPE type, int maxlen = 0);
-    int getLocaleInfo_int(LCTYPE type, int maxlen = 0);
-    QChar getLocaleInfo_qchar(LCTYPE type);
-
-    SubstitutionType substitution();
-    QString &substituteDigits(QString &string);
-
-    static QString winToQtFormat(const QString &sys_fmt);
-
-};
-Q_GLOBAL_STATIC(QSystemLocalePrivate, systemLocalePrivate)
-
-QSystemLocalePrivate::QSystemLocalePrivate()
-    : substitutionType(SUnknown)
-{
-    langEnvVar = qgetenv("LANG");
-    lcid = GetUserDefaultLCID();
-}
-
-QString QSystemLocalePrivate::getLocaleInfo(LCTYPE type, int maxlen)
-{
-    QVarLengthArray<wchar_t, 64> buf(maxlen ? maxlen : 64);
-    if (!GetLocaleInfo(lcid, type, buf.data(), buf.size()))
-        return QString();
-    if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
-        int cnt = GetLocaleInfo(lcid, type, 0, 0);
-        if (cnt == 0)
-            return QString();
-        buf.resize(cnt);
-        if (!GetLocaleInfo(lcid, type, buf.data(), buf.size()))
-            return QString();
-    }
-    return QString::fromWCharArray(buf.data());
-}
-
-int QSystemLocalePrivate::getLocaleInfo_int(LCTYPE type, int maxlen)
-{
-    QString str = getLocaleInfo(type, maxlen);
-    bool ok = false;
-    int v = str.toInt(&ok);
-    return ok ? v : 0;
-}
-
-QChar QSystemLocalePrivate::getLocaleInfo_qchar(LCTYPE type)
-{
-    QString str = getLocaleInfo(type);
-    return str.isEmpty() ? QChar() : str.at(0);
-}
-
-QSystemLocalePrivate::SubstitutionType QSystemLocalePrivate::substitution()
-{
-    if (substitutionType == SUnknown) {
-        wchar_t buf[8];
-        if (!GetLocaleInfo(lcid, LOCALE_IDIGITSUBSTITUTION, buf, 8)) {
-            substitutionType = QSystemLocalePrivate::SNever;
-            return substitutionType;
-        }
-        if (buf[0] == '1')
-            substitutionType = QSystemLocalePrivate::SNever;
-        else if (buf[0] == '0')
-            substitutionType = QSystemLocalePrivate::SContext;
-        else if (buf[0] == '2')
-            substitutionType = QSystemLocalePrivate::SAlways;
-        else {
-            wchar_t digits[11];
-            if (!GetLocaleInfo(lcid, LOCALE_SNATIVEDIGITS, digits, 11)) {
-                substitutionType = QSystemLocalePrivate::SNever;
-                return substitutionType;
-            }
-            const wchar_t zero = digits[0];
-            if (buf[0] == zero + 2)
-                substitutionType = QSystemLocalePrivate::SAlways;
-            else
-                substitutionType = QSystemLocalePrivate::SNever;
-        }
-    }
-    return substitutionType;
-}
-
-QString &QSystemLocalePrivate::substituteDigits(QString &string)
-{
-    ushort zero = zeroDigit().unicode();
-    ushort *qch = (ushort *)string.data();
-    for (ushort *end = qch + string.size(); qch != end; ++qch) {
-        if (*qch >= '0' && *qch <= '9')
-            *qch = zero + (*qch - '0');
-    }
-    return string;
-}
-
-QChar QSystemLocalePrivate::zeroDigit()
-{
-    if (zero.isNull())
-        zero = getLocaleInfo_qchar(LOCALE_SNATIVEDIGITS);
-    return zero;
-}
-
-QChar QSystemLocalePrivate::decimalPoint()
-{
-    return getLocaleInfo_qchar(LOCALE_SDECIMAL);
-}
-
-QChar QSystemLocalePrivate::groupSeparator()
-{
-    return getLocaleInfo_qchar(LOCALE_STHOUSAND);
-}
-
-QChar QSystemLocalePrivate::negativeSign()
-{
-    return getLocaleInfo_qchar(LOCALE_SNEGATIVESIGN);
-}
-
-QChar QSystemLocalePrivate::positiveSign()
-{
-    return getLocaleInfo_qchar(LOCALE_SPOSITIVESIGN);
-}
-
-QVariant QSystemLocalePrivate::dateFormat(QLocale::FormatType type)
-{
-    switch (type) {
-    case QLocale::ShortFormat:
-        return winToQtFormat(getLocaleInfo(LOCALE_SSHORTDATE));
-    case QLocale::LongFormat:
-        return winToQtFormat(getLocaleInfo(LOCALE_SLONGDATE));
-    case QLocale::NarrowFormat:
-        break;
-    }
-    return QVariant();
-}
-
-QVariant QSystemLocalePrivate::timeFormat(QLocale::FormatType type)
-{
-    switch (type) {
-    case QLocale::ShortFormat:
-        return winToQtFormat(getLocaleInfo(LOCALE_STIMEFORMAT)); //###
-    case QLocale::LongFormat:
-        return winToQtFormat(getLocaleInfo(LOCALE_STIMEFORMAT));
-    case QLocale::NarrowFormat:
-        break;
-    }
-    return QVariant();
-}
-
-QVariant QSystemLocalePrivate::dateTimeFormat(QLocale::FormatType type)
-{
-    return QString(dateFormat(type).toString() + QLatin1Char(' ') + timeFormat(type).toString());
-}
-
-QVariant QSystemLocalePrivate::dayName(int day, QLocale::FormatType type)
-{
-    static const LCTYPE short_day_map[]
-        = { LOCALE_SABBREVDAYNAME1, LOCALE_SABBREVDAYNAME2,
-            LOCALE_SABBREVDAYNAME3, LOCALE_SABBREVDAYNAME4, LOCALE_SABBREVDAYNAME5,
-            LOCALE_SABBREVDAYNAME6, LOCALE_SABBREVDAYNAME7 };
-
-    static const LCTYPE long_day_map[]
-        = { LOCALE_SDAYNAME1, LOCALE_SDAYNAME2,
-            LOCALE_SDAYNAME3, LOCALE_SDAYNAME4, LOCALE_SDAYNAME5,
-            LOCALE_SDAYNAME6, LOCALE_SDAYNAME7 };
-
-    static const LCTYPE narrow_day_map[]
-        = { LOCALE_SSHORTESTDAYNAME1, LOCALE_SSHORTESTDAYNAME2,
-            LOCALE_SSHORTESTDAYNAME3, LOCALE_SSHORTESTDAYNAME4,
-            LOCALE_SSHORTESTDAYNAME5, LOCALE_SSHORTESTDAYNAME6,
-            LOCALE_SSHORTESTDAYNAME7 };
-
-    day -= 1;
-
-    if (type == QLocale::LongFormat)
-        return getLocaleInfo(long_day_map[day]);
-    else if (type == QLocale::NarrowFormat && QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA)
-        return getLocaleInfo(narrow_day_map[day]);
-    return getLocaleInfo(short_day_map[day]);
-}
-
-QVariant QSystemLocalePrivate::monthName(int month, QLocale::FormatType type)
-{
-    static const LCTYPE short_month_map[]
-        = { LOCALE_SABBREVMONTHNAME1, LOCALE_SABBREVMONTHNAME2, LOCALE_SABBREVMONTHNAME3,
-            LOCALE_SABBREVMONTHNAME4, LOCALE_SABBREVMONTHNAME5, LOCALE_SABBREVMONTHNAME6,
-            LOCALE_SABBREVMONTHNAME7, LOCALE_SABBREVMONTHNAME8, LOCALE_SABBREVMONTHNAME9,
-            LOCALE_SABBREVMONTHNAME10, LOCALE_SABBREVMONTHNAME11, LOCALE_SABBREVMONTHNAME12 };
-
-    static const LCTYPE long_month_map[]
-        = { LOCALE_SMONTHNAME1, LOCALE_SMONTHNAME2, LOCALE_SMONTHNAME3,
-            LOCALE_SMONTHNAME4, LOCALE_SMONTHNAME5, LOCALE_SMONTHNAME6,
-            LOCALE_SMONTHNAME7, LOCALE_SMONTHNAME8, LOCALE_SMONTHNAME9,
-            LOCALE_SMONTHNAME10, LOCALE_SMONTHNAME11, LOCALE_SMONTHNAME12 };
-
-    month -= 1;
-    if (month < 0 || month > 11)
-    return QString();
-
-    LCTYPE lctype = (type == QLocale::ShortFormat || type == QLocale::NarrowFormat)
-            ? short_month_map[month] : long_month_map[month];
-    return getLocaleInfo(lctype);
-}
-
-QVariant QSystemLocalePrivate::toString(const QDate &date, QLocale::FormatType type)
-{
-    SYSTEMTIME st;
-    memset(&st, 0, sizeof(SYSTEMTIME));
-    st.wYear = date.year();
-    st.wMonth = date.month();
-    st.wDay = date.day();
-
-    DWORD flags = (type == QLocale::LongFormat ? DATE_LONGDATE : DATE_SHORTDATE);
-    wchar_t buf[255];
-    if (GetDateFormat(lcid, flags, &st, NULL, buf, 255)) {
-        QString format = QString::fromWCharArray(buf);
-        if (substitution() == SAlways)
-            substituteDigits(format);
-        return format;
-    }
-    return QString();
-}
-
-QVariant QSystemLocalePrivate::toString(const QTime &time, QLocale::FormatType)
-{
-    SYSTEMTIME st;
-    memset(&st, 0, sizeof(SYSTEMTIME));
-    st.wHour = time.hour();
-    st.wMinute = time.minute();
-    st.wSecond = time.second();
-    st.wMilliseconds = 0;
-
-    DWORD flags = 0;
-
-    wchar_t buf[255];
-    if (GetTimeFormat(lcid, flags, &st, NULL, buf, 255)) {
-        QString format = QString::fromWCharArray(buf);
-        if (substitution() == SAlways)
-            substituteDigits(format);
-        return format;
-    }
-    return QString();
-}
-
-QVariant QSystemLocalePrivate::toString(const QDateTime &dt, QLocale::FormatType type)
-{
-    return QString(toString(dt.date(), type).toString() + QLatin1Char(' ') + toString(dt.time(), type).toString());
-}
-
-QVariant QSystemLocalePrivate::measurementSystem()
-{
-    wchar_t output[2];
-
-    if (GetLocaleInfo(lcid, LOCALE_IMEASURE, output, 2)) {
-        QString iMeasure = QString::fromWCharArray(output);
-        if (iMeasure == QLatin1String("1")) {
-            return QLocale::ImperialSystem;
-        }
-    }
-
-    return QLocale::MetricSystem;
-}
-
-QVariant QSystemLocalePrivate::amText()
-{
-    wchar_t output[15]; // maximum length including  terminating zero character for Win2003+
-
-    if (GetLocaleInfo(lcid, LOCALE_S1159, output, 15)) {
-        return QString::fromWCharArray(output);
-    }
-
-    return QVariant();
-}
-
-QVariant QSystemLocalePrivate::pmText()
-{
-    wchar_t output[15]; // maximum length including  terminating zero character for Win2003+
-
-    if (GetLocaleInfo(lcid, LOCALE_S2359, output, 15)) {
-        return QString::fromWCharArray(output);
-    }
-
-    return QVariant();
-}
-
-QVariant QSystemLocalePrivate::firstDayOfWeek()
-{
-    wchar_t output[4]; // maximum length including  terminating zero character for Win2003+
-
-    if (GetLocaleInfo(lcid, LOCALE_IFIRSTDAYOFWEEK, output, 4))
-        return QString::fromWCharArray(output).toUInt()+1;
-
-    return 1;
-}
-
-QVariant QSystemLocalePrivate::currencySymbol(QLocale::CurrencySymbolFormat format)
-{
-    wchar_t buf[13];
-    switch (format) {
-    case QLocale::CurrencySymbol:
-        if (GetLocaleInfo(lcid, LOCALE_SCURRENCY, buf, 13))
-            return QString::fromWCharArray(buf);
-        break;
-    case QLocale::CurrencyIsoCode:
-        if (GetLocaleInfo(lcid, LOCALE_SINTLSYMBOL, buf, 9))
-            return QString::fromWCharArray(buf);
-        break;
-    case QLocale::CurrencyDisplayName: {
-        QVarLengthArray<wchar_t, 64> buf(64);
-        if (!GetLocaleInfo(lcid, LOCALE_SNATIVECURRNAME, buf.data(), buf.size())) {
-            if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
-                break;
-            buf.resize(255); // should be large enough, right?
-            if (!GetLocaleInfo(lcid, LOCALE_SNATIVECURRNAME, buf.data(), buf.size()))
-                break;
-        }
-        return QString::fromWCharArray(buf.data());
-    }
-    default:
-        break;
-    }
-    return QVariant();
-}
-
-QVariant QSystemLocalePrivate::toCurrencyString(const QSystemLocale::CurrencyToStringArgument &arg)
-{
-    QString value;
-    switch (arg.value.type()) {
-    case QVariant::Int:
-        value = QLocalePrivate::longLongToString(QLatin1Char('0'), QLatin1Char(','), QLatin1Char('+'), QLatin1Char('-'),
-                                                 arg.value.toInt(), -1, 10, -1, QLocale::OmitGroupSeparator);
-        break;
-    case QVariant::UInt:
-        value = QLocalePrivate::unsLongLongToString(QLatin1Char('0'), QLatin1Char(','), QLatin1Char('+'),
-                                                    arg.value.toUInt(), -1, 10, -1, QLocale::OmitGroupSeparator);
-        break;
-    case QVariant::Double:
-        value = QLocalePrivate::doubleToString(QLatin1Char('0'), QLatin1Char('+'), QLatin1Char('-'),
-                                               QLatin1Char(' '), QLatin1Char(','), QLatin1Char('.'),
-                                               arg.value.toDouble(), -1, QLocalePrivate::DFDecimal, -1, QLocale::OmitGroupSeparator);
-        break;
-    case QVariant::LongLong:
-        value = QLocalePrivate::longLongToString(QLatin1Char('0'), QLatin1Char(','), QLatin1Char('+'), QLatin1Char('-'),
-                                                 arg.value.toLongLong(), -1, 10, -1, QLocale::OmitGroupSeparator);
-        break;
-    case QVariant::ULongLong:
-        value = QLocalePrivate::unsLongLongToString(QLatin1Char('0'), QLatin1Char(','), QLatin1Char('+'),
-                                                    arg.value.toULongLong(), -1, 10, -1, QLocale::OmitGroupSeparator);
-        break;
-    default:
-        return QVariant();
-    }
-
-    QVarLengthArray<wchar_t, 64> out(64);
-
-    QString decimalSep;
-    QString thousandSep;
-    CURRENCYFMT format;
-    CURRENCYFMT *pformat = NULL;
-    if (!arg.symbol.isEmpty()) {
-        format.NumDigits = getLocaleInfo_int(lcid, LOCALE_ICURRDIGITS);
-        format.LeadingZero = getLocaleInfo_int(lcid, LOCALE_ILZERO);
-        decimalSep = getLocaleInfo(lcid, LOCALE_SMONDECIMALSEP);
-        format.lpDecimalSep = (wchar_t *)decimalSep.utf16();
-        thousandSep = getLocaleInfo(lcid, LOCALE_SMONTHOUSANDSEP);
-        format.lpThousandSep = (wchar_t *)thousandSep.utf16();
-        format.NegativeOrder = getLocaleInfo_int(lcid, LOCALE_INEGCURR);
-        format.PositiveOrder = getLocaleInfo_int(lcid, LOCALE_ICURRENCY);
-        format.lpCurrencySymbol = (wchar_t *)arg.symbol.utf16();
-
-        // grouping is complicated and ugly:
-        // int(0)  == "123456789.00"    == string("0")
-        // int(3)  == "123,456,789.00"  == string("3;0")
-        // int(30) == "123456,789.00"   == string("3;0;0")
-        // int(32) == "12,34,56,789.00" == string("3;2;0")
-        // int(320)== "1234,56,789.00"  == string("3;2")
-        QString groupingStr = getLocaleInfo(lcid, LOCALE_SMONGROUPING);
-        format.Grouping = groupingStr.remove(QLatin1Char(';')).toInt();
-        if (format.Grouping % 10 == 0) // magic
-            format.Grouping /= 10;
-        else
-            format.Grouping *= 10;
-        pformat = &format;
-    }
-
-    int ret = ::GetCurrencyFormat(lcid, 0, reinterpret_cast<const wchar_t *>(value.utf16()),
-                                  pformat, out.data(), out.size());
-    if (ret == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
-        ret = ::GetCurrencyFormat(lcid, 0, reinterpret_cast<const wchar_t *>(value.utf16()),
-                                  pformat, out.data(), 0);
-        out.resize(ret);
-        ::GetCurrencyFormat(lcid, 0, reinterpret_cast<const wchar_t *>(value.utf16()),
-                            pformat, out.data(), out.size());
-    }
-
-    value = QString::fromWCharArray(out.data());
-    if (substitution() == SAlways)
-        substituteDigits( value);
-    return value;
-}
-
-QVariant QSystemLocalePrivate::uiLanguages()
-{
-    if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) {
-        typedef BOOL (WINAPI *GetUserPreferredUILanguagesFunc) (
-                    DWORD dwFlags,
-                    PULONG pulNumLanguages,
-                    PWSTR pwszLanguagesBuffer,
-                    PULONG pcchLanguagesBuffer);
-        static GetUserPreferredUILanguagesFunc GetUserPreferredUILanguages_ptr = 0;
-        if (!GetUserPreferredUILanguages_ptr) {
-            QSystemLibrary lib(QLatin1String("kernel32"));
-            if (lib.load())
-                GetUserPreferredUILanguages_ptr = (GetUserPreferredUILanguagesFunc)lib.resolve("GetUserPreferredUILanguages");
-        }
-        if (GetUserPreferredUILanguages_ptr) {
-            unsigned long cnt = 0;
-            QVarLengthArray<wchar_t, 64> buf(64);
-            unsigned long size = buf.size();
-            if (!GetUserPreferredUILanguages_ptr(MUI_LANGUAGE_NAME, &cnt, buf.data(), &size)) {
-                size = 0;
-                if (GetLastError() == ERROR_INSUFFICIENT_BUFFER &&
-                    GetUserPreferredUILanguages_ptr(MUI_LANGUAGE_NAME, &cnt, NULL, &size)) {
-                    buf.resize(size);
-                    if (!GetUserPreferredUILanguages_ptr(MUI_LANGUAGE_NAME, &cnt, buf.data(), &size))
-                        return QStringList();
-                }
-            }
-            QStringList result;
-            result.reserve(cnt);
-            const wchar_t *str = buf.constData();
-            for (; cnt > 0; --cnt) {
-                QString s = QString::fromWCharArray(str);
-                if (s.isEmpty())
-                    break; // something is wrong
-                result.append(s);
-                str += s.size()+1;
-            }
-            return result;
-        }
-    }
-
-    // old Windows before Vista
-    return QStringList(QString::fromLatin1(winLangCodeToIsoName(GetUserDefaultUILanguage())));
-}
-
-QVariant QSystemLocalePrivate::nativeLanguageName()
-{
-    if (QSysInfo::windowsVersion() < QSysInfo::WV_WINDOWS7)
-        return getLocaleInfo(LOCALE_SNATIVELANGNAME);
-    return getLocaleInfo(LOCALE_SNATIVELANGUAGENAME);
-}
-
-QVariant QSystemLocalePrivate::nativeCountryName()
-{
-    if (QSysInfo::windowsVersion() < QSysInfo::WV_WINDOWS7)
-        return getLocaleInfo(LOCALE_SNATIVECTRYNAME);
-    return getLocaleInfo(LOCALE_SNATIVECOUNTRYNAME);
-}
-
-
-void QSystemLocalePrivate::update()
-{
-    lcid = GetUserDefaultLCID();
-    substitutionType = SUnknown;
-    zero = QChar();
-}
-
-QString QSystemLocalePrivate::winToQtFormat(const QString &sys_fmt)
-{
-    QString result;
-    int i = 0;
-
-    while (i < sys_fmt.size()) {
-        if (sys_fmt.at(i).unicode() == QLatin1Char('\'')) {
-            QString text = qt_readEscapedFormatString(sys_fmt, &i);
-            if (text == QLatin1String("'"))
-                result += QLatin1String("''");
-            else
-                result += QString(QLatin1Char('\'') + text + QLatin1Char('\''));
-            continue;
-        }
-
-        QChar c = sys_fmt.at(i);
-        int repeat = qt_repeatCount(sys_fmt, i);
-
-        switch (c.unicode()) {
-            // Date
-            case 'y':
-                if (repeat > 5)
-                    repeat = 5;
-                else if (repeat == 3)
-                    repeat = 2;
-                switch (repeat) {
-                    case 1:
-                        result += QLatin1String("yy"); // "y" unsupported by Qt, use "yy"
-                        break;
-                    case 5:
-                        result += QLatin1String("yyyy"); // "yyyyy" same as "yyyy" on Windows
-                        break;
-                    default:
-                        result += QString(repeat, QLatin1Char('y'));
-                        break;
-                }
-                break;
-            case 'g':
-                if (repeat > 2)
-                    repeat = 2;
-                switch (repeat) {
-                    case 2:
-                        break; // no equivalent of "gg" in Qt
-                    default:
-                        result += QLatin1Char('g');
-                        break;
-                }
-                break;
-            case 't':
-                if (repeat > 2)
-                    repeat = 2;
-                result += QLatin1String("AP"); // "t" unsupported, use "AP"
-                break;
-            default:
-                result += QString(repeat, c);
-                break;
-        }
-
-        i += repeat;
-    }
-
-    return result;
-}
-
-QLocale QSystemLocale::fallbackLocale() const
-{
-    return QLocale(QString::fromLatin1(getWinLocaleName()));
-}
-
-QVariant QSystemLocale::query(QueryType type, QVariant in = QVariant()) const
-{
-    QSystemLocalePrivate *d = systemLocalePrivate();
-    switch(type) {
-    case DecimalPoint:
-        return d->decimalPoint();
-    case GroupSeparator:
-        return d->groupSeparator();
-    case NegativeSign:
-        return d->negativeSign();
-    case PositiveSign:
-        return d->positiveSign();
-    case DateFormatLong:
-        return d->dateFormat(QLocale::LongFormat);
-    case DateFormatShort:
-        return d->dateFormat(QLocale::ShortFormat);
-    case TimeFormatLong:
-        return d->timeFormat(QLocale::LongFormat);
-    case TimeFormatShort:
-        return d->timeFormat(QLocale::ShortFormat);
-    case DateTimeFormatLong:
-        return d->dateTimeFormat(QLocale::LongFormat);
-    case DateTimeFormatShort:
-        return d->dateTimeFormat(QLocale::ShortFormat);
-    case DayNameLong:
-        return d->dayName(in.toInt(), QLocale::LongFormat);
-    case DayNameShort:
-        return d->dayName(in.toInt(), QLocale::ShortFormat);
-    case MonthNameLong:
-    case StandaloneMonthNameLong:
-        return d->monthName(in.toInt(), QLocale::LongFormat);
-    case MonthNameShort:
-    case StandaloneMonthNameShort:
-        return d->monthName(in.toInt(), QLocale::ShortFormat);
-    case DateToStringShort:
-        return d->toString(in.toDate(), QLocale::ShortFormat);
-    case DateToStringLong:
-        return d->toString(in.toDate(), QLocale::LongFormat);
-    case TimeToStringShort:
-        return d->toString(in.toTime(), QLocale::ShortFormat);
-    case TimeToStringLong:
-        return d->toString(in.toTime(), QLocale::LongFormat);
-    case DateTimeToStringShort:
-        return d->toString(in.toDateTime(), QLocale::ShortFormat);
-    case DateTimeToStringLong:
-        return d->toString(in.toDateTime(), QLocale::LongFormat);
-    case ZeroDigit:
-        return d->zeroDigit();
-    case LanguageId:
-    case CountryId: {
-        QString locale = QString::fromLatin1(getWinLocaleName());
-        QLocale::Language lang;
-        QLocale::Script script;
-        QLocale::Country cntry;
-        QLocalePrivate::getLangAndCountry(locale, lang, script, cntry);
-        if (type == LanguageId)
-            return lang;
-        if (cntry == QLocale::AnyCountry)
-            return fallbackLocale().country();
-        return cntry;
-    }
-    case ScriptId:
-        return QVariant(QLocale::AnyScript);
-    case MeasurementSystem:
-        return d->measurementSystem();
-    case AMText:
-        return d->amText();
-    case PMText:
-        return d->pmText();
-    case FirstDayOfWeek:
-        return d->firstDayOfWeek();
-    case CurrencySymbol:
-        return d->currencySymbol(QLocale::CurrencySymbolFormat(in.toUInt()));
-    case CurrencyToString:
-        return d->toCurrencyString(in.value<QSystemLocale::CurrencyToStringArgument>());
-    case UILanguages:
-        return d->uiLanguages();
-    case LocaleChanged:
-        d->update();
-        break;
-    case NativeLanguageName:
-        return d->nativeLanguageName();
-    case NativeCountryName:
-        return d->nativeCountryName();
-    default:
-        break;
-    }
-    return QVariant();
-}
-#endif // QT_NO_SYSTEMLOCALE
-
-struct WindowsToISOListElt {
-    ushort windows_code;
-    char iso_name[6];
-};
-
-/* NOTE: This array should be sorted by the first column! */
-static const WindowsToISOListElt windows_to_iso_list[] = {
-    { 0x0401, "ar_SA" },
-    { 0x0402, "bg\0  " },
-    { 0x0403, "ca\0  " },
-    { 0x0404, "zh_TW" },
-    { 0x0405, "cs\0  " },
-    { 0x0406, "da\0  " },
-    { 0x0407, "de\0  " },
-    { 0x0408, "el\0  " },
-    { 0x0409, "en_US" },
-    { 0x040a, "es\0  " },
-    { 0x040b, "fi\0  " },
-    { 0x040c, "fr\0  " },
-    { 0x040d, "he\0  " },
-    { 0x040e, "hu\0  " },
-    { 0x040f, "is\0  " },
-    { 0x0410, "it\0  " },
-    { 0x0411, "ja\0  " },
-    { 0x0412, "ko\0  " },
-    { 0x0413, "nl\0  " },
-    { 0x0414, "no\0  " },
-    { 0x0415, "pl\0  " },
-    { 0x0416, "pt_BR" },
-    { 0x0418, "ro\0  " },
-    { 0x0419, "ru\0  " },
-    { 0x041a, "hr\0  " },
-    { 0x041c, "sq\0  " },
-    { 0x041d, "sv\0  " },
-    { 0x041e, "th\0  " },
-    { 0x041f, "tr\0  " },
-    { 0x0420, "ur\0  " },
-    { 0x0421, "in\0  " },
-    { 0x0422, "uk\0  " },
-    { 0x0423, "be\0  " },
-    { 0x0425, "et\0  " },
-    { 0x0426, "lv\0  " },
-    { 0x0427, "lt\0  " },
-    { 0x0429, "fa\0  " },
-    { 0x042a, "vi\0  " },
-    { 0x042d, "eu\0  " },
-    { 0x042f, "mk\0  " },
-    { 0x0436, "af\0  " },
-    { 0x0438, "fo\0  " },
-    { 0x0439, "hi\0  " },
-    { 0x043e, "ms\0  " },
-    { 0x0458, "mt\0  " },
-    { 0x0801, "ar_IQ" },
-    { 0x0804, "zh_CN" },
-    { 0x0807, "de_CH" },
-    { 0x0809, "en_GB" },
-    { 0x080a, "es_MX" },
-    { 0x080c, "fr_BE" },
-    { 0x0810, "it_CH" },
-    { 0x0812, "ko\0  " },
-    { 0x0813, "nl_BE" },
-    { 0x0814, "no\0  " },
-    { 0x0816, "pt\0  " },
-    { 0x081a, "sr\0  " },
-    { 0x081d, "sv_FI" },
-    { 0x0c01, "ar_EG" },
-    { 0x0c04, "zh_HK" },
-    { 0x0c07, "de_AT" },
-    { 0x0c09, "en_AU" },
-    { 0x0c0a, "es\0  " },
-    { 0x0c0c, "fr_CA" },
-    { 0x0c1a, "sr\0  " },
-    { 0x1001, "ar_LY" },
-    { 0x1004, "zh_SG" },
-    { 0x1007, "de_LU" },
-    { 0x1009, "en_CA" },
-    { 0x100a, "es_GT" },
-    { 0x100c, "fr_CH" },
-    { 0x1401, "ar_DZ" },
-    { 0x1407, "de_LI" },
-    { 0x1409, "en_NZ" },
-    { 0x140a, "es_CR" },
-    { 0x140c, "fr_LU" },
-    { 0x1801, "ar_MA" },
-    { 0x1809, "en_IE" },
-    { 0x180a, "es_PA" },
-    { 0x1c01, "ar_TN" },
-    { 0x1c09, "en_ZA" },
-    { 0x1c0a, "es_DO" },
-    { 0x2001, "ar_OM" },
-    { 0x2009, "en_JM" },
-    { 0x200a, "es_VE" },
-    { 0x2401, "ar_YE" },
-    { 0x2409, "en\0  " },
-    { 0x240a, "es_CO" },
-    { 0x2801, "ar_SY" },
-    { 0x2809, "en_BZ" },
-    { 0x280a, "es_PE" },
-    { 0x2c01, "ar_JO" },
-    { 0x2c09, "en_TT" },
-    { 0x2c0a, "es_AR" },
-    { 0x3001, "ar_LB" },
-    { 0x300a, "es_EC" },
-    { 0x3401, "ar_KW" },
-    { 0x340a, "es_CL" },
-    { 0x3801, "ar_AE" },
-    { 0x380a, "es_UY" },
-    { 0x3c01, "ar_BH" },
-    { 0x3c0a, "es_PY" },
-    { 0x4001, "ar_QA" },
-    { 0x400a, "es_BO" },
-    { 0x440a, "es_SV" },
-    { 0x480a, "es_HN" },
-    { 0x4c0a, "es_NI" },
-    { 0x500a, "es_PR" }
-};
-
-static const int windows_to_iso_count
-    = sizeof(windows_to_iso_list)/sizeof(WindowsToISOListElt);
-
-static const char *winLangCodeToIsoName(int code)
-{
-    int cmp = code - windows_to_iso_list[0].windows_code;
-    if (cmp < 0)
-        return 0;
-
-    if (cmp == 0)
-        return windows_to_iso_list[0].iso_name;
-
-    int begin = 0;
-    int end = windows_to_iso_count;
-
-    while (end - begin > 1) {
-        uint mid = (begin + end)/2;
-
-        const WindowsToISOListElt *elt = windows_to_iso_list + mid;
-        int cmp = code - elt->windows_code;
-        if (cmp < 0)
-            end = mid;
-        else if (cmp > 0)
-            begin = mid;
-        else
-            return elt->iso_name;
-    }
-
-    return 0;
-
-}
-
-static QString winIso639LangName(LCID id)
-{
-    QString result;
-
-    // Windows returns the wrong ISO639 for some languages, we need to detect them here using
-    // the language code
-    QString lang_code;
-    wchar_t out[256];
-    if (GetLocaleInfo(id, LOCALE_ILANGUAGE, out, 255)) // ### shouldn't use them according to msdn
-        lang_code = QString::fromWCharArray(out);
-
-    if (!lang_code.isEmpty()) {
-        const char *endptr;
-        bool ok;
-        QByteArray latin1_lang_code = lang_code.toLatin1();
-        int i = qstrtoull(latin1_lang_code, &endptr, 16, &ok);
-        if (ok && *endptr == '\0') {
-            switch (i) {
-                case 0x814:
-                    result = QLatin1String("nn"); // Nynorsk
-                    break;
-                default:
-                    break;
-            }
-        }
-    }
-
-    if (!result.isEmpty())
-        return result;
-
-    // not one of the problematic languages - do the usual lookup
-    if (GetLocaleInfo(id, LOCALE_SISO639LANGNAME , out, 255))
-        result = QString::fromWCharArray(out);
-
-    return result;
-}
-
-static QString winIso3116CtryName(LCID id)
-{
-    QString result;
-
-    wchar_t out[256];
-    if (GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME, out, 255))
-        result = QString::fromWCharArray(out);
-
-    return result;
-}
-
-static QByteArray getWinLocaleName(LCID id)
-{
-    QByteArray result;
-    if (id == LOCALE_USER_DEFAULT) {
-        static QByteArray langEnvVar = qgetenv("LANG");
-        result = langEnvVar;
-        QString lang, script, cntry;
-        if ( result == "C" || (!result.isEmpty()
-                && qt_splitLocaleName(QString::fromLocal8Bit(result), lang, script, cntry)) ) {
-            long id = 0;
-            bool ok = false;
-            id = qstrtoll(result.data(), 0, 0, &ok);
-            if ( !ok || id == 0 || id < INT_MIN || id > INT_MAX )
-                return result;
-            else
-                return winLangCodeToIsoName( (int)id );
-        }
-    }
-
-#if defined(Q_OS_WINCE)
-    result = winLangCodeToIsoName(id != LOCALE_USER_DEFAULT ? id : GetUserDefaultLCID());
-#else
-    if (id == LOCALE_USER_DEFAULT)
-        id = GetUserDefaultLCID();
-    QString resultuage = winIso639LangName(id);
-    QString country = winIso3116CtryName(id);
-    result = resultuage.toLatin1();
-    if (!country.isEmpty()) {
-        result += '_';
-        result += country.toLatin1();
-    }
-#endif
-
-    return result;
-}
-
-Q_CORE_EXPORT QLocale qt_localeFromLCID(LCID id)
-{
-    return QLocale(QString::fromLatin1(getWinLocaleName(id)));
-}
-
-QT_END_NAMESPACE
index 7612510..63382d3 100644 (file)
@@ -237,13 +237,6 @@ void QDeclarativeViewPrivate::init()
     q->setFocusPolicy(Qt::StrongFocus);
 
     q->scene()->setStickyFocus(true);  //### needed for correct focus handling
-
-#ifdef QDECLARATIVEVIEW_NOBACKGROUND
-    q->setAttribute(Qt::WA_OpaquePaintEvent);
-    q->setAttribute(Qt::WA_NoSystemBackground);
-    q->viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
-    q->viewport()->setAttribute(Qt::WA_NoSystemBackground);
-#endif
 }
 
 /*!
diff --git a/src/gui/accessible/qaccessible_mac.mm b/src/gui/accessible/qaccessible_mac.mm
deleted file mode 100644 (file)
index 8f75327..0000000
+++ /dev/null
@@ -1,2460 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qaccessible.h"
-
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible_mac_p.h"
-#include "qhash.h"
-#include "qset.h"
-#include "qpointer.h"
-#include "qapplication.h"
-#include "qmainwindow.h"
-#include "qtextdocument.h"
-#include "qdebug.h"
-#include "qabstractslider.h"
-#include "qsplitter.h"
-#include "qtabwidget.h"
-#include "qlistview.h"
-#include "qtableview.h"
-#include "qdockwidget.h"
-
-#include <qt_mac_p.h>
-#include <qwidget_p.h>
-#include <CoreFoundation/CoreFoundation.h>
-
-QT_BEGIN_NAMESPACE
-
-/*
-    Set up platform defines. There is a one-to-one correspondence between the
-    Carbon and Cocoa roles and attributes, but the prefix and type changes.
-*/
-#ifdef QT_MAC_USE_COCOA
-typedef NSString * const QAXRoleType;
-#define QAXApplicationRole NSAccessibilityApplicationRole
-#define QAXButtonRole NSAccessibilityButtonRole
-#define QAXCancelAction NSAccessibilityCancelAction
-#define QAXCheckBoxRole NSAccessibilityCheckBoxRole
-#define QAXChildrenAttribute NSAccessibilityChildrenAttribute
-#define QAXCloseButtonAttribute NSAccessibilityCloseButtonAttribute
-#define QAXCloseButtonAttribute NSAccessibilityCloseButtonAttribute
-#define QAXColumnRole NSAccessibilityColumnRole
-#define QAXConfirmAction NSAccessibilityConfirmAction
-#define QAXContentsAttribute NSAccessibilityContentsAttribute
-#define QAXDecrementAction NSAccessibilityDecrementAction
-#define QAXDecrementArrowSubrole NSAccessibilityDecrementArrowSubrole
-#define QAXDecrementPageSubrole NSAccessibilityDecrementPageSubrole
-#define QAXDescriptionAttribute NSAccessibilityDescriptionAttribute
-#define QAXEnabledAttribute NSAccessibilityEnabledAttribute
-#define QAXExpandedAttribute NSAccessibilityExpandedAttribute
-#define QAXFocusedAttribute NSAccessibilityFocusedAttribute
-#define QAXFocusedUIElementChangedNotification NSAccessibilityFocusedUIElementChangedNotification
-#define QAXFocusedWindowChangedNotification NSAccessibilityFocusedWindowChangedNotification
-#define QAXGroupRole NSAccessibilityGroupRole
-#define QAXGrowAreaAttribute NSAccessibilityGrowAreaAttribute
-#define QAXGrowAreaRole NSAccessibilityGrowAreaRole
-#define QAXHelpAttribute NSAccessibilityHelpAttribute
-#define QAXHorizontalOrientationValue NSAccessibilityHorizontalOrientationValue
-#define QAXHorizontalScrollBarAttribute NSAccessibilityHorizontalScrollBarAttribute
-#define QAXIncrementAction NSAccessibilityIncrementAction
-#define QAXIncrementArrowSubrole NSAccessibilityIncrementArrowSubrole
-#define QAXIncrementPageSubrole NSAccessibilityIncrementPageSubrole
-#define QAXIncrementorRole NSAccessibilityIncrementorRole
-#define QAXLinkedUIElementsAttribute NSAccessibilityLinkedUIElementsAttribute
-#define QAXListRole NSAccessibilityListRole
-#define QAXMainAttribute NSAccessibilityMainAttribute
-#define QAXMaxValueAttribute NSAccessibilityMaxValueAttribute
-#define QAXMenuBarRole NSAccessibilityMenuBarRole
-#define QAXMenuButtonRole NSAccessibilityMenuButtonRole
-#define QAXMenuClosedNotification NSAccessibilityMenuClosedNotification
-#define QAXMenuItemRole NSAccessibilityMenuItemRole
-#define QAXMenuOpenedNotification NSAccessibilityMenuOpenedNotification
-#define QAXMenuRole NSAccessibilityMenuRole
-#define QAXMinValueAttribute NSAccessibilityMinValueAttribute
-#define QAXMinimizeButtonAttribute NSAccessibilityMinimizeButtonAttribute
-#define QAXMinimizedAttribute NSAccessibilityMinimizedAttribute
-#define QAXNextContentsAttribute NSAccessibilityNextContentsAttribute
-#define QAXOrientationAttribute NSAccessibilityOrientationAttribute
-#define QAXParentAttribute NSAccessibilityParentAttribute
-#define QAXPickAction NSAccessibilityPickAction
-#define QAXPopUpButtonRole NSAccessibilityPopUpButtonRole
-#define QAXPositionAttribute NSAccessibilityPositionAttribute
-#define QAXPressAction NSAccessibilityPressAction
-#define QAXPreviousContentsAttribute NSAccessibilityPreviousContentsAttribute
-#define QAXProgressIndicatorRole NSAccessibilityProgressIndicatorRole
-#define QAXRadioButtonRole NSAccessibilityRadioButtonRole
-#define QAXRoleAttribute NSAccessibilityRoleAttribute
-#define QAXRoleDescriptionAttribute NSAccessibilityRoleDescriptionAttribute
-#define QAXRowRole NSAccessibilityRowRole
-#define QAXRowsAttribute NSAccessibilityRowsAttribute
-#define QAXScrollAreaRole NSAccessibilityScrollAreaRole
-#define QAXScrollBarRole NSAccessibilityScrollBarRole
-#define QAXSelectedAttribute NSAccessibilitySelectedAttribute
-#define QAXSelectedChildrenAttribute NSAccessibilitySelectedChildrenAttribute
-#define QAXSelectedRowsAttribute NSAccessibilitySelectedRowsAttribute
-#define QAXSizeAttribute NSAccessibilitySizeAttribute
-#define QAXSliderRole NSAccessibilitySliderRole
-#define QAXSplitGroupRole NSAccessibilitySplitGroupRole
-#define QAXSplitterRole NSAccessibilitySplitterRole
-#define QAXSplittersAttribute NSAccessibilitySplittersAttribute
-#define QAXStaticTextRole NSAccessibilityStaticTextRole
-#define QAXSubroleAttribute NSAccessibilitySubroleAttribute
-#define QAXSubroleAttribute NSAccessibilitySubroleAttribute
-#define QAXTabGroupRole NSAccessibilityTabGroupRole
-#define QAXTableRole NSAccessibilityTableRole
-#define QAXTabsAttribute NSAccessibilityTabsAttribute
-#define QAXTextFieldRole NSAccessibilityTextFieldRole
-#define QAXTitleAttribute NSAccessibilityTitleAttribute
-#define QAXTitleUIElementAttribute NSAccessibilityTitleUIElementAttribute
-#define QAXToolbarButtonAttribute NSAccessibilityToolbarButtonAttribute
-#define QAXToolbarRole NSAccessibilityToolbarRole
-#define QAXTopLevelUIElementAttribute NSAccessibilityTopLevelUIElementAttribute
-#define QAXUnknownRole NSAccessibilityUnknownRole
-#define QAXValueAttribute NSAccessibilityValueAttribute
-#define QAXValueChangedNotification NSAccessibilityValueChangedNotification
-#define QAXValueIndicatorRole NSAccessibilityValueIndicatorRole
-#define QAXVerticalOrientationValue NSAccessibilityVerticalOrientationValue
-#define QAXVerticalScrollBarAttribute NSAccessibilityVerticalScrollBarAttribute
-#define QAXVisibleRowsAttribute NSAccessibilityVisibleRowsAttribute
-#define QAXWindowAttribute NSAccessibilityWindowAttribute
-#define QAXWindowCreatedNotification NSAccessibilityWindowCreatedNotification
-#define QAXWindowMovedNotification NSAccessibilityWindowMovedNotification
-#define QAXWindowRole NSAccessibilityWindowRole
-#define QAXZoomButtonAttribute NSAccessibilityZoomButtonAttribute
-#else
-typedef CFStringRef const QAXRoleType;
-#define QAXApplicationRole kAXApplicationRole
-#define QAXButtonRole kAXButtonRole
-#define QAXCancelAction kAXCancelAction
-#define QAXCheckBoxRole kAXCheckBoxRole
-#define QAXChildrenAttribute kAXChildrenAttribute
-#define QAXCloseButtonAttribute kAXCloseButtonAttribute
-#define QAXColumnRole kAXColumnRole
-#define QAXConfirmAction kAXConfirmAction
-#define QAXContentsAttribute kAXContentsAttribute
-#define QAXDecrementAction kAXDecrementAction
-#define QAXDecrementArrowSubrole kAXDecrementArrowSubrole
-#define QAXDecrementPageSubrole kAXDecrementPageSubrole
-#define QAXDescriptionAttribute kAXDescriptionAttribute
-#define QAXEnabledAttribute kAXEnabledAttribute
-#define QAXExpandedAttribute kAXExpandedAttribute
-#define QAXFocusedAttribute kAXFocusedAttribute
-#define QAXFocusedUIElementChangedNotification kAXFocusedUIElementChangedNotification
-#define QAXFocusedWindowChangedNotification kAXFocusedWindowChangedNotification
-#define QAXGroupRole kAXGroupRole
-#define QAXGrowAreaAttribute kAXGrowAreaAttribute
-#define QAXGrowAreaRole kAXGrowAreaRole
-#define QAXHelpAttribute kAXHelpAttribute
-#define QAXHorizontalOrientationValue kAXHorizontalOrientationValue
-#define QAXHorizontalScrollBarAttribute kAXHorizontalScrollBarAttribute
-#define QAXIncrementAction kAXIncrementAction
-#define QAXIncrementArrowSubrole kAXIncrementArrowSubrole
-#define QAXIncrementPageSubrole kAXIncrementPageSubrole
-#define QAXIncrementorRole kAXIncrementorRole
-#define QAXLinkedUIElementsAttribute kAXLinkedUIElementsAttribute
-#define QAXListRole kAXListRole
-#define QAXMainAttribute kAXMainAttribute
-#define QAXMaxValueAttribute kAXMaxValueAttribute
-#define QAXMenuBarRole kAXMenuBarRole
-#define QAXMenuButtonRole kAXMenuButtonRole
-#define QAXMenuClosedNotification kAXMenuClosedNotification
-#define QAXMenuItemRole kAXMenuItemRole
-#define QAXMenuOpenedNotification kAXMenuOpenedNotification
-#define QAXMenuRole kAXMenuRole
-#define QAXMinValueAttribute kAXMinValueAttribute
-#define QAXMinimizeButtonAttribute kAXMinimizeButtonAttribute
-#define QAXMinimizedAttribute kAXMinimizedAttribute
-#define QAXNextContentsAttribute kAXNextContentsAttribute
-#define QAXOrientationAttribute kAXOrientationAttribute
-#define QAXParentAttribute kAXParentAttribute
-#define QAXPickAction kAXPickAction
-#define QAXPopUpButtonRole kAXPopUpButtonRole
-#define QAXPositionAttribute kAXPositionAttribute
-#define QAXPressAction kAXPressAction
-#define QAXPreviousContentsAttribute kAXPreviousContentsAttribute
-#define QAXProgressIndicatorRole kAXProgressIndicatorRole
-#define QAXRadioButtonRole kAXRadioButtonRole
-#define QAXRoleAttribute kAXRoleAttribute
-#define QAXRoleDescriptionAttribute kAXRoleDescriptionAttribute
-#define QAXRowRole kAXRowRole
-#define QAXRowsAttribute kAXRowsAttribute
-#define QAXScrollAreaRole kAXScrollAreaRole
-#define QAXScrollBarRole kAXScrollBarRole
-#define QAXSelectedAttribute kAXSelectedAttribute
-#define QAXSelectedChildrenAttribute kAXSelectedChildrenAttribute
-#define QAXSelectedRowsAttribute kAXSelectedRowsAttribute
-#define QAXSizeAttribute kAXSizeAttribute
-#define QAXSliderRole kAXSliderRole
-#define QAXSplitGroupRole kAXSplitGroupRole
-#define QAXSplitterRole kAXSplitterRole
-#define QAXSplittersAttribute kAXSplittersAttribute
-#define QAXStaticTextRole kAXStaticTextRole
-#define QAXSubroleAttribute kAXSubroleAttribute
-#define QAXTabGroupRole kAXTabGroupRole
-#define QAXTableRole kAXTableRole
-#define QAXTabsAttribute kAXTabsAttribute
-#define QAXTextFieldRole kAXTextFieldRole
-#define QAXTitleAttribute kAXTitleAttribute
-#define QAXTitleUIElementAttribute kAXTitleUIElementAttribute
-#define QAXToolbarButtonAttribute kAXToolbarButtonAttribute
-#define QAXToolbarRole kAXToolbarRole
-#define QAXTopLevelUIElementAttribute kAXTopLevelUIElementAttribute
-#define QAXUnknownRole kAXUnknownRole
-#define QAXValueAttribute kAXValueAttribute
-#define QAXValueChangedNotification kAXValueChangedNotification
-#define QAXValueIndicatorRole kAXValueIndicatorRole
-#define QAXVerticalOrientationValue kAXVerticalOrientationValue
-#define QAXVerticalScrollBarAttribute kAXVerticalScrollBarAttribute
-#define QAXVisibleRowsAttribute kAXVisibleRowsAttribute
-#define QAXWindowAttribute kAXWindowAttribute
-#define QAXWindowCreatedNotification kAXWindowCreatedNotification
-#define QAXWindowMovedNotification kAXWindowMovedNotification
-#define QAXWindowRole kAXWindowRole
-#define QAXZoomButtonAttribute kAXZoomButtonAttribute
-#endif
-
-
-/*****************************************************************************
-  Externals
- *****************************************************************************/
-extern bool qt_mac_is_macsheet(const QWidget *w); //qwidget_mac.cpp
-extern bool qt_mac_is_macdrawer(const QWidget *w); //qwidget_mac.cpp
-
-/*****************************************************************************
-  QAccessible Bindings
- *****************************************************************************/
-//hardcoded bindings between control info and (known) QWidgets
-struct QAccessibleTextBinding {
-    int qt;
-    QAXRoleType mac;
-    bool settable;
-} text_bindings[][10] = {
-    { { QAccessible::MenuItem, QAXMenuItemRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::MenuBar, QAXMenuBarRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ScrollBar, QAXScrollBarRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Grip, QAXGrowAreaRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Window, QAXWindowRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Dialog, QAXWindowRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::AlertMessage, QAXWindowRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ToolTip, QAXWindowRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::HelpBalloon, QAXWindowRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::PopupMenu, QAXMenuRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Application, QAXApplicationRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Pane, QAXGroupRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Grouping, QAXGroupRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Separator, QAXSplitterRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ToolBar, QAXToolbarRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::PageTab, QAXRadioButtonRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ButtonMenu, QAXMenuButtonRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ButtonDropDown, QAXPopUpButtonRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::SpinBox, QAXIncrementorRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Slider, QAXSliderRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ProgressBar, QAXProgressIndicatorRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ComboBox, QAXPopUpButtonRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::RadioButton, QAXRadioButtonRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::CheckBox, QAXCheckBoxRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::StaticText, QAXStaticTextRole, false },
-      { QAccessible::Name, QAXValueAttribute, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Table, QAXTableRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::StatusBar, QAXStaticTextRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Column, QAXColumnRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ColumnHeader, QAXColumnRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Row, QAXRowRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::RowHeader, QAXRowRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Cell, QAXTextFieldRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::PushButton, QAXButtonRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::EditableText, QAXTextFieldRole, true },
-      { -1, 0, false }
-    },
-    { { QAccessible::Link, QAXTextFieldRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Indicator, QAXValueIndicatorRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Splitter, QAXSplitGroupRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::List, QAXListRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::ListItem, QAXStaticTextRole, false },
-      { -1, 0, false }
-    },
-    { { QAccessible::Cell, QAXStaticTextRole, false },
-      { -1, 0, false }
-    },
-    { { -1, 0, false } }
-};
-
-class QAInterface;
-static CFStringRef macRole(const QAInterface &interface);
-
-QDebug operator<<(QDebug debug, const QAInterface &interface)
-{
-    if (interface.isValid() == false)
-        debug << "invalid interface";
-    else 
-        debug << interface.object() << "id" << interface.id() << "role" << hex << interface.role();
-    return debug;
-}
-
-// The root of the Qt accessible hiearchy.
-static QObject *rootObject = 0;
-
-
-bool QAInterface::operator==(const QAInterface &other) const
-{
-    if (isValid() == false || other.isValid() == false)
-        return (isValid() && other.isValid());
-    
-    // walk up the parent chain, comparing child indexes, until we reach
-    // an interface that has a QObject.
-    QAInterface currentThis = *this;
-    QAInterface currentOther = other;
-    
-    while (currentThis.object() == 0) {
-        if (currentOther.object() != 0)
-            return false;
-
-        // fail if the child indexes in the two hirearchies don't match.
-        if (currentThis.parent().indexOfChild(currentThis) !=
-            currentOther.parent().indexOfChild(currentOther))
-            return false;
-
-        currentThis = currentThis.parent();
-        currentOther = currentOther.parent();
-    }
-    
-    return (currentThis.object() == currentOther.object() && currentThis.id() == currentOther.id());
-}
-
-bool QAInterface::operator!=(const QAInterface &other) const
-{
-    return !operator==(other);
-}
-
-uint qHash(const QAInterface &item)
-{
-    if (item.isValid())
-        return qHash(item.object()) + qHash(item.id());
-    else
-        return qHash(item.cachedObject()) + qHash(item.id());
-}
-
-QAInterface QAInterface::navigate(RelationFlag relation, int entry) const
-{
-        if (!checkValid())
-            return QAInterface();
-
-    // On a QAccessibleInterface that handles its own children we can short-circut
-    // the navigation if this QAInterface refers to one of the children:
-    if (child != 0) {
-        // The Ancestor interface will always be the same QAccessibleInterface with
-        // a child value of 0.
-        if (relation == QAccessible::Ancestor)
-            return QAInterface(*this, 0);
-
-        // The child hiearchy is only one level deep, so navigating to a child
-        // of a child is not possible.
-        if (relation == QAccessible::Child) {
-            return QAInterface();
-        }
-    }
-    QAccessibleInterface *child_iface = 0;
-
-    const int status = base.interface->navigate(relation, entry, &child_iface);
-
-    if (status == -1)
-        return QAInterface(); // not found;
-
-    // Check if target is a child of this interface.
-    if (!child_iface) {
-        return QAInterface(*this, status);
-    } else {
-        // Target is child_iface or a child of that (status decides).
-        return QAInterface(child_iface, status);
-    }
-}
-
-QAElement::QAElement()
-:elementRef(0)
-{}
-
-QAElement::QAElement(AXUIElementRef elementRef)
-:elementRef(elementRef)
-{
-    if (elementRef != 0) {
-        CFRetain(elementRef);
-        CFRetain(object());
-    }
-}
-
-QAElement::QAElement(const QAElement &element)
-:elementRef(element.elementRef)
-{
-    if (elementRef != 0) {
-        CFRetain(elementRef);
-        CFRetain(object());
-    }
-}
-
-QAElement::QAElement(HIObjectRef object, int child)
-{
-#ifndef QT_MAC_USE_COCOA
-    if (object == 0) {
-        elementRef = 0; // Create invalid QAElement.
-    } else {
-        elementRef = AXUIElementCreateWithHIObjectAndIdentifier(object, child);
-        CFRetain(object);
-    }
-#else
-    Q_UNUSED(object);
-    Q_UNUSED(child);
-#endif
-}
-
-QAElement::~QAElement()
-{
-    if (elementRef != 0) {
-        CFRelease(object());
-        CFRelease(elementRef);
-    }
-}
-
-void QAElement::operator=(const QAElement &other)
-{
-    if (*this == other)
-        return;
-
-    if (elementRef != 0) {
-        CFRelease(object());
-        CFRelease(elementRef);
-    }
-
-    elementRef = other.elementRef;
-
-    if (elementRef != 0) {
-        CFRetain(elementRef);
-        CFRetain(object());
-    }
-}
-
-bool QAElement::operator==(const QAElement &other) const
-{
-    if (elementRef == 0 || other.elementRef == 0)
-        return (elementRef == other.elementRef);
-
-    return CFEqual(elementRef, other.elementRef);
-}
-
-uint qHash(QAElement element)
-{
-    return qHash(element.object()) + qHash(element.id());
-}
-
-#ifndef QT_MAC_USE_COCOA
-static QInterfaceFactory *createFactory(const QAInterface &interface);
-#endif
-Q_GLOBAL_STATIC(QAccessibleHierarchyManager, accessibleHierarchyManager);
-
-/*
-    Reomves all accessibility info accosiated with the sender object.
-*/
-void QAccessibleHierarchyManager::objectDestroyed(QObject *object)
-{
-    HIObjectRef hiObject = qobjectHiobjectHash.value(object);
-    delete qobjectElementHash.value(object);
-    qobjectElementHash.remove(object);
-    hiobjectInterfaceHash.remove(hiObject);
-}
-
-/*
-    Removes all stored items.
-*/
-void QAccessibleHierarchyManager::reset()
-{
-    qDeleteAll(qobjectElementHash);
-    qobjectElementHash.clear();
-    hiobjectInterfaceHash.clear();
-    qobjectHiobjectHash.clear();
-}
-
-QAccessibleHierarchyManager *QAccessibleHierarchyManager::instance()
-{
-    return accessibleHierarchyManager();
-}
-
-#ifndef QT_MAC_USE_COCOA
-static bool isItemView(const QAInterface &interface)
-{
-    QObject *object = interface.object();
-    return (interface.role() == QAccessible::List || interface.role() == QAccessible::Table
-            || (object && qobject_cast<QAbstractItemView *>(interface.object()))
-            || (object && object->objectName() == QLatin1String("qt_scrollarea_viewport")
-                && qobject_cast<QAbstractItemView *>(object->parent())));
-}
-#endif
-
-static bool isTabWidget(const QAInterface &interface)
-{
-    if (QObject *object = interface.object())
-        return (object->inherits("QTabWidget") && interface.id() == 0);
-    return false;
-}
-
-static bool isStandaloneTabBar(const QAInterface &interface)
-{
-    QObject *object = interface.object();
-    if (interface.role() == QAccessible::PageTabList && object)
-        return (qobject_cast<QTabWidget *>(object->parent()) == 0);
-
-    return false;
-}
-
-static bool isEmbeddedTabBar(const QAInterface &interface)
-{
-    QObject *object = interface.object();
-    if (interface.role() == QAccessible::PageTabList && object)
-        return (qobject_cast<QTabWidget *>(object->parent()));
-
-    return false;
-}
-
-/*
-    Decides if a QAInterface is interesting from an accessibility users point of view.
-*/
-bool isItInteresting(const QAInterface &interface)
-{
-    // Mac accessibility does not have an attribute that corresponds to the Invisible/Offscreen
-    // state, so we disable the interface here.
-    const QAccessible::State state = interface.state();
-    if (state & QAccessible::Invisible ||
-        state & QAccessible::Offscreen )
-        return false;
-
-    const QAccessible::Role role = interface.role();
-
-    if (QObject * const object = interface.object()) {
-        const QString className = QLatin1String(object->metaObject()->className());
-
-        // VoiceOver focusing on tool tips can be confusing. The contents of the
-        // tool tip is avalible through the description attribute anyway, so
-        // we disable accessibility for tool tips.
-        if (className == QLatin1String("QTipLabel"))
-            return false;
-
-        // Hide TabBars that has a QTabWidget parent (the tab widget handles the accessibility)
-        if (isEmbeddedTabBar(interface))
-            return false;
-
-         // Hide docked dockwidgets. ### causes infinitie loop in the apple accessibility code.
-     /*    if (QDockWidget *dockWidget = qobject_cast<QDockWidget *>(object)) {
-            if (dockWidget->isFloating() == false)
-                return false;        
-         }
-    */
-    }
-
-    // Client is a generic role returned by plain QWidgets or other
-    // widgets that does not have separate QAccessible interface, such
-    // as the TabWidget. Return false unless macRole gives the interface
-    // a special role.
-    if (role == QAccessible::Client && macRole(interface) == CFStringRef(QAXUnknownRole))
-        return false;
-
-    // Some roles are not interesting:
-    if (role == QAccessible::Border ||    // QFrame
-        role == QAccessible::Application || // We use the system-provided application element.
-        role == QAccessible::MenuItem)      // The system also provides the menu items.
-        return false;
-
-    // It is probably better to access the toolbar buttons directly than having
-    // to navigate through the toolbar.
-    if (role == QAccessible::ToolBar)
-        return false;
-
-    return true;
-}
-
-QAElement QAccessibleHierarchyManager::registerInterface(QObject *object, int child)
-{
-#ifndef QT_MAC_USE_COCOA
-    return registerInterface(QAInterface(QAccessible::queryAccessibleInterface(object), child));
-#else
-    Q_UNUSED(object);
-    Q_UNUSED(child);
-    return QAElement();
-#endif
-}
-
-/*
-    Creates a QAXUIelement that corresponds to the given QAInterface.
-*/
-QAElement QAccessibleHierarchyManager::registerInterface(const QAInterface &interface)
-{
-#ifndef QT_MAC_USE_COCOA
-    if (interface.isValid() == false)
-        return QAElement();
-    QAInterface objectInterface = interface.objectInterface();
-
-    QObject * qobject = objectInterface.object();
-    HIObjectRef hiobject = objectInterface.hiObject();
-    if (qobject == 0 || hiobject == 0)
-        return QAElement();
-
-    if (qobjectElementHash.contains(qobject) == false) {
-        registerInterface(qobject, hiobject, createFactory(interface));
-        HIObjectSetAccessibilityIgnored(hiobject, !isItInteresting(interface));
-    }
-
-    return QAElement(hiobject, interface.id());
-#else
-    Q_UNUSED(interface);
-    return QAElement();
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-#include "qaccessible_mac_carbon.cpp"
-#endif
-
-void QAccessibleHierarchyManager::registerInterface(QObject * qobject, HIObjectRef hiobject, QInterfaceFactory *interfaceFactory)
-{
-#ifndef QT_MAC_USE_COCOA
-    if (qobjectElementHash.contains(qobject) == false) {
-        qobjectElementHash.insert(qobject, interfaceFactory);
-        qobjectHiobjectHash.insert(qobject, hiobject);
-        connect(qobject, SIGNAL(destroyed(QObject *)), SLOT(objectDestroyed(QObject *)));
-    }
-
-    if (hiobjectInterfaceHash.contains(hiobject) == false) {
-        hiobjectInterfaceHash.insert(hiobject, interfaceFactory);
-        installAcessibilityEventHandler(hiobject);
-    }
-#else
-    Q_UNUSED(qobject);
-    Q_UNUSED(hiobject);
-    Q_UNUSED(interfaceFactory);
-#endif
-}
-
-void QAccessibleHierarchyManager::registerChildren(const QAInterface &interface)
-{
-    QObject * const object = interface.object();
-    if (object == 0)
-        return;
-
-    QInterfaceFactory *interfaceFactory = qobjectElementHash.value(object);
-    
-    if (interfaceFactory == 0)
-        return;
-
-    interfaceFactory->registerChildren();
-}
-
-QAInterface QAccessibleHierarchyManager::lookup(const AXUIElementRef &element)
-{
-     if (element == 0)
-        return QAInterface();
-#ifndef QT_MAC_USE_COCOA
-    HIObjectRef hiObject = AXUIElementGetHIObject(element);
-
-    QInterfaceFactory *factory = hiobjectInterfaceHash.value(hiObject);
-    if (factory == 0) {
-        return QAInterface();
-    }
-
-    UInt64 id;
-    AXUIElementGetIdentifier(element, &id);
-    return factory->interface(id);
-#else
-    return QAInterface();
-#endif
-}
-
-QAInterface QAccessibleHierarchyManager::lookup(const QAElement &element)
-{
-    return lookup(element.element());
-}
-
-QAElement QAccessibleHierarchyManager::lookup(const QAInterface &interface)
-{
-    if (interface.isValid() == false)
-        return QAElement();
-
-    QInterfaceFactory *factory = qobjectElementHash.value(interface.objectInterface().object());
-    if (factory == 0)
-        return QAElement();
-
-    return factory->element(interface);
-}
-
-QAElement QAccessibleHierarchyManager::lookup(QObject * const object, int id)
-{
-    QInterfaceFactory *factory = qobjectElementHash.value(object);
-    if (factory == 0)
-        return QAElement();
-
-    return factory->element(id);
-}
-
-/*
-    Standard interface mapping, return the stored interface
-    or HIObjectRef, and there is an one-to-one mapping between
-    the identifier and child.
-*/
-class QStandardInterfaceFactory : public QInterfaceFactory
-{
-public:
-    QStandardInterfaceFactory(const QAInterface &interface)
-    : m_interface(interface), object(interface.hiObject())
-    {
-        CFRetain(object);
-    }
-    
-    ~QStandardInterfaceFactory()
-    {
-         CFRelease(object);
-    }
-
-    
-    QAInterface interface(UInt64 identifier)
-    {
-        const int child = identifier;
-        return QAInterface(m_interface, child);
-    }
-
-    QAElement element(int id)
-    {
-        return QAElement(object, id);
-    }
-
-    QAElement element(const QAInterface &interface)
-    {
-        if (interface.object() == 0)
-            return QAElement();
-        return QAElement(object, interface.id());
-    }
-
-    void registerChildren()
-    {
-        const int childCount = m_interface.childCount();
-        for (int i = 1; i <= childCount; ++i) {
-            accessibleHierarchyManager()->registerInterface(m_interface.navigate(QAccessible::Child, i));
-        }
-    }
-
-private:
-    QAInterface m_interface;
-    HIObjectRef object;
-};
-
-/*
-    Interface mapping where that creates one HIObject for each interface child.
-*/
-class QMultipleHIObjectFactory : public QInterfaceFactory
-{
-public:
-    QMultipleHIObjectFactory(const QAInterface &interface)
-    : m_interface(interface)
-    {  }
-    
-    ~QMultipleHIObjectFactory()
-    {
-        foreach (HIObjectRef object, objects) {
-            CFRelease(object);
-        }
-    }
-
-    QAInterface interface(UInt64 identifier)
-    {
-        const int child = identifier;
-        return QAInterface(m_interface, child);
-    }
-
-    QAElement element(int child)
-    {
-        if (child == 0)
-            return QAElement(m_interface.hiObject(), 0);
-        
-        if (child > objects.count())
-            return QAElement();
-
-        return QAElement(objects.at(child - 1), child);
-    }
-
-    void registerChildren()
-    {
-#ifndef QT_MAC_USE_COCOA
-        const int childCount = m_interface.childCount();
-        for (int i = 1; i <= childCount; ++i) {
-            HIObjectRef hiobject;
-            HIObjectCreate(kObjectQtAccessibility, 0, &hiobject);
-            objects.append(hiobject);
-              accessibleHierarchyManager()->registerInterface(m_interface.object(), hiobject, this);
-            HIObjectSetAccessibilityIgnored(hiobject, !isItInteresting(m_interface.navigate(QAccessible::Child, i)));
-        }
-#endif
-    }
-
-private:
-    QAInterface m_interface;
-    QList<HIObjectRef> objects;
-};
-
-class QItemViewInterfaceFactory : public QInterfaceFactory
-{
-public:
-    QItemViewInterfaceFactory(const QAInterface &interface)
-    : m_interface(interface), object(interface.hiObject())
-    {
-        CFRetain(object);
-        columnCount = 0;
-        if (QTableView * tableView = qobject_cast<QTableView *>(interface.parent().object())) {
-            if (tableView->model())
-                columnCount = tableView->model()->columnCount();
-            if (tableView->verticalHeader())
-                ++columnCount;
-        }
-    }
-    
-    ~QItemViewInterfaceFactory()
-    {
-        CFRelease(object);
-    }
-
-    QAInterface interface(UInt64 identifier)
-    {
-        if (identifier == 0)
-            return m_interface;
-
-        if (m_interface.role() == QAccessible::List)
-            return m_interface.childAt(identifier);
-        
-        if (m_interface.role() == QAccessible::Table) {
-            const int index = identifier;
-            if (index == 0)
-                return m_interface; // return the item view interface.
-           
-            const int rowIndex = (index - 1) / (columnCount + 1);
-            const int cellIndex = (index - 1)  % (columnCount + 1);
-/*
-            qDebug() << "index" << index;
-            qDebug() << "rowIndex" << rowIndex;
-            qDebug() << "cellIndex" << cellIndex;
-*/
-            const QAInterface rowInterface = m_interface.childAt(rowIndex + 1);
-
-            if ((cellIndex) == 0) // Is it a row?
-                return rowInterface;
-            else {
-                return rowInterface.childAt(cellIndex);
-            }
-        }
-
-        return QAInterface();
-    }
-
-    QAElement element(int id)
-    {
-        if (id != 0) {
-            return QAElement();
-        }
-        return QAElement(object, 0);
-    }
-
-    QAElement element(const QAInterface &interface)
-    {
-        if (interface.object() && interface.object() == m_interface.object()) {
-            return QAElement(object, 0);
-        } else if (m_interface.role() == QAccessible::List) {
-            if (interface.parent().object() && interface.parent().object() == m_interface.object())
-                return QAElement(object, m_interface.indexOfChild(interface));
-        } else if (m_interface.role() == QAccessible::Table) {
-            QAInterface currentInterface = interface;
-            int index = 0;
-
-            while (currentInterface.isValid() && currentInterface.object() == 0) {
-                const QAInterface parentInterface = currentInterface.parent();
-/*
-                qDebug() << "current index" << index;
-                qDebug() << "current interface" << interface;
-
-                qDebug() << "parent interface" << parentInterface;
-                qDebug() << "grandparent interface" << parentInterface.parent();
-                qDebug() << "childCount" << interface.childCount();
-                qDebug() << "index of child" << parentInterface.indexOfChild(currentInterface);
-*/
-                index += ((parentInterface.indexOfChild(currentInterface) - 1) * (currentInterface.childCount() + 1)) + 1;
-                currentInterface = parentInterface;
-//                qDebug() << "new current interface" << currentInterface;
-            }
-            if (currentInterface.object() == m_interface.object())
-                return QAElement(object, index);
-
-
-        }
-        return QAElement();
-    }
-
-    void registerChildren()
-    {
-        // Item view child interfraces don't have their own qobjects, so there is nothing to register here.
-    }
-
-private:
-    QAInterface m_interface;
-    HIObjectRef object;
-    int columnCount; // for table views;
-};
-
-#ifndef QT_MAC_USE_COCOA
-static bool managesChildren(const QAInterface &interface)
-{
-    return (interface.childCount() > 0 && interface.childAt(1).id() > 0);
-}
-
-static QInterfaceFactory *createFactory(const QAInterface &interface)
-{
-    if (isItemView(interface)) {
-        return new QItemViewInterfaceFactory(interface);
-    }  if (managesChildren(interface)) {
-        return new QMultipleHIObjectFactory(interface);
-    }
-
-    return new QStandardInterfaceFactory(interface);
-}
-#endif
-
-QList<QAElement> lookup(const QList<QAInterface> &interfaces)
-{
-    QList<QAElement> elements;
-    foreach (const QAInterface &interface, interfaces)
-        if (interface.isValid()) {
-            const QAElement element = accessibleHierarchyManager()->lookup(interface);
-            if (element.isValid())
-                elements.append(element);
-        }
-    return elements;
-}
-
-// Debug output helpers:
-/*
-static QString nameForEventKind(UInt32 kind)
-{
-    switch(kind) {
-        case kEventAccessibleGetChildAtPoint:       return QString("GetChildAtPoint");      break;
-        case kEventAccessibleGetAllAttributeNames:  return QString("GetAllAttributeNames"); break;
-        case kEventAccessibleGetNamedAttribute:     return QString("GetNamedAttribute");    break;
-        case kEventAccessibleSetNamedAttribute:     return QString("SetNamedAttribute");    break;
-        case kEventAccessibleGetAllActionNames:     return QString("GetAllActionNames");    break;
-        case kEventAccessibleGetFocusedChild:       return QString("GetFocusedChild");      break;
-        default:
-            return QString("Unknown accessibility event type: %1").arg(kind);
-        break;
-    };
-}
-*/
-#ifndef QT_MAC_USE_COCOA
-static bool qt_mac_append_cf_uniq(CFMutableArrayRef array, CFTypeRef value)
-{
-    if (value == 0)
-        return false; 
-
-    CFRange range;
-    range.location = 0;
-    range.length = CFArrayGetCount(array);
-    if(!CFArrayContainsValue(array, range, value)) {
-        CFArrayAppendValue(array, value);
-        return true;
-    }
-    return false;
-}
-
-static OSStatus setAttributeValue(EventRef event, const QList<QAElement> &elements)
-{
-    CFMutableArrayRef array = CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks);
-    foreach (const QAElement &element, elements) {
-        if (element.isValid())
-            CFArrayAppendValue(array, element.element());
-    }
-
-    const OSStatus err = SetEventParameter(event, kEventParamAccessibleAttributeValue, 
-                                           typeCFTypeRef, sizeof(array), &array);
-    CFRelease(array);
-    return err;
-}
-#endif //QT_MAC_USE_COCOA
-
-/*
-    The application event handler makes sure that all top-level qt windows are registered
-    before any accessibility events are handeled.
-*/
-#ifndef QT_MAC_USE_COCOA
-static OSStatus applicationEventHandler(EventHandlerCallRef next_ref, EventRef event, void *)
-{
-    QAInterface rootInterface(QAccessible::queryAccessibleInterface(rootObject ? rootObject : qApp), 0);
-    accessibleHierarchyManager()->registerChildren(rootInterface);
-
-    return CallNextEventHandler(next_ref, event);
-}
-
-/*
-    Returns the value for element by combining the QAccessibility::Checked and
-    QAccessibility::Mixed flags into an int value that the Mac accessibilty
-    system understands. This works for check boxes, radio buttons, and the like.
-    The return values are:
-    0: unchecked
-    1: checked
-    2: undecided
-*/
-static int buttonValue(QAInterface element)
-{
-    const QAccessible::State state = element.state();
-    if (state & QAccessible::Mixed)
-        return 2;
-    else if(state & QAccessible::Checked)
-        return 1;
-    else
-        return 0;
-}
-
-static QString getValue(const QAInterface &interface)
-{
-    const QAccessible::Role role = interface.role();
-    if (role == QAccessible::RadioButton || role == QAccessible::CheckBox)
-        return QString::number(buttonValue(interface));
-    else
-        return interface.text(QAccessible::Value);
-}
-#endif //QT_MAC_USE_COCOA
-
-/*
-    Translates a QAccessible::Role into a mac accessibility role.
-*/
-static CFStringRef macRole(const QAInterface &interface)
-{
-    const QAccessible::Role qtRole = interface.role();
-
-//    qDebug() << "role for" << interface.object() << "interface role" << hex << qtRole;
-
-    // Qt accessibility:  QAccessible::Splitter contains QAccessible::Grip.
-    // Mac accessibility: AXSplitGroup contains AXSplitter.
-    if (qtRole == QAccessible::Grip) {
-        const QAInterface parent = interface.parent();
-        if (parent.isValid() && parent.role() == QAccessible::Splitter)
-            return CFStringRef(QAXSplitterRole);
-    }
-
-    // Tab widgets and standalone tab bars get the kAXTabGroupRole. Accessibility
-    // for tab bars emebedded in a tab widget is handled by the tab widget.
-    if (isTabWidget(interface) || isStandaloneTabBar(interface))
-        return kAXTabGroupRole;
-
-    if (QObject *object = interface.object()) {
-        // ### The interface for an abstract scroll area returns the generic "Client"
-        // role, so we have to to an extra detect on the QObject here.
-        if (object->inherits("QAbstractScrollArea") && interface.id() == 0)
-            return CFStringRef(QAXScrollAreaRole);
-
-        if (object->inherits("QDockWidget"))
-            return CFStringRef(QAXUnknownRole);
-    }
-
-    int i = 0;
-    int testRole = text_bindings[i][0].qt;
-    while (testRole != -1) {
-        if (testRole == qtRole)
-            return CFStringRef(text_bindings[i][0].mac);
-        ++i;
-        testRole = text_bindings[i][0].qt;
-    }
-
-//    qDebug() << "got unknown role!" << interface << interface.parent();
-
-    return CFStringRef(QAXUnknownRole);
-}
-
-/*
-    Translates a QAccessible::Role and an attribute name into a QAccessible::Text, taking into
-    account execptions listed in text_bindings.
-*/
-#ifndef QT_MAC_USE_COCOA
-static int textForRoleAndAttribute(QAccessible::Role role, CFStringRef attribute)
-{
-     // Search for exception, return it if found.
-    int testRole = text_bindings[0][0].qt;
-    int i = 0;
-    while (testRole != -1) {
-        if (testRole == role) {
-            int j = 1;
-            int qtRole = text_bindings[i][j].qt;
-            CFStringRef testAttribute = CFStringRef(text_bindings[i][j].mac);
-            while (qtRole != -1) {
-                if (CFStringCompare(attribute, testAttribute, 0) == kCFCompareEqualTo) {
-                    return (QAccessible::Text)qtRole;
-                }
-                ++j;
-                testAttribute = CFStringRef(text_bindings[i][j].mac); /// ### custom compare
-                qtRole = text_bindings[i][j].qt; /// ### custom compare
-            }
-            break;
-        }
-        ++i;
-        testRole = text_bindings[i][0].qt;
-    }
-
-    // Return default mappping
-    if (CFStringCompare(attribute, CFStringRef(QAXTitleAttribute), 0) == kCFCompareEqualTo)
-        return QAccessible::Name;
-    else if (CFStringCompare(attribute, CFStringRef(QAXValueAttribute), 0) == kCFCompareEqualTo)
-        return QAccessible::Value;
-    else if (CFStringCompare(attribute, CFStringRef(QAXHelpAttribute), 0) == kCFCompareEqualTo)
-        return QAccessible::Help;
-    else if (CFStringCompare(attribute, CFStringRef(QAXDescriptionAttribute), 0) == kCFCompareEqualTo)
-        return QAccessible::Description;
-    else
-        return -1;
-}
-
-/*
-    Returns the subrole string constant for the interface if it has one,
-    else returns an empty string.
-*/
-static QCFString subrole(const QAInterface &interface)
-{
-    const QAInterface parent = interface.parent();
-    if (parent.isValid() == false)
-        return QCFString();
-
-    if (parent.role() == QAccessible::ScrollBar) {
-        QCFString subrole;
-        switch(interface.id()) {
-            case 1: subrole = CFStringRef(QAXDecrementArrowSubrole); break;
-            case 2: subrole = CFStringRef(QAXDecrementPageSubrole); break;
-            case 4: subrole = CFStringRef(QAXIncrementPageSubrole); break;
-            case 5: subrole = CFStringRef(QAXIncrementArrowSubrole); break;
-            default:
-            break;
-        }
-        return subrole;
-    }
-    return QCFString();
-}
-
-// Gets the scroll bar orientation by asking the QAbstractSlider object directly.
-static Qt::Orientation scrollBarOrientation(const QAInterface &scrollBar)
-{
-    QObject *const object = scrollBar.object();
-    if (QAbstractSlider * const sliderObject = qobject_cast<QAbstractSlider * const>(object))
-        return sliderObject->orientation();
-
-    return Qt::Vertical; // D'oh! The interface wasn't a scroll bar.
-}
-
-static QAInterface scrollAreaGetScrollBarInterface(const QAInterface &scrollArea, Qt::Orientation orientation)
-{
-    if (macRole(scrollArea) != CFStringRef(CFStringRef(QAXScrollAreaRole)))
-        return QAInterface();
-
-    // Child 1 is the contents widget, 2 and 3 are the scroll bar containers wich contains possible scroll bars.
-    for (int i = 2; i <= 3; ++i) {
-        QAInterface scrollBarContainer = scrollArea.childAt(i);
-        for (int i = 1; i <= scrollBarContainer.childCount(); ++i) {
-            QAInterface scrollBar = scrollBarContainer.childAt(i);
-            if (scrollBar.isValid() &&
-                scrollBar.role() == QAccessible::ScrollBar &&
-                scrollBarOrientation(scrollBar) == orientation)
-                return scrollBar;
-        }
-    }
-
-    return QAInterface();
-}
-
-static bool scrollAreaHasScrollBar(const QAInterface &scrollArea, Qt::Orientation orientation)
-{
-    return scrollAreaGetScrollBarInterface(scrollArea, orientation).isValid();
-}
-
-static QAElement scrollAreaGetScrollBar(const QAInterface &scrollArea, Qt::Orientation orientation)
-{
-    return accessibleHierarchyManager()->lookup(scrollAreaGetScrollBarInterface(scrollArea, orientation));
-}
-
-static QAElement scrollAreaGetContents(const QAInterface &scrollArea)
-{
-    // Child 1 is the contents widget,
-    return accessibleHierarchyManager()->lookup(scrollArea.navigate(QAccessible::Child, 1));
-}
-
-static QAElement tabWidgetGetContents(const QAInterface &interface)
-{
-    // A kAXTabGroup has a kAXContents attribute, which consists of the
-    // ui elements for the current tab page. Get the current tab page
-    // from the QStackedWidget, where the current visible page can
-    // be found at index 1.
-    QAInterface stackedWidget = interface.childAt(1);
-    accessibleHierarchyManager()->registerChildren(stackedWidget);
-    QAInterface tabPageInterface = stackedWidget.childAt(1);
-    return accessibleHierarchyManager()->lookup(tabPageInterface);
-}
-
-static QList<QAElement> tabBarGetTabs(const QAInterface &interface)
-{
-    // Get the tabs by searching for children with the "PageTab" role.
-    // This filters out the left/right navigation buttons.
-    accessibleHierarchyManager()->registerChildren(interface);
-    QList<QAElement> tabs;
-    const int numChildren = interface.childCount();
-    for (int i = 1; i < numChildren + 1; ++i) {
-        QAInterface child = interface.navigate(QAccessible::Child, i);
-        if (child.isValid() && child.role() == QAccessible::PageTab) {
-            tabs.append(accessibleHierarchyManager()->lookup(child));
-        }
-    }
-    return tabs;
-}
-
-static QList<QAElement> tabWidgetGetTabs(const QAInterface &interface)
-{
-    // Each QTabWidget has two children, a QStackedWidget and a QTabBar.
-    // Get the tabs from the QTabBar.
-    return tabBarGetTabs(interface.childAt(2));
-}
-
-static QList<QAElement> tabWidgetGetChildren(const QAInterface &interface)
-{
-    // The children for a kAXTabGroup should consist of the tabs and the
-    // contents of the current open tab page.
-    QList<QAElement> children = tabWidgetGetTabs(interface);
-    children += tabWidgetGetContents(interface);
-    return children;
-}
-#endif //QT_MAC_USE_COCOA
-
-/*
-    Returns the label (buddy) interface for interface, or 0 if it has none.
-*/
-/*
-static QAInterface findLabel(const QAInterface &interface)
-{
-    return interface.navigate(QAccessible::Label, 1);
-}
-*/
-/*
-    Returns a list of interfaces this interface labels, or an empty list if it doesn't label any.
-*/
-/*
-static QList<QAInterface> findLabelled(const QAInterface &interface)
-{
-    QList<QAInterface> interfaceList;
-
-    int count = 1;
-    const QAInterface labelled = interface.navigate(QAccessible::Labelled, count);
-    while (labelled.isValid()) {
-        interfaceList.append(labelled);
-        ++count;
-    }
-    return interfaceList;
-}
-*/
-/*
-    Tests if the given QAInterface has data for a mac attribute.
-*/
-#ifndef QT_MAC_USE_COCOA
-static bool supportsAttribute(CFStringRef attribute, const QAInterface &interface)
-{
-    const int text = textForRoleAndAttribute(interface.role(), attribute);
-
-    // Special case: Static texts don't have a title.
-    if (interface.role() == QAccessible::StaticText && attribute == CFStringRef(QAXTitleAttribute))
-        return false;
-
-    // Return true if we the attribute matched a QAccessible::Role and we get text for that role from the interface.
-    if (text != -1) {
-        if (text == QAccessible::Value) // Special case for Value, see getValue()
-            return !getValue(interface).isEmpty();
-        else
-            return !interface.text((QAccessible::Text)text).isEmpty();
-    }
-
-    if (CFStringCompare(attribute, CFStringRef(QAXChildrenAttribute),  0) == kCFCompareEqualTo) {
-        if (interface.childCount() > 0)
-            return true;
-    }
-
-    if (CFStringCompare(attribute, CFStringRef(QAXSubroleAttribute),  0) == kCFCompareEqualTo) {
-        return (subrole(interface) != QCFString());
-    }
-
-    return false;
-}
-
-static void appendIfSupported(CFMutableArrayRef array, CFStringRef attribute, const QAInterface &interface)
-{
-    if (supportsAttribute(attribute, interface))
-        qt_mac_append_cf_uniq(array, attribute);
-}
-
-/*
-    Returns the names of the attributes the give QAInterface supports.
-*/
-static OSStatus getAllAttributeNames(EventRef event, const QAInterface &interface, EventHandlerCallRef next_ref)
-{
-    // Call system event handler.
-    OSStatus err = CallNextEventHandler(next_ref, event);
-    if(err != noErr && err != eventNotHandledErr)
-        return err;
-    CFMutableArrayRef attrs = 0;
-    GetEventParameter(event, kEventParamAccessibleAttributeNames, typeCFMutableArrayRef, 0,
-                      sizeof(attrs), 0, &attrs);
-
-    if (!attrs)
-        return eventNotHandledErr;
-
-    // Append attribute names that are always supported.
-    qt_mac_append_cf_uniq(attrs, CFStringRef(QAXPositionAttribute));
-    qt_mac_append_cf_uniq(attrs, CFStringRef(QAXSizeAttribute));
-    qt_mac_append_cf_uniq(attrs, CFStringRef(QAXRoleAttribute));
-    qt_mac_append_cf_uniq(attrs, CFStringRef(QAXEnabledAttribute));
-    qt_mac_append_cf_uniq(attrs, CFStringRef(QAXWindowAttribute));
-    qt_mac_append_cf_uniq(attrs, CFStringRef(QAXTopLevelUIElementAttribute));
-
-    // Append these names if the QInterafceItem returns any data for them.
-    appendIfSupported(attrs, CFStringRef(QAXTitleAttribute), interface);
-    appendIfSupported(attrs, CFStringRef(QAXValueAttribute), interface);
-    appendIfSupported(attrs, CFStringRef(QAXDescriptionAttribute), interface);
-    appendIfSupported(attrs, CFStringRef(QAXLinkedUIElementsAttribute), interface);
-    appendIfSupported(attrs, CFStringRef(QAXHelpAttribute), interface);
-    appendIfSupported(attrs, CFStringRef(QAXTitleUIElementAttribute), interface);
-    appendIfSupported(attrs, CFStringRef(QAXChildrenAttribute), interface);
-    appendIfSupported(attrs, CFStringRef(QAXSubroleAttribute), interface);
-
-    // Append attribute names based on the interaface role.
-    switch (interface.role())  {
-        case QAccessible::Window:
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMainAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMinimizedAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXCloseButtonAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXZoomButtonAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMinimizeButtonAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXToolbarButtonAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXGrowAreaAttribute));
-        break;
-        case QAccessible::RadioButton:
-        case QAccessible::CheckBox:
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMinValueAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXMaxValueAttribute));
-        break;
-        case QAccessible::ScrollBar:
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXOrientationAttribute));
-        break;
-        case QAccessible::Splitter:
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXSplittersAttribute));
-        break;
-        case QAccessible::Table:
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXRowsAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXVisibleRowsAttribute));
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXSelectedRowsAttribute));
-        break;
-        default:
-        break;
-    }
-
-    // Append attribute names based on the mac accessibility role.
-    const QCFString mac_role = macRole(interface);
-    if (mac_role == CFStringRef(QAXSplitterRole)) {
-        qt_mac_append_cf_uniq(attrs, CFStringRef(QAXPreviousContentsAttribute));
-        qt_mac_append_cf_uniq(attrs, CFStringRef(QAXNextContentsAttribute));
-        qt_mac_append_cf_uniq(attrs, CFStringRef(QAXOrientationAttribute));
-    } else if (mac_role == CFStringRef(QAXScrollAreaRole)) {
-        if (scrollAreaHasScrollBar(interface, Qt::Horizontal))
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXHorizontalScrollBarAttribute));
-        if (scrollAreaHasScrollBar(interface, Qt::Vertical))
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXVerticalScrollBarAttribute));
-        qt_mac_append_cf_uniq(attrs, CFStringRef(QAXContentsAttribute));
-    } else if (mac_role == CFStringRef(QAXTabGroupRole)) {
-        qt_mac_append_cf_uniq(attrs, CFStringRef(QAXTabsAttribute));
-        // Only tab widgets can have the contents attribute, there is no way of getting
-        // the contents from a QTabBar.
-        if (isTabWidget(interface)) 
-            qt_mac_append_cf_uniq(attrs, CFStringRef(QAXContentsAttribute));
-    }
-
-    return noErr;
-}
-
-static void handleStringAttribute(EventRef event, QAccessible::Text text, const QAInterface &interface)
-{
-    QString str = interface.text(text);
-    if (str.isEmpty())
-        return;
-
-    // Remove any html markup from the text string, or VoiceOver will read the html tags.
-    static QTextDocument document;
-    document.setHtml(str);
-    str = document.toPlainText();
-
-    CFStringRef cfstr = QCFString::toCFStringRef(str);
-    SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFStringRef, sizeof(cfstr), &cfstr);
-}
-
-/*
-    Handles the parent attribute for a interface.
-    There are basically three cases here:
-    1. interface is a HIView and has only HIView children.
-    2. interface is a HIView but has children that is not a HIView
-    3. interface is not a HIView.
-*/
-static OSStatus handleChildrenAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
-   // Add the children for this interface to the global QAccessibelHierachyManager.
-    accessibleHierarchyManager()->registerChildren(interface);
-
-    if (isTabWidget(interface)) {
-        QList<QAElement> children = tabWidgetGetChildren(interface);
-        const int childCount = children.count();
-
-        CFMutableArrayRef array = 0;
-        array = CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks);
-        for (int i = 0; i < childCount; ++i)  {
-            qt_mac_append_cf_uniq(array, children.at(i).element());
-        }
-
-        OSStatus err;
-        err = SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFArrayRef, sizeof(array), &array);
-        if (err != noErr)
-            qWarning("Qt:Internal error (%s:%d)", __FILE__, __LINE__);
-
-        return noErr;
-    }
-
-    const QList<QAElement> children = lookup(interface.children());
-    const int childCount = children.count();
-
-    OSStatus err = eventNotHandledErr;
-    if (interface.isHIView())
-        err = CallNextEventHandler(next_ref, event);
-
-    CFMutableArrayRef array = 0;
-    int arraySize = 0;
-    if (err == noErr) {
-        CFTypeRef obj = 0;
-        err = GetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, NULL , sizeof(obj), NULL, &obj);
-        if (err == noErr && obj != 0) {
-            array = (CFMutableArrayRef)obj;
-            arraySize = CFArrayGetCount(array);
-        }
-    }
-
-    if (array) {
-        CFArrayRemoveAllValues(array);
-        for (int i = 0; i < childCount; ++i)  {
-            qt_mac_append_cf_uniq(array, children.at(i).element());
-        }
-    } else {
-        array = CFArrayCreateMutable(0, 0, &kCFTypeArrayCallBacks);
-        for (int i = 0; i < childCount; ++i)  {
-            qt_mac_append_cf_uniq(array, children.at(i).element());
-        }
-
-        err = SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFArrayRef, sizeof(array), &array);
-        if (err != noErr)
-            qWarning("Qt:Internal error (%s:%d)", __FILE__, __LINE__);
-    }
-
-    return noErr;
-}
-
-/*
-
-*/
-static OSStatus handleParentAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
-    OSStatus err = eventNotHandledErr;
-    if (interface.isHIView()) {
-         err = CallNextEventHandler(next_ref, event);
-    }
-    if (err == noErr)
-        return err;
-
-    const QAInterface parentInterface  = interface.navigate(QAccessible::Ancestor, 1);
-    const QAElement parentElement = accessibleHierarchyManager()->lookup(parentInterface);
-
-    if (parentElement.isValid() == false)
-        return eventNotHandledErr;
-
-    AXUIElementRef elementRef = parentElement.element();
-    SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, sizeof(elementRef), &elementRef);
-    return noErr;
-}
-#endif
-
-struct IsWindowTest
-{
-    static inline bool test(const QAInterface &interface)
-    {
-        return (interface.role() == QAccessible::Window);
-    }
-};
-
-struct IsWindowAndNotDrawerOrSheetTest
-{
-    static inline bool test(const QAInterface &interface)
-    {
-        QWidget * const widget = qobject_cast<QWidget*>(interface.object());
-        return (interface.role() == QAccessible::Window &&
-                widget && widget->isWindow() &&
-                !qt_mac_is_macdrawer(widget) &&
-                !qt_mac_is_macsheet(widget));
-    }
-};
-
-/*
-    Navigates up the iterfaces ancestor hierachy until a QAccessibleInterface that
-    passes the Test is found. If we reach a interface that is a HIView we stop the
-    search and call AXUIElementCopyAttributeValue.
-*/
-template <typename TestType>
-OSStatus navigateAncestors(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface, CFStringRef attribute)
-{
-    if (interface.isHIView())
-        return CallNextEventHandler(next_ref, event);
-
-    QAInterface current = interface;
-    QAElement element;
-    while (current.isValid()) {
-        if (TestType::test(interface)) {
-            element = accessibleHierarchyManager()->lookup(current);
-            break;
-        }
-
-        // If we reach an InterfaceItem that is a HiView we can hand of the search to
-        // the system event handler. This is the common case.
-        if (current.isHIView()) {
-            CFTypeRef value = 0;
-            const QAElement currentElement = accessibleHierarchyManager()->lookup(current);
-            AXError err = AXUIElementCopyAttributeValue(currentElement.element(), attribute, &value);
-            AXUIElementRef newElement = (AXUIElementRef)value;
-
-            if (err == noErr)
-                element = QAElement(newElement);
-
-            if (newElement != 0)
-                CFRelease(newElement);
-            break;
-        }
-
-        QAInterface next = current.parent();
-        if (next.isValid() == false)
-            break;
-        if (next == current)
-            break;
-        current = next;
-    }
-
-    if (element.isValid() == false)
-        return eventNotHandledErr;
-
-
-    AXUIElementRef elementRef = element.element();
-    SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef,
-                                      sizeof(elementRef), &elementRef);
-    return noErr;
-}
-
-/*
-    Returns the top-level window for an interface, which is the closest ancestor interface that
-    has the Window role, but is not a sheet or a drawer.
-*/
-#ifndef QT_MAC_USE_COCOA
-static OSStatus handleWindowAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
-    return navigateAncestors<IsWindowAndNotDrawerOrSheetTest>(next_ref, event, interface, CFStringRef(QAXWindowAttribute));
-}
-
-/*
-    Returns the top-level window for an interface, which is the closest ancestor interface that
-    has the Window role. (Can also be a sheet or a drawer)
-*/
-static OSStatus handleTopLevelUIElementAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
-    return navigateAncestors<IsWindowTest>(next_ref, event, interface, CFStringRef(QAXTopLevelUIElementAttribute));
-}
-
-/*
-    Returns the tab buttons for an interface.
-*/
-static OSStatus handleTabsAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
-    Q_UNUSED(next_ref);
-    if (isTabWidget(interface))
-        return setAttributeValue(event, tabWidgetGetTabs(interface));
-    else
-        return setAttributeValue(event, tabBarGetTabs(interface));
-}
-
-static OSStatus handlePositionAttribute(EventHandlerCallRef, EventRef event, const QAInterface &interface)
-{
-    QPoint qpoint(interface.rect().topLeft());
-    HIPoint point;
-    point.x = qpoint.x();
-    point.y = qpoint.y();
-    SetEventParameter(event, kEventParamAccessibleAttributeValue, typeHIPoint, sizeof(point), &point);
-    return noErr;
-}
-
-static OSStatus handleSizeAttribute(EventHandlerCallRef, EventRef event, const QAInterface &interface)
-{
-    QSize qSize(interface.rect().size());
-    HISize size;
-    size.width = qSize.width();
-    size.height = qSize.height();
-    SetEventParameter(event, kEventParamAccessibleAttributeValue, typeHISize, sizeof(size), &size);
-    return noErr;
-}
-
-static OSStatus handleSubroleAttribute(EventHandlerCallRef, EventRef event, const QAInterface &interface)
-{
-    const QCFString role = subrole(interface);
-    CFStringRef rolestr = (CFStringRef)role;
-    SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, sizeof(rolestr), &rolestr);
-    return noErr;
-}
-
-static OSStatus handleOrientationAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
-    QObject *const object = interface.object();
-    Qt::Orientation orientation;
-    if (interface.role() == QAccessible::ScrollBar) {
-        orientation  = scrollBarOrientation(interface);
-    } else if (QSplitterHandle * const splitter = qobject_cast<QSplitterHandle * const>(object)) {
-        // Qt reports the layout orientation, but we want the splitter handle orientation.
-        orientation = (splitter->orientation() == Qt::Horizontal) ? Qt::Vertical : Qt::Horizontal;
-    } else {
-        return CallNextEventHandler(next_ref, event);
-    }
-    const CFStringRef orientationString = (orientation == Qt::Vertical)
-        ? CFStringRef(QAXVerticalOrientationValue) : CFStringRef(QAXHorizontalOrientationValue);
-    SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFStringRef, sizeof(orientationString), &orientationString);
-    return noErr;
-}
-
-/*
-    Figures out the next or previous contents for a splitter.
-*/
-static OSStatus handleSplitterContentsAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface, QCFString nextOrPrev)
-{
-    if (interface.isValid() == false || interface.role() != QAccessible::Grip)
-        return eventNotHandledErr;
-
-    const QAInterface parent = interface.parent();
-    if (parent.isValid() == false)
-        return CallNextEventHandler(next_ref, event);
-
-    if (parent.role() != QAccessible::Splitter)
-        return CallNextEventHandler(next_ref, event);
-
-    const QSplitter * const splitter = qobject_cast<const QSplitter * const>(parent.object());
-    if (splitter == 0)
-        return CallNextEventHandler(next_ref, event);
-
-    QWidget * const splitterHandle = qobject_cast<QWidget * const>(interface.object());
-    const int splitterHandleIndex = splitter->indexOf(splitterHandle);
-    const int widgetIndex = (nextOrPrev == QCFString(CFStringRef(QAXPreviousContentsAttribute))) ? splitterHandleIndex - 1 : splitterHandleIndex;
-    const QAElement contentsElement = accessibleHierarchyManager()->lookup(splitter->widget(widgetIndex), 0);
-    return setAttributeValue(event, QList<QAElement>() << contentsElement);
-}
-
-/*
-    Creates a list of all splitter handles the splitter contains.
-*/
-static OSStatus handleSplittersAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
-    const QSplitter * const splitter = qobject_cast<const QSplitter * const>(interface.object());
-    if (splitter == 0)
-        return CallNextEventHandler(next_ref, event);
-
-    accessibleHierarchyManager()->registerChildren(interface);
-
-    QList<QAElement> handles;
-    const int visibleSplitterCount = splitter->count() -1; // skip first handle, it's always invisible.
-    for (int i = 0; i < visibleSplitterCount; ++i)
-        handles.append(accessibleHierarchyManager()->lookup(splitter->handle(i + 1), 0));
-
-    return setAttributeValue(event, handles);
-}
-
-// This handler gets the scroll bars for a scroll area
-static OSStatus handleScrollBarAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &scrollArea, Qt::Orientation orientation)
-{
-    QAElement scrollBar = scrollAreaGetScrollBar(scrollArea, orientation);
-    if (scrollBar.isValid() == false)
-        return CallNextEventHandler(next_ref, event);
-
-    AXUIElementRef elementRef = scrollBar.element();
-    SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, sizeof(elementRef), &elementRef);
-    return noErr;
-}
-
-// This handler gets the contents for a scroll area or tab widget.
-static OSStatus handleContentsAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
-    const QCFString mac_role = macRole(interface);
-
-    QAElement contents;
-
-    if (mac_role == kAXTabGroupRole) {
-        contents = tabWidgetGetContents(interface);
-    } else {
-        contents = scrollAreaGetContents(interface);
-        if (contents.isValid() == false)
-            return CallNextEventHandler(next_ref, event);
-    }
-
-    return setAttributeValue(event, QList<QAElement>() << contents);
-}
-
-static OSStatus handleRowsAttribute(EventHandlerCallRef, EventRef event, QAInterface &tableView)
-{
-    QList<QAElement> rows = lookup(tableView.children());
-
-    // kill the first row which is the horizontal header.
-    rows.removeAt(0);
-
-    return setAttributeValue(event, rows);
-}
-
-static OSStatus handleVisibleRowsAttribute(EventHandlerCallRef, EventRef event, QAInterface &tableView)
-{
-    QList<QAElement> visibleRows;
-
-    QList<QAInterface> rows = tableView.children();
-    // kill the first row which is the horizontal header.
-    rows.removeAt(0);
-
-    foreach (const QAInterface &interface, rows)
-        if ((interface.state() & QAccessible::Invisible) == false)
-            visibleRows.append(accessibleHierarchyManager()->lookup(interface));
-
-    return setAttributeValue(event, visibleRows);
-}
-
-static OSStatus handleSelectedRowsAttribute(EventHandlerCallRef, EventRef event, QAInterface &tableView)
-{
-    QList<QAElement> selectedRows;
-    foreach (const QAInterface &interface, tableView.children())
-        if ((interface.state() & QAccessible::Selected))
-            selectedRows.append(accessibleHierarchyManager()->lookup(interface));
-
-    return setAttributeValue(event, selectedRows);
-}
-
-static OSStatus getNamedAttribute(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
-    CFStringRef var;
-    GetEventParameter(event, kEventParamAccessibleAttributeName, typeCFStringRef, 0,
-                              sizeof(var), 0, &var);
-
-    if (CFStringCompare(var, CFStringRef(QAXChildrenAttribute), 0) == kCFCompareEqualTo) {
-        return handleChildrenAttribute(next_ref, event, interface);
-    } else if(CFStringCompare(var, CFStringRef(QAXTopLevelUIElementAttribute), 0) == kCFCompareEqualTo) {
-        return handleTopLevelUIElementAttribute(next_ref, event, interface);
-    } else if(CFStringCompare(var, CFStringRef(QAXWindowAttribute), 0) == kCFCompareEqualTo) {
-        return handleWindowAttribute(next_ref, event, interface);
-    } else if(CFStringCompare(var, CFStringRef(QAXParentAttribute), 0) == kCFCompareEqualTo) {
-        return handleParentAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXPositionAttribute), 0) == kCFCompareEqualTo) {
-        return handlePositionAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXSizeAttribute), 0) == kCFCompareEqualTo) {
-        return handleSizeAttribute(next_ref, event, interface);
-    } else  if (CFStringCompare(var, CFStringRef(QAXRoleAttribute), 0) == kCFCompareEqualTo) {
-        CFStringRef role = macRole(interface);
-// ###
-//        QWidget * const widget = qobject_cast<QWidget *>(interface.object());
-//        if (role == CFStringRef(QAXUnknownRole) && widget && widget->isWindow())
-//            role = CFStringRef(QAXWindowRole);
-
-        SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFStringRef,
-                          sizeof(role), &role);
-
-    } else if (CFStringCompare(var, CFStringRef(QAXEnabledAttribute), 0) == kCFCompareEqualTo) {
-        Boolean val =  !((interface.state() & QAccessible::Unavailable))
-                     && !((interface.state() & QAccessible::Invisible));
-        SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                          sizeof(val), &val);
-    } else if (CFStringCompare(var, CFStringRef(QAXExpandedAttribute), 0) == kCFCompareEqualTo) {
-        Boolean val = (interface.state() & QAccessible::Expanded);
-        SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                          sizeof(val), &val);
-    } else if (CFStringCompare(var, CFStringRef(QAXSelectedAttribute), 0) == kCFCompareEqualTo) {
-        Boolean val = (interface.state() & QAccessible::Selection);
-        SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                          sizeof(val), &val);
-    } else if (CFStringCompare(var, CFStringRef(QAXFocusedAttribute), 0) == kCFCompareEqualTo) {
-        Boolean val = (interface.state() & QAccessible::Focus);
-        SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                          sizeof(val), &val);
-    } else if (CFStringCompare(var, CFStringRef(QAXSelectedChildrenAttribute), 0) == kCFCompareEqualTo) {
-        const int cc = interface.childCount();
-        QList<QAElement> selected;
-        for (int i = 1; i <= cc; ++i) {
-            const QAInterface child_iface = interface.navigate(QAccessible::Child, i);
-            if (child_iface.isValid() && child_iface.state() & QAccessible::Selected)
-                selected.append(accessibleHierarchyManager()->lookup(child_iface));
-        }
-
-        return setAttributeValue(event, selected);
-
-      } else if (CFStringCompare(var, CFStringRef(QAXCloseButtonAttribute), 0) == kCFCompareEqualTo) {
-        if(interface.object() && interface.object()->isWidgetType()) {
-            Boolean val = true; //do we want to add a WState for this?
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                              sizeof(val), &val);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXZoomButtonAttribute), 0) == kCFCompareEqualTo) {
-        if(interface.object() && interface.object()->isWidgetType()) {
-            QWidget *widget = (QWidget*)interface.object();
-            Boolean val = (widget->windowFlags() & Qt::WindowMaximizeButtonHint);
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                              sizeof(val), &val);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXMinimizeButtonAttribute), 0) == kCFCompareEqualTo) {
-        if(interface.object() && interface.object()->isWidgetType()) {
-            QWidget *widget = (QWidget*)interface.object();
-            Boolean val = (widget->windowFlags() & Qt::WindowMinimizeButtonHint);
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                              sizeof(val), &val);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXToolbarButtonAttribute), 0) == kCFCompareEqualTo) {
-        if(interface.object() && interface.object()->isWidgetType()) {
-            QWidget *widget = (QWidget*)interface.object();
-            Boolean val = qobject_cast<QMainWindow *>(widget) != 0;
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                              sizeof(val), &val);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXGrowAreaAttribute), 0) == kCFCompareEqualTo) {
-        if(interface.object() && interface.object()->isWidgetType()) {
-            Boolean val = true; //do we want to add a WState for this?
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                              sizeof(val), &val);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXMinimizedAttribute), 0) == kCFCompareEqualTo) {
-        if (interface.object() && interface.object()->isWidgetType()) {
-            QWidget *widget = (QWidget*)interface.object();
-            Boolean val = (widget->windowState() & Qt::WindowMinimized);
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeBoolean,
-                              sizeof(val), &val);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXSubroleAttribute), 0) == kCFCompareEqualTo) {
-        return handleSubroleAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXRoleDescriptionAttribute), 0) == kCFCompareEqualTo) {
-#if !defined(QT_MAC_USE_COCOA)
-        if (HICopyAccessibilityRoleDescription) {
-            const CFStringRef roleDescription = HICopyAccessibilityRoleDescription(macRole(interface), 0);
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFStringRef,
-                          sizeof(roleDescription), &roleDescription);
-        } else
-#endif
-        {
-            // Just use Qt::Description on 10.3
-            handleStringAttribute(event, QAccessible::Description, interface);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXTitleAttribute), 0) == kCFCompareEqualTo) {
-        const QAccessible::Role role = interface.role();
-        const QAccessible::Text text = (QAccessible::Text)textForRoleAndAttribute(role, var);
-        handleStringAttribute(event, text, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXValueAttribute), 0) == kCFCompareEqualTo) {
-        const QAccessible::Role role = interface.role();
-        const QAccessible::Text text = (QAccessible::Text)textForRoleAndAttribute(role, var);
-        if (role == QAccessible::CheckBox || role == QAccessible::RadioButton) {
-            int value = buttonValue(interface);
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeUInt32, sizeof(value), &value);
-        } else {
-            handleStringAttribute(event, text, interface);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXDescriptionAttribute), 0) == kCFCompareEqualTo) {
-        const QAccessible::Role role = interface.role();
-        const QAccessible::Text text = (QAccessible::Text)textForRoleAndAttribute(role, var);
-        handleStringAttribute(event, text, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXLinkedUIElementsAttribute), 0) == kCFCompareEqualTo) {
-        return CallNextEventHandler(next_ref, event);
-    } else if (CFStringCompare(var, CFStringRef(QAXHelpAttribute), 0) == kCFCompareEqualTo) {
-        const QAccessible::Role role = interface.role();
-        const QAccessible::Text text = (QAccessible::Text)textForRoleAndAttribute(role, var);
-        handleStringAttribute(event, text, interface);
-    } else if (CFStringCompare(var, kAXTitleUIElementAttribute, 0) == kCFCompareEqualTo) {
-        return CallNextEventHandler(next_ref, event);
-    } else if (CFStringCompare(var, CFStringRef(QAXTabsAttribute), 0) == kCFCompareEqualTo) {
-        return handleTabsAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXMinValueAttribute), 0) == kCFCompareEqualTo) {
-        // tabs we first go to the tab bar which is child #2.
-        QAInterface tabBarInterface = interface.childAt(2);
-        return handleTabsAttribute(next_ref, event, tabBarInterface);
-    } else if (CFStringCompare(var, CFStringRef(QAXMinValueAttribute), 0) == kCFCompareEqualTo) {
-        if (interface.role() == QAccessible::RadioButton || interface.role() == QAccessible::CheckBox) {
-            uint value = 0;
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeUInt32, sizeof(value), &value);
-        } else {
-            return CallNextEventHandler(next_ref, event);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXMaxValueAttribute), 0) == kCFCompareEqualTo) {
-        if (interface.role() == QAccessible::RadioButton || interface.role() == QAccessible::CheckBox) {
-            uint value = 2;
-            SetEventParameter(event, kEventParamAccessibleAttributeValue, typeUInt32, sizeof(value), &value);
-        } else {
-            return CallNextEventHandler(next_ref, event);
-        }
-    } else if (CFStringCompare(var, CFStringRef(QAXOrientationAttribute), 0) == kCFCompareEqualTo) {
-        return handleOrientationAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXPreviousContentsAttribute), 0) == kCFCompareEqualTo) {
-        return handleSplitterContentsAttribute(next_ref, event, interface, CFStringRef(QAXPreviousContentsAttribute));
-    } else if (CFStringCompare(var, CFStringRef(QAXNextContentsAttribute), 0) == kCFCompareEqualTo) {
-        return handleSplitterContentsAttribute(next_ref, event, interface, CFStringRef(QAXNextContentsAttribute));
-    } else if (CFStringCompare(var, CFStringRef(QAXSplittersAttribute), 0) == kCFCompareEqualTo) {
-        return handleSplittersAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXHorizontalScrollBarAttribute), 0) == kCFCompareEqualTo) {
-        return handleScrollBarAttribute(next_ref, event, interface, Qt::Horizontal);
-    } else if (CFStringCompare(var, CFStringRef(QAXVerticalScrollBarAttribute), 0) == kCFCompareEqualTo) {
-        return handleScrollBarAttribute(next_ref, event, interface, Qt::Vertical);
-    } else if (CFStringCompare(var, CFStringRef(QAXContentsAttribute), 0) == kCFCompareEqualTo) {
-        return handleContentsAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXRowsAttribute), 0) == kCFCompareEqualTo) {
-        return handleRowsAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXVisibleRowsAttribute), 0) == kCFCompareEqualTo) {
-        return handleVisibleRowsAttribute(next_ref, event, interface);
-    } else if (CFStringCompare(var, CFStringRef(QAXSelectedRowsAttribute), 0) == kCFCompareEqualTo) {
-        return handleSelectedRowsAttribute(next_ref, event, interface);
-    } else {
-        return CallNextEventHandler(next_ref, event);
-    }
-    return noErr;
-}
-
-static OSStatus isNamedAttributeSettable(EventRef event, const QAInterface &interface)
-{
-    CFStringRef var;
-    GetEventParameter(event, kEventParamAccessibleAttributeName, typeCFStringRef, 0,
-                      sizeof(var), 0, &var);
-    Boolean settable = false;
-    if (CFStringCompare(var, CFStringRef(QAXFocusedAttribute), 0) == kCFCompareEqualTo) {
-        settable = true;
-    } else {
-        for (int r = 0; text_bindings[r][0].qt != -1; r++) {
-            if(interface.role() == (QAccessible::Role)text_bindings[r][0].qt) {
-                for (int a = 1; text_bindings[r][a].qt != -1; a++) {
-                    if (CFStringCompare(var, CFStringRef(text_bindings[r][a].mac), 0) == kCFCompareEqualTo) {
-                        settable = text_bindings[r][a].settable;
-                        break;
-                    }
-                }
-            }
-        }
-    }
-    SetEventParameter(event, kEventParamAccessibleAttributeSettable, typeBoolean,
-                      sizeof(settable), &settable);
-    return noErr;
-}
-
-static OSStatus getChildAtPoint(EventHandlerCallRef next_ref, EventRef event, QAInterface &interface)
-{
-    Q_UNUSED(next_ref);
-    if (interface.isValid() == false)
-        return eventNotHandledErr;
-
-    // Add the children for this interface to the global QAccessibelHierachyManager.
-    accessibleHierarchyManager()->registerChildren(interface);
-
-    Point where;
-    GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, 0, sizeof(where), 0, &where);
-    const QAInterface childInterface = interface.childAt(where.h, where.v);
-
-    if (childInterface.isValid() == false || childInterface == interface)
-        return eventNotHandledErr;
-
-    const QAElement element = accessibleHierarchyManager()->lookup(childInterface);
-    if (element.isValid() == false)
-        return eventNotHandledErr;
-
-    AXUIElementRef elementRef = element.element();
-    CFRetain(elementRef);
-    SetEventParameter(event, kEventParamAccessibleChild, typeCFTypeRef,
-                                  sizeof(elementRef), &elementRef);
-
-    return noErr;
-}
-
-/*
-    Returns a list of actions the given interface supports.
-    Currently implemented by getting the interface role and deciding based on that.
-*/
-static QList<QAccessible::Action> supportedPredefinedActions(const QAInterface &interface)
-{
-    QList<QAccessible::Action> actions;
-    switch (interface.role()) {
-        default:
-            // Most things can be pressed.
-            actions.append(QAccessible::Press);
-        break;
-    }
-
-    return actions;
-}
-
-/*
-    Translates a predefined QAccessible::Action to a Mac action constant.
-    Returns an empty string if the Qt Action has no mac equivalent.
-*/
-static QCFString translateAction(const QAccessible::Action action)
-{
-    switch (action) {
-        case QAccessible::Press:
-            return CFStringRef(QAXPressAction);
-        break;
-        case QAccessible::Increase:
-            return CFStringRef(QAXIncrementAction);
-        break;
-        case QAccessible::Decrease:
-            return CFStringRef(QAXDecrementAction);
-        break;
-        case QAccessible::Accept:
-            return CFStringRef(QAXConfirmAction);
-        break;
-        case QAccessible::Select:
-            return CFStringRef(QAXPickAction);
-        break;
-        case QAccessible::Cancel:
-            return CFStringRef(QAXCancelAction);
-        break;
-        default:
-            return QCFString();
-        break;
-    }
-}
-
-/*
-    Translates between a Mac action constant and a QAccessible::Action.
-    Returns QAccessible::Default action if there is no Qt predefined equivalent.
-*/
-static QAccessible::Action translateAction(const CFStringRef actionName)
-{
-    if(CFStringCompare(actionName, CFStringRef(QAXPressAction), 0) == kCFCompareEqualTo) {
-        return QAccessible::Press;
-    } else if(CFStringCompare(actionName, CFStringRef(QAXIncrementAction), 0) == kCFCompareEqualTo) {
-        return QAccessible::Increase;
-    } else if(CFStringCompare(actionName, CFStringRef(QAXDecrementAction), 0) == kCFCompareEqualTo) {
-        return QAccessible::Decrease;
-    } else if(CFStringCompare(actionName, CFStringRef(QAXConfirmAction), 0) == kCFCompareEqualTo) {
-        return QAccessible::Accept;
-    } else if(CFStringCompare(actionName, CFStringRef(QAXPickAction), 0) == kCFCompareEqualTo) {
-        return QAccessible::Select;
-    } else if(CFStringCompare(actionName, CFStringRef(QAXCancelAction), 0) == kCFCompareEqualTo) {
-        return QAccessible::Cancel;
-    } else {
-        return QAccessible::DefaultAction;
-    }
-}
-#endif // QT_MAC_USE_COCOA
-
-/*
-    Copies the translated names all supported actions for an interface into the kEventParamAccessibleActionNames
-    event parameter.
-*/
-#ifndef QT_MAC_USE_COCOA
-static OSStatus getAllActionNames(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
-    Q_UNUSED(next_ref);
-
-    CFMutableArrayRef actions = 0;
-    GetEventParameter(event, kEventParamAccessibleActionNames, typeCFMutableArrayRef, 0,
-                      sizeof(actions), 0, &actions);
-
-    // Add supported predefined actions.
-    const QList<QAccessible::Action> predefinedActions = supportedPredefinedActions(interface);
-    for (int i = 0; i < predefinedActions.count(); ++i) {
-        const QCFString action = translateAction(predefinedActions.at(i));
-        if (action != QCFString())
-            qt_mac_append_cf_uniq(actions, action);
-    }
-
-    // Add user actions
-    const int actionCount = interface.userActionCount();
-    for (int i = 0; i < actionCount; ++i) {
-        const QString actionName = interface.actionText(i, QAccessible::Name);
-        qt_mac_append_cf_uniq(actions, QCFString::toCFStringRef(actionName));
-    }
-
-    return noErr;
-}
-#endif
-
-/*
-    Handles the perforNamedAction event.
-*/
-#ifndef QT_MAC_USE_COCOA
-static OSStatus performNamedAction(EventHandlerCallRef next_ref, EventRef event, const QAInterface& interface)
-{
-    Q_UNUSED(next_ref);
-
-    CFStringRef act;
-    GetEventParameter(event, kEventParamAccessibleActionName, typeCFStringRef, 0,
-                      sizeof(act), 0, &act);
-
-    const QAccessible::Action action = translateAction(act);
-
-    // Perform built-in action
-    if (action != QAccessible::DefaultAction) {
-        interface.doAction(action, QVariantList());
-        return noErr;
-    }
-
-    // Search for user-defined actions and perform it if found.
-    const int actCount = interface.userActionCount();
-    const QString qAct = QCFString::toQString(act);
-    for(int i = 0; i < actCount; i++) {
-        if(interface.actionText(i, QAccessible::Name) == qAct) {
-            interface.doAction(i, QVariantList());
-            break;
-        }
-    }
-    return noErr;
-}
-
-static OSStatus setNamedAttribute(EventHandlerCallRef next_ref, EventRef event, const QAInterface &interface)
-{
-    Q_UNUSED(next_ref);
-    Q_UNUSED(event);
-
-    CFStringRef var;
-    GetEventParameter(event, kEventParamAccessibleAttributeName, typeCFStringRef, 0,
-                      sizeof(var), 0, &var);
-    if(CFStringCompare(var, CFStringRef(QAXFocusedAttribute), 0) == kCFCompareEqualTo) {
-        CFTypeRef val;
-        if(GetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, 0,
-                             sizeof(val), 0, &val) == noErr) {
-            if(CFGetTypeID(val) == CFBooleanGetTypeID() &&
-               CFEqual(static_cast<CFBooleanRef>(val), kCFBooleanTrue)) {
-                interface.doAction(QAccessible::SetFocus);
-            }
-        }
-    } else {
-        bool found = false;
-        for(int r = 0; text_bindings[r][0].qt != -1; r++) {
-            if(interface.role() == (QAccessible::Role)text_bindings[r][0].qt) {
-                for(int a = 1; text_bindings[r][a].qt != -1; a++) {
-                    if(CFStringCompare(var, CFStringRef(text_bindings[r][a].mac), 0) == kCFCompareEqualTo) {
-                        if(!text_bindings[r][a].settable) {
-                        } else {
-                            CFTypeRef val;
-                            if(GetEventParameter(event, kEventParamAccessibleAttributeValue, typeCFTypeRef, 0,
-                                                 sizeof(val), 0, &val) == noErr) {
-                                if(CFGetTypeID(val) == CFStringGetTypeID())
-                                    interface.setText((QAccessible::Text)text_bindings[r][a].qt,
-                                                   QCFString::toQString(static_cast<CFStringRef>(val)));
-
-                            }
-                        }
-                        found = true;
-                        break;
-                    }
-                }
-                break;
-            }
-        }
-    }
-    return noErr;
-}
-
-/*
-    This is the main accessibility event handler.
-*/
-static OSStatus accessibilityEventHandler(EventHandlerCallRef next_ref, EventRef event, void *data)
-{
-    Q_UNUSED(data)
-
-    // Return if this event is not a AccessibleGetNamedAttribute event.
-    const UInt32 eclass = GetEventClass(event);
-    if (eclass != kEventClassAccessibility)
-        return eventNotHandledErr;
-
-    // Get the AXUIElementRef and QAInterface pointer
-    AXUIElementRef element = 0;
-    GetEventParameter(event, kEventParamAccessibleObject, typeCFTypeRef, 0, sizeof(element), 0, &element);
-    QAInterface interface = accessibleHierarchyManager()->lookup(element);
-    if (interface.isValid() == false)
-        return eventNotHandledErr;
-
-    const UInt32 ekind = GetEventKind(event);
-    OSStatus status = noErr;
-    switch (ekind) {
-        case kEventAccessibleGetAllAttributeNames:
-             status = getAllAttributeNames(event, interface, next_ref);
-        break;
-        case kEventAccessibleGetNamedAttribute:
-             status = getNamedAttribute(next_ref, event, interface);
-        break;
-        case kEventAccessibleIsNamedAttributeSettable:
-             status = isNamedAttributeSettable(event, interface);
-        break;
-        case kEventAccessibleGetChildAtPoint:
-            status = getChildAtPoint(next_ref, event, interface);
-        break;
-        case kEventAccessibleGetAllActionNames:
-            status = getAllActionNames(next_ref, event, interface);
-        break;
-        case kEventAccessibleGetFocusedChild:
-            status = CallNextEventHandler(next_ref, event);
-        break;
-        case kEventAccessibleSetNamedAttribute:
-            status = setNamedAttribute(next_ref, event, interface);
-        break;
-        case kEventAccessiblePerformNamedAction:
-            status = performNamedAction(next_ref, event, interface);
-        break;
-        default:
-            status = CallNextEventHandler(next_ref, event);
-        break;
-    };
-    return status;
-}
-#endif
-
-void QAccessible::initialize()
-{
-#ifndef QT_MAC_USE_COCOA
-    registerQtAccessibilityHIObjectSubclass();
-    installApplicationEventhandler();
-#endif
-}
-
-// Sets thre root object for the application
-void QAccessible::setRootObject(QObject *object)
-{
-    // Call installed root object handler if we have one
-    if (rootObjectHandler) {
-        rootObjectHandler(object);
-        return;
-    }
-
-    rootObject = object;
-}
-
-void QAccessible::cleanup()
-{
-    accessibleHierarchyManager()->reset();
-#ifndef QT_MAC_USE_COCOA
-    removeEventhandler(applicationEventHandlerUPP);
-    removeEventhandler(objectCreateEventHandlerUPP);
-    removeEventhandler(accessibilityEventHandlerUPP);
-#endif
-}
-
-void QAccessible::updateAccessibility(QObject *object, int child, Event reason)
-{
-    // Call installed update handler if we have one.
-    if (updateHandler) {
-        updateHandler(object, child, reason);
-        return;
-    }
-
-#ifndef QT_MAC_USE_COCOA
-    // Return if the mac accessibility is not enabled.
-    if(!AXAPIEnabled())
-        return;
-
-     // Work around crash, disable accessiblity for focus frames.
-     if (qstrcmp(object->metaObject()->className(), "QFocusFrame") == 0)
-        return;
-
-//    qDebug() << "updateAccessibility" << object << child << hex << reason;
-
-    if (reason == ObjectShow) {
-        QAInterface interface = QAInterface(QAccessible::queryAccessibleInterface(object), child);
-        accessibleHierarchyManager()->registerInterface(interface);
-    }
-
-    const QAElement element = accessibleHierarchyManager()->lookup(object, child);
-    if (element.isValid() == false)
-        return;
-
-
-    CFStringRef notification = 0;
-    if(object && object->isWidgetType() && reason == ObjectCreated) {
-        notification = CFStringRef(QAXWindowCreatedNotification);
-    } else if(reason == ValueChanged) {
-        notification = CFStringRef(QAXValueChangedNotification);
-    } else if(reason == MenuStart) {
-        notification = CFStringRef(QAXMenuOpenedNotification);
-    } else if(reason == MenuEnd) {
-        notification = CFStringRef(QAXMenuClosedNotification);
-    } else if(reason == LocationChanged) {
-        notification = CFStringRef(QAXWindowMovedNotification);
-    } else if(reason == ObjectShow || reason == ObjectHide ) {
-        // When a widget is deleted we get a ObjectHide before the destroyed(QObject *)
-        // signal is emitted (which makes sense). However, at this point we are in the
-        // middle of the QWidget destructor which means that we have to be careful when
-        // using the widget pointer. Since we can't control what the accessibilty interfaces
-        // does when navigate() is called below we ignore the hide update in this case.
-        // (the widget will be deleted soon anyway.)
-        extern QWidgetPrivate * qt_widget_private(QWidget *);
-        if (QWidget *widget = qobject_cast<QWidget*>(object)) {
-            if (qt_widget_private(widget)->data.in_destructor)
-                return;
-
-            // Check widget parent as well, special case for preventing crash
-            // when the viewport() of an abstract scroll area is hidden when
-            // the QWidget destructor hides all its children.
-            QWidget *parentWidget = widget->parentWidget();
-            if (parentWidget && qt_widget_private(parentWidget)->data.in_destructor)
-                return;
-        }
-
-        // There is no equivalent Mac notification for ObjectShow/Hide, so we call HIObjectSetAccessibilityIgnored
-        // and isItInteresting which will mark the HIObject accociated with the element as ignored if the
-        // QAccessible::Invisible state bit is set.
-        QAInterface interface = accessibleHierarchyManager()->lookup(element);
-        if (interface.isValid()) {
-            HIObjectSetAccessibilityIgnored(element.object(), !isItInteresting(interface));
-        }
-
-        // If the interface manages its own children, also check if we should ignore those.
-        if (isItemView(interface) == false && managesChildren(interface)) {
-            for (int i = 1; i <= interface.childCount(); ++i) {
-                QAInterface childInterface = interface.navigate(QAccessible::Child, i);
-                if (childInterface.isValid() && childInterface.isHIView() == false) {
-                    const QAElement element = accessibleHierarchyManager()->lookup(childInterface);
-                    if (element.isValid()) {
-                        HIObjectSetAccessibilityIgnored(element.object(), !isItInteresting(childInterface));
-                    }
-                }
-            }
-        }
-
-    } else if(reason == Focus) {
-        if(object && object->isWidgetType()) {
-            QWidget *w = static_cast<QWidget*>(object);
-            if(w->isWindow())
-                notification = CFStringRef(QAXFocusedWindowChangedNotification);
-            else
-                notification = CFStringRef(QAXFocusedUIElementChangedNotification);
-        }
-    }
-
-    if (!notification)
-        return;
-
-    AXNotificationHIObjectNotify(notification, element.object(), element.id());
-#endif
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qaccessible_mac_p.h"
-
-#endif // QT_NO_ACCESSIBILITY
diff --git a/src/gui/accessible/qaccessible_mac_carbon.cpp b/src/gui/accessible/qaccessible_mac_carbon.cpp
deleted file mode 100644 (file)
index 594cfbf..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-static OSStatus applicationEventHandler(EventHandlerCallRef next_ref, EventRef event, void *data);
-static EventHandlerUPP applicationEventHandlerUPP = 0;
-static EventTypeSpec application_events[] = {
-    { kEventClassAccessibility,  kEventAccessibleGetChildAtPoint },
-    { kEventClassAccessibility,  kEventAccessibleGetNamedAttribute }
-};
-
-static CFStringRef kObjectQtAccessibility = CFSTR("com.trolltech.qt.accessibility");
-static EventHandlerUPP objectCreateEventHandlerUPP = 0;
-static EventTypeSpec objectCreateEvents[] = {
-    { kEventClassHIObject,  kEventHIObjectConstruct },
-    { kEventClassHIObject,  kEventHIObjectInitialize },
-    { kEventClassHIObject,  kEventHIObjectDestruct },
-    { kEventClassHIObject,  kEventHIObjectPrintDebugInfo }
-};
-
-static OSStatus accessibilityEventHandler(EventHandlerCallRef next_ref, EventRef event, void *data);
-static EventHandlerUPP accessibilityEventHandlerUPP = 0;
-static EventTypeSpec accessibilityEvents[] = {
-    { kEventClassAccessibility,  kEventAccessibleGetChildAtPoint },
-    { kEventClassAccessibility,  kEventAccessibleGetFocusedChild },
-    { kEventClassAccessibility,  kEventAccessibleGetAllAttributeNames },
-    { kEventClassAccessibility,  kEventAccessibleGetNamedAttribute },
-    { kEventClassAccessibility,  kEventAccessibleSetNamedAttribute },
-    { kEventClassAccessibility,  kEventAccessibleIsNamedAttributeSettable },
-    { kEventClassAccessibility,  kEventAccessibleGetAllActionNames },
-    { kEventClassAccessibility,  kEventAccessiblePerformNamedAction },
-    { kEventClassAccessibility,  kEventAccessibleGetNamedActionDescription }
-};
-
-static void installAcessibilityEventHandler(HIObjectRef hiObject)
-{
-    if (!accessibilityEventHandlerUPP)
-        accessibilityEventHandlerUPP = NewEventHandlerUPP(accessibilityEventHandler);
-
-    InstallHIObjectEventHandler(hiObject, accessibilityEventHandlerUPP,
-                                        GetEventTypeCount(accessibilityEvents),
-                                        accessibilityEvents, 0, 0);
-}
-
-static OSStatus objectCreateEventHandler(EventHandlerCallRef next_ref, EventRef event, void *data)
-{
-    Q_UNUSED(data)
-    Q_UNUSED(event)
-    Q_UNUSED(next_ref)
-    return noErr;
-}
-
-static void registerQtAccessibilityHIObjectSubclass()
-{
-    if (!objectCreateEventHandlerUPP)
-        objectCreateEventHandlerUPP = NewEventHandlerUPP(objectCreateEventHandler);
-    OSStatus err = HIObjectRegisterSubclass(kObjectQtAccessibility, 0, 0, objectCreateEventHandlerUPP,
-                                         GetEventTypeCount(objectCreateEvents), objectCreateEvents, 0, 0);
-    if (err && err != hiObjectClassExistsErr)
-        qWarning("qaccessible_mac internal error: Could not register accessibility HIObject subclass");
-}
-
-static void installApplicationEventhandler()
-{
-    if (!applicationEventHandlerUPP)
-        applicationEventHandlerUPP = NewEventHandlerUPP(applicationEventHandler);
-
-    OSStatus err = InstallApplicationEventHandler(applicationEventHandlerUPP,
-                            GetEventTypeCount(application_events), application_events,
-                            0, 0);
-
-    if (err && err != eventHandlerAlreadyInstalledErr)
-        qWarning("qaccessible_mac internal error: Could not install application accessibility event handler");
-}
-
-static void removeEventhandler(EventHandlerUPP eventHandler)
-{
-    if (eventHandler) {
-        DisposeEventHandlerUPP(eventHandler);
-        eventHandler = 0;
-    }
-}
diff --git a/src/gui/accessible/qaccessible_mac_cocoa.mm b/src/gui/accessible/qaccessible_mac_cocoa.mm
deleted file mode 100644 (file)
index b87b061..0000000
+++ /dev/null
@@ -1,239 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qaccessible.h"
-#include "qaccessible_mac_p.h"
-#include "qdebug.h"
-#include "qtabwidget.h"
-
-#include <qt_mac_p.h>
-#include <qcocoaview_mac_p.h>
-#include <qwidget_p.h>
-
-
-#ifndef QT_NO_ACCESSIBILITY
-
-#ifdef QT_MAC_USE_COCOA
-
-QT_BEGIN_NAMESPACE
-
-//#define MAC_ACCESSIBILTY_DEVELOPER_MODE
-
-#ifndef QT_NO_DEBUG_STREAM
-#ifdef MAC_ACCESSIBILTY_DEVELOPER_MODE
-#define MAC_ACCESSIBILTY_DEBUG QT_PREPEND_NAMESPACE(qDebug)
-#else
-#define MAC_ACCESSIBILTY_DEBUG if (0) QT_PREPEND_NAMESPACE(qDebug)
-#endif
-#else
-#define MAC_ACCESSIBILTY_DEBUG if (0) QT_PREPEND_NAMESPACE(QNoDebug)
-#endif
-
-typedef QMap<QAccessible::Role, NSString *> QMacAccessibiltyRoleMap;
-Q_GLOBAL_STATIC(QMacAccessibiltyRoleMap, qMacAccessibiltyRoleMap);
-
-static QAInterface interfaceForView(QT_MANGLE_NAMESPACE(QCocoaView) *view)
-{
-    return QAInterface(QAccessible::queryAccessibleInterface([view qt_qwidget]));
-}
-
-/*
-    Set up mappings from Qt accessibilty roles to Mac accessibilty roles.
-*/
-static void populateRoleMap()
-{
-    QMacAccessibiltyRoleMap &roleMap = *qMacAccessibiltyRoleMap();
-    roleMap[QAccessible::MenuItem] = NSAccessibilityMenuItemRole;
-    roleMap[QAccessible::MenuBar] = NSAccessibilityMenuBarRole;
-    roleMap[QAccessible::ScrollBar] = NSAccessibilityScrollBarRole;
-    roleMap[QAccessible::Grip] = NSAccessibilityGrowAreaRole;
-    roleMap[QAccessible::Window] = NSAccessibilityWindowRole;
-    roleMap[QAccessible::Dialog] = NSAccessibilityWindowRole;
-    roleMap[QAccessible::AlertMessage] = NSAccessibilityWindowRole;
-    roleMap[QAccessible::ToolTip] = NSAccessibilityWindowRole;
-    roleMap[QAccessible::HelpBalloon] = NSAccessibilityWindowRole;
-    roleMap[QAccessible::PopupMenu] = NSAccessibilityMenuRole;
-    roleMap[QAccessible::Application] = NSAccessibilityApplicationRole;
-    roleMap[QAccessible::Pane] = NSAccessibilityGroupRole;
-    roleMap[QAccessible::Grouping] = NSAccessibilityGroupRole;
-    roleMap[QAccessible::Separator] = NSAccessibilitySplitterRole;
-    roleMap[QAccessible::ToolBar] = NSAccessibilityToolbarRole;
-    roleMap[QAccessible::PageTab] = NSAccessibilityRadioButtonRole;
-    roleMap[QAccessible::ButtonMenu] = NSAccessibilityMenuButtonRole;
-    roleMap[QAccessible::ButtonDropDown] = NSAccessibilityPopUpButtonRole;
-    roleMap[QAccessible::SpinBox] = NSAccessibilityIncrementorRole;
-    roleMap[QAccessible::Slider] = NSAccessibilitySliderRole;
-    roleMap[QAccessible::ProgressBar] = NSAccessibilityProgressIndicatorRole;
-    roleMap[QAccessible::ComboBox] = NSAccessibilityPopUpButtonRole;
-    roleMap[QAccessible::RadioButton] = NSAccessibilityRadioButtonRole;
-    roleMap[QAccessible::CheckBox] = NSAccessibilityCheckBoxRole;
-    roleMap[QAccessible::StaticText] = NSAccessibilityStaticTextRole;
-    roleMap[QAccessible::Table] = NSAccessibilityTableRole;
-    roleMap[QAccessible::StatusBar] = NSAccessibilityStaticTextRole;
-    roleMap[QAccessible::Column] = NSAccessibilityColumnRole;
-    roleMap[QAccessible::ColumnHeader] = NSAccessibilityColumnRole;
-    roleMap[QAccessible::Row] = NSAccessibilityRowRole;
-    roleMap[QAccessible::RowHeader] = NSAccessibilityRowRole;
-    roleMap[QAccessible::Cell] = NSAccessibilityTextFieldRole;
-    roleMap[QAccessible::PushButton] = NSAccessibilityButtonRole;
-    roleMap[QAccessible::EditableText] = NSAccessibilityTextFieldRole;
-    roleMap[QAccessible::Link] = NSAccessibilityTextFieldRole;
-    roleMap[QAccessible::Indicator] = NSAccessibilityValueIndicatorRole;
-    roleMap[QAccessible::Splitter] = NSAccessibilitySplitGroupRole;
-    roleMap[QAccessible::List] = NSAccessibilityListRole;
-    roleMap[QAccessible::ListItem] = NSAccessibilityStaticTextRole;
-    roleMap[QAccessible::Cell] = NSAccessibilityStaticTextRole;
-}
-
-/*
-    Returns a Mac accessibility role for the given interface, or
-    NSAccessibilityUnknownRole if no role mapping is found.
-*/
-static NSString *macRoleForInterface(QAInterface interface)
-{
-    const QAccessible::Role qtRole = interface.role();
-    QMacAccessibiltyRoleMap &roleMap = *qMacAccessibiltyRoleMap();
-
-    if (roleMap.isEmpty())
-        populateRoleMap();
-
-    MAC_ACCESSIBILTY_DEBUG() << "role for" << interface.object() << "interface role" << hex << qtRole;
-
-    if (roleMap.contains(qtRole)) {
-        MAC_ACCESSIBILTY_DEBUG() << "return" <<  roleMap[qtRole];
-        return roleMap[qtRole];
-    }
-
-    MAC_ACCESSIBILTY_DEBUG() << "return NSAccessibilityUnknownRole";
-    return NSAccessibilityUnknownRole;
-}
-
-/*
-    Is the interface a QTabBar embedded in a QTabWidget?
-    (as opposed to a stand-alone tab bar)
-*/
-static bool isEmbeddedTabBar(const QAInterface &interface)
-{
-    QObject *object = interface.object();
-    if (interface.role() == QAccessible::PageTabList && object)
-        return (qobject_cast<QTabWidget *>(object->parent()));
-
-    return false;
-}
-
-static bool isInterfaceIgnored(QAInterface interface)
-{
-    // Mac accessibility does not have an attribute that corresponds to the 
-    // Invisible/Offscreen state. Use the ignore facility to disable them.
-    const QAccessible::State state = interface.state();
-    if (state & QAccessible::Invisible ||
-        state & QAccessible::Offscreen )
-        return false;
-
-    // Hide QTabBars that has a QTabWidget parent (the QTabWidget handles the accessibility)
-    if (isEmbeddedTabBar(interface))
-        return false;
-
-    if (QObject * const object = interface.object()) {
-        const QString className = QLatin1String(object->metaObject()->className());
-
-        // Prevent VoiceOver from focusing on tool tips by ignoring those
-        // interfaces. Shifting VoiceOver focus to the tool tip is confusing
-        // and the contents of the tool tip is avalible through the description 
-        // attribute anyway.
-        if (className == QLatin1String("QTipLabel"))
-            return false;
-    }
-
-    // Hide interfaces with an unknown role. When developing it's often useful to disable
-    // this check to see all interfaces in the hierarchy.
-#ifndef MAC_ACCESSIBILTY_DEVELOPER_MODE
-    return [macRoleForInterface(interface) isEqualToString: NSAccessibilityUnknownRole];
-#else
-    return NO;
-#endif
-}
-
-QT_END_NAMESPACE
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaView) (Accessibility)
-
-- (BOOL)accessibilityIsIgnored
-{
-    QT_PREPEND_NAMESPACE(QAInterface) interface = QT_PREPEND_NAMESPACE(interfaceForView)(self);
-    return isInterfaceIgnored(interface);
-}
-
-- (NSArray *)accessibilityAttributeNames
-{
-    QT_PREPEND_NAMESPACE(QAInterface) interface = QT_PREPEND_NAMESPACE(interfaceForView)(self);
-
-    static NSArray *attributes = nil;
-    if (attributes == nil) {
-        attributes = [super accessibilityAttributeNames];
-
-    }
-    return attributes;
-}
-
-- (id)accessibilityAttributeValue:(NSString *)attribute
-{
-    MAC_ACCESSIBILTY_DEBUG() << "accessibilityAttributeValue" << self <<  
-            QT_PREPEND_NAMESPACE(QCFString)::toQString(reinterpret_cast<CFStringRef>(attribute));
-
-    QT_PREPEND_NAMESPACE(QAInterface) interface = QT_PREPEND_NAMESPACE(interfaceForView)(self);
-
-    // Switch on the attribute name and call the appropriate handler function.
-    // Pass the call on to the NSView class for attributes we don't handle.
-    if ([attribute isEqualToString:@"AXRole"]) {
-        return macRoleForInterface(interface);
-    } else {
-        return [super accessibilityAttributeValue:attribute];    
-    }
-}
-
-@end
-
-#endif // QT_MAC_USE_COCOA
-
-#endif // QT_NO_ACCESSIBILITY
-
diff --git a/src/gui/accessible/qaccessible_mac_p.h b/src/gui/accessible/qaccessible_mac_p.h
deleted file mode 100644 (file)
index d6c7915..0000000
+++ /dev/null
@@ -1,479 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QACCESSIBLE_MAC_P_H
-#define QACCESSIBLE_MAC_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 <qglobal.h>
-#include <qt_mac_p.h>
-#include <qaccessible.h>
-#include <qwidget.h>
-#include <qdebug.h>
-
-//#define Q_ACCESSIBLE_MAC_DEBUG
-
-QT_BEGIN_NAMESPACE
-
-/*
-    QAccessibleInterfaceWrapper wraps QAccessibleInterface and adds
-    a ref count. QAccessibleInterfaceWrapper is a "by-value" class.
-*/
-class Q_AUTOTEST_EXPORT QAccessibleInterfaceWrapper
-{
-public:
-    QAccessibleInterfaceWrapper()
-    : interface(0), childrenIsRegistered(new bool(false)), refCount(new int(1)) { }
-
-    QAccessibleInterfaceWrapper(QAccessibleInterface *interface)
-    :interface(interface), childrenIsRegistered(new bool(false)), refCount(new int(1))  { }
-
-    ~QAccessibleInterfaceWrapper()
-    {
-        if (--(*refCount) == 0) {
-            delete interface;
-            delete refCount;
-            delete childrenIsRegistered;
-        }
-    }
-
-    QAccessibleInterfaceWrapper(const QAccessibleInterfaceWrapper &other)
-    :interface(other.interface), childrenIsRegistered(other.childrenIsRegistered), refCount(other.refCount)
-    {
-        ++(*refCount);
-    }
-
-    void operator=(const QAccessibleInterfaceWrapper &other)
-    {
-        if (other.interface == interface)
-            return;
-
-        if (--(*refCount) == 0) {
-            delete interface;
-            delete refCount;
-            delete childrenIsRegistered;
-        }
-
-        interface = other.interface;
-        childrenIsRegistered = other.childrenIsRegistered;
-        refCount = other.refCount;
-        ++(*refCount);
-    }
-
-    QAccessibleInterface *interface;
-    bool *childrenIsRegistered;
-private:
-    int *refCount;
-};
-
-/*
-    QAInterface represents one accessiblity item. It hides the fact that
-    one QAccessibleInterface may represent more than one item, and it also
-    automates the memory management for QAccessibleInterfaces using the
-    QAccessibleInterfaceWrapper wrapper class.
-
-    It has the same API as QAccessibleInterface, minus the child parameter
-    in the functions.
-*/
-class Q_AUTOTEST_EXPORT QAInterface : public QAccessible
-{
-public:
-    QAInterface()
-    : base(QAccessibleInterfaceWrapper())
-    { }
-
-    QAInterface(QAccessibleInterface *interface, int child = 0)
-    {
-        if (interface == 0 || child > interface->childCount()) {
-           base = QAccessibleInterfaceWrapper(); 
-        } else {
-            base = QAccessibleInterfaceWrapper(interface);
-            m_cachedObject = interface->object();
-            this->child = child;
-        }
-    }
-
-    QAInterface(QAccessibleInterfaceWrapper wrapper, int child = 0)
-    :base(wrapper), m_cachedObject(wrapper.interface->object()), child(child)
-    { }
-
-    QAInterface(const QAInterface &other, int child)
-    {
-        if (other.isValid() == false || child > other.childCount()) {
-           base = QAccessibleInterfaceWrapper();
-        } else {
-            base = other.base;
-            m_cachedObject = other.m_cachedObject;
-            this->child = child;
-        }
-    }
-
-    bool operator==(const QAInterface &other) const;
-    bool operator!=(const QAInterface &other) const;
-
-    inline QString actionText (int action, Text text) const
-    { return base.interface->actionText(action, text, child); }
-
-    QAInterface childAt(int x, int y) const
-    {
-        if (!checkValid())
-            return QAInterface();
-
-        const int foundChild = base.interface->childAt(x, y);
-
-        if (foundChild == -1)
-            return QAInterface();
-
-        if (child == 0)
-            return navigate(QAccessible::Child, foundChild);
-
-        if (foundChild == child)
-            return *this;
-        return QAInterface();
-    }
-
-    int indexOfChild(const QAInterface &child) const
-    {
-        if (!checkValid())
-            return -1;
-
-        if (*this != child.parent())
-            return -1;
-
-        if (object() == child.object())
-            return child.id();
-
-        return base.interface->indexOfChild(child.base.interface);
-    }
-
-    inline int childCount() const
-    {
-        if (!checkValid())
-            return 0;
-
-        if (child != 0)
-            return 0;
-        return base.interface->childCount();
-    }
-
-    QList<QAInterface> children() const
-    {
-        if (!checkValid())
-            return QList<QAInterface>();
-
-        QList<QAInterface> children;
-        for (int i = 1; i <= childCount(); ++i) {
-            children.append(navigate(QAccessible::Child, i));
-        }
-        return children;
-    }
-
-    QAInterface childAt(int index) const
-    {
-        return navigate(QAccessible::Child, index);
-    }
-
-    inline void doAction(int action, const QVariantList &params = QVariantList()) const
-    {
-        if (!checkValid())
-            return;
-
-        base.interface->doAction(action, child, params);
-    }
-
-    QAInterface navigate(RelationFlag relation, int entry) const;
-
-    inline QObject * object() const
-    {
-        if (!checkValid())
-            return 0;
-
-        return base.interface->object();
-    }
-
-    QAInterface objectInterface() const
-    {
-        if (!checkValid())
-            return QAInterface();
-
-        QObject *obj = object();
-        QAInterface current = *this;
-        while (obj == 0)
-        {
-            QAInterface parent = current.parent();
-            if (parent.isValid() == false)
-                break;
-            obj = parent.object();
-            current = parent;
-        }
-        return current;
-    }
-
-    inline HIObjectRef hiObject() const
-    {
-        if (!checkValid())
-            return 0;
-        QWidget * const widget = qobject_cast<QWidget * const>(object());
-        if (widget)
-            return (HIObjectRef)widget->winId();
-        else
-            return 0;
-    }
-
-    inline QObject * cachedObject() const
-    {
-        if (!checkValid())
-            return 0;
-        return m_cachedObject;
-    }
-
-    inline QRect rect() const
-    {
-        if (!checkValid())
-            return QRect();
-        return base.interface->rect(child);
-    }
-
-    inline Role role() const
-    {
-        if (!checkValid())
-            return QAccessible::NoRole;
-        return base.interface->role(child);
-    }
-
-    inline void setText(Text t, const QString &text) const
-    {
-        if (!checkValid())
-            return;
-        base.interface->setText(t, child, text);
-    }
-
-    inline State state() const
-    {
-        if (!checkValid())
-            return 0;
-        return base.interface->state(child);
-    }
-
-    inline QString text (Text text) const
-    {
-        if (!checkValid())
-            return QString();
-        return base.interface->text(text, child);
-    }
-
-    inline QString value() const
-    { return text(QAccessible::Value); }
-
-    inline QString name() const
-    { return text(QAccessible::Name); }
-
-    inline int userActionCount() const
-    {
-        if (!checkValid())
-            return 0;
-        return base.interface->userActionCount(child);
-    }
-
-    inline QString className() const
-    {
-        if (!checkValid())
-            return QString();
-        return QLatin1String(base.interface->object()->metaObject()->className());
-    }
-
-    inline bool isHIView() const
-    { return (child == 0 && object() != 0); }
-
-    inline int id() const
-    { return child; }
-
-    inline bool isValid() const
-    {
-        return (base.interface != 0 && base.interface->isValid());
-    }
-
-    QAInterface parent() const
-    { return navigate(QAccessible::Ancestor, 1); }
-
-    QAccessibleInterfaceWrapper interfaceWrapper() const
-    { return base; }
-
-protected:
-    bool checkValid() const
-    {
-        const bool valid = isValid();
-#ifdef Q_ACCESSIBLE_MAC_DEBUG
-        if (!valid)
-            qFatal("QAccessible_mac: tried to use invalid interface.");
-#endif
-        return valid;
-    }
-
-    QAccessibleInterfaceWrapper base;
-    QObject *m_cachedObject;
-    int child;
-};
-
-Q_AUTOTEST_EXPORT QDebug operator<<(QDebug debug, const QAInterface &interface);
-
-/*
-    QAElement is a thin wrapper around an AXUIElementRef that automates
-    the ref-counting.
-*/
-class Q_AUTOTEST_EXPORT QAElement
-{
-public:
-    QAElement();
-    explicit QAElement(AXUIElementRef elementRef);
-    QAElement(const QAElement &element);
-    QAElement(HIObjectRef, int child);
-    ~QAElement();
-
-    inline HIObjectRef object() const
-    {
-#ifndef Q_WS_MAC64
-        return AXUIElementGetHIObject(elementRef);
-#else
-        return 0;
-#endif
-    }
-
-    inline int id() const
-    {
-        UInt64 theId;
-#ifndef QT_MAC_USE_COCOA
-        AXUIElementGetIdentifier(elementRef, &theId);
-#else
-        theId = 0;
-#endif
-        return theId;
-    }
-
-    inline AXUIElementRef element() const
-    {
-        return elementRef;
-    }
-
-    inline bool isValid() const
-    {
-        return (elementRef != 0);
-    }
-
-    void operator=(const QAElement &other);
-    bool operator==(const QAElement &other) const;
-private:
-    AXUIElementRef elementRef;
-};
-
-
-class QInterfaceFactory
-{
-public:
-    virtual QAInterface interface(UInt64 identifier) = 0;
-    virtual QAElement element(int id) = 0;
-    virtual QAElement element(const QAInterface &interface)
-    {
-        return element(interface.id());
-    }
-    virtual void registerChildren() = 0;
-    virtual ~QInterfaceFactory() {}
-};
-
-/*
-    QAccessibleHierarchyManager bridges the Mac and Qt accessibility hierarchies.
-    There is a one-to-one relationship between QAElements on the Mac side
-    and QAInterfaces on the Qt side, and this class provides lookup functions
-    that translates between these to items.
-
-    The identity of a QAInterface is determined by its QAccessibleInterface and
-    child identifier, and the identity of a QAElement is determined by its
-    HIObjectRef and identifier.
-
-    QAccessibleHierarchyManager receives QObject::destroyed() signals and deletes
-    the accessibility objects for destroyed objects.
-*/
-class Q_AUTOTEST_EXPORT QAccessibleHierarchyManager : public QObject
-{
-    Q_OBJECT
-public:
-    ~QAccessibleHierarchyManager() { reset(); }
-    static QAccessibleHierarchyManager *instance();
-    void reset();
-
-    QAElement registerInterface(QObject *object, int child);
-    QAElement registerInterface(const QAInterface &interface);
-    void registerInterface(QObject *object, HIObjectRef hiobject, QInterfaceFactory *interfaceFactory);
-
-    void registerChildren(const QAInterface &interface);
-
-    QAInterface lookup(const AXUIElementRef &element);
-    QAInterface lookup(const QAElement &element);
-    QAElement lookup(const QAInterface &interface);
-    QAElement lookup(QObject * const object, int id);
-private slots:
-    void objectDestroyed(QObject *);
-private:
-    typedef QHash<QObject *, QInterfaceFactory *> QObjectElementHash;
-    typedef QHash<HIObjectRef, QInterfaceFactory *> HIObjectInterfaceHash;
-    typedef QHash<QObject *, HIObjectRef> QObjectHIObjectHash;
-
-    QObjectElementHash qobjectElementHash;
-    HIObjectInterfaceHash hiobjectInterfaceHash;
-    QObjectHIObjectHash qobjectHiobjectHash;
-};
-
-Q_AUTOTEST_EXPORT bool isItInteresting(const QAInterface &interface);
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/accessible/qaccessible_win.cpp b/src/gui/accessible/qaccessible_win.cpp
deleted file mode 100644 (file)
index bc65ede..0000000
+++ /dev/null
@@ -1,1477 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include "qaccessible.h"
-#ifndef QT_NO_ACCESSIBILITY
-
-#include "qapplication.h"
-#include <qsystemlibrary_p.h>
-#include "qmessagebox.h" // ### dependency
-#include "qt_windows.h"
-#include "qwidget.h"
-#include "qsettings.h"
-#include <QtCore/qmap.h>
-#include <QtCore/qpair.h>
-#include <QtCore/qpointer.h>
-#include <QtGui/qgraphicsitem.h>
-#include <QtGui/qgraphicsscene.h>
-#include <QtGui/qgraphicsview.h>
-
-#include <winuser.h>
-#if !defined(WINABLEAPI)
-#  if defined(Q_WS_WINCE)
-#    include <bldver.h>
-#  endif
-#  include <winable.h>
-#endif
-
-#include <oleacc.h>
-#if !defined(Q_CC_BOR) && !defined (Q_CC_GNU)
-#include <comdef.h>
-#endif
-
-#ifdef Q_WS_WINCE
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-//#define DEBUG_SHOW_ATCLIENT_COMMANDS
-#ifdef DEBUG_SHOW_ATCLIENT_COMMANDS
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <qdebug.h>
-QT_END_INCLUDE_NAMESPACE
-
-static const char *roleString(QAccessible::Role role)
-{
-    static const char *roles[] = {
-       "NoRole"         /* = 0x00000000 */,
-       "TitleBar"       /* = 0x00000001 */,
-       "MenuBar"        /* = 0x00000002 */,
-       "ScrollBar"      /* = 0x00000003 */,
-       "Grip"           /* = 0x00000004 */,
-       "Sound"          /* = 0x00000005 */,
-       "Cursor"         /* = 0x00000006 */,
-       "Caret"          /* = 0x00000007 */,
-       "AlertMessage"   /* = 0x00000008 */,
-       "Window"         /* = 0x00000009 */,
-       "Client"         /* = 0x0000000A */,
-       "PopupMenu"      /* = 0x0000000B */,
-       "MenuItem"       /* = 0x0000000C */,
-       "ToolTip"        /* = 0x0000000D */,
-       "Application"    /* = 0x0000000E */,
-       "Document"       /* = 0x0000000F */,
-       "Pane"           /* = 0x00000010 */,
-       "Chart"          /* = 0x00000011 */,
-       "Dialog"         /* = 0x00000012 */,
-       "Border"         /* = 0x00000013 */,
-       "Grouping"       /* = 0x00000014 */,
-       "Separator"      /* = 0x00000015 */,
-       "ToolBar"        /* = 0x00000016 */,
-       "StatusBar"      /* = 0x00000017 */,
-       "Table"          /* = 0x00000018 */,
-       "ColumnHeader"   /* = 0x00000019 */,
-       "RowHeader"      /* = 0x0000001A */,
-       "Column"         /* = 0x0000001B */,
-       "Row"            /* = 0x0000001C */,
-       "Cell"           /* = 0x0000001D */,
-       "Link"           /* = 0x0000001E */,
-       "HelpBalloon"    /* = 0x0000001F */,
-       "Assistant"      /* = 0x00000020 */,
-       "List"           /* = 0x00000021 */,
-       "ListItem"       /* = 0x00000022 */,
-       "Tree"           /* = 0x00000023 */,
-       "TreeItem"       /* = 0x00000024 */,
-       "PageTab"        /* = 0x00000025 */,
-       "PropertyPage"   /* = 0x00000026 */,
-       "Indicator"      /* = 0x00000027 */,
-       "Graphic"        /* = 0x00000028 */,
-       "StaticText"     /* = 0x00000029 */,
-       "EditableText"   /* = 0x0000002A */,  // Editable, selectable, etc.
-       "PushButton"     /* = 0x0000002B */,
-       "CheckBox"       /* = 0x0000002C */,
-       "RadioButton"    /* = 0x0000002D */,
-       "ComboBox"       /* = 0x0000002E */,
-       "DropList"       /* = 0x0000002F */,    // commented out
-       "ProgressBar"    /* = 0x00000030 */,
-       "Dial"           /* = 0x00000031 */,
-       "HotkeyField"    /* = 0x00000032 */,
-       "Slider"         /* = 0x00000033 */,
-       "SpinBox"        /* = 0x00000034 */,
-       "Canvas"         /* = 0x00000035 */,
-       "Animation"      /* = 0x00000036 */,
-       "Equation"       /* = 0x00000037 */,
-       "ButtonDropDown" /* = 0x00000038 */,
-       "ButtonMenu"     /* = 0x00000039 */,
-       "ButtonDropGrid" /* = 0x0000003A */,
-       "Whitespace"     /* = 0x0000003B */,
-       "PageTabList"    /* = 0x0000003C */,
-       "Clock"          /* = 0x0000003D */,
-       "Splitter"       /* = 0x0000003E */,
-       "LayeredPane"    /* = 0x0000003F */,
-       "UserRole"       /* = 0x0000ffff*/
-   };
-
-   if (role >=0x40)
-        role = QAccessible::UserRole;
-   return roles[int(role)];
-}
-
-static const char *eventString(QAccessible::Event ev)
-{
-    static const char *events[] = {
-        "null",                                 // 0
-        "SoundPlayed"          /*= 0x0001*/,
-        "Alert"                /*= 0x0002*/,
-        "ForegroundChanged"    /*= 0x0003*/,
-        "MenuStart"            /*= 0x0004*/,
-        "MenuEnd"              /*= 0x0005*/,
-        "PopupMenuStart"       /*= 0x0006*/,
-        "PopupMenuEnd"         /*= 0x0007*/,
-        "ContextHelpStart"     /*= 0x000C*/,    // 8
-        "ContextHelpEnd"       /*= 0x000D*/,
-        "DragDropStart"        /*= 0x000E*/,
-        "DragDropEnd"          /*= 0x000F*/,
-        "DialogStart"          /*= 0x0010*/,
-        "DialogEnd"            /*= 0x0011*/,
-        "ScrollingStart"       /*= 0x0012*/,
-        "ScrollingEnd"         /*= 0x0013*/,
-        "MenuCommand"          /*= 0x0018*/,    // 16
-
-        // Values from IAccessible2
-        "ActionChanged"        /*= 0x0101*/,    // 17
-        "ActiveDescendantChanged",
-        "AttributeChanged",
-        "DocumentContentChanged",
-        "DocumentLoadComplete",
-        "DocumentLoadStopped",
-        "DocumentReload",
-        "HyperlinkEndIndexChanged",
-        "HyperlinkNumberOfAnchorsChanged",
-        "HyperlinkSelectedLinkChanged",
-        "HypertextLinkActivated",
-        "HypertextLinkSelected",
-        "HyperlinkStartIndexChanged",
-        "HypertextChanged",
-        "HypertextNLinksChanged",
-        "ObjectAttributeChanged",
-        "PageChanged",
-        "SectionChanged",
-        "TableCaptionChanged",
-        "TableColumnDescriptionChanged",
-        "TableColumnHeaderChanged",
-        "TableModelChanged",
-        "TableRowDescriptionChanged",
-        "TableRowHeaderChanged",
-        "TableSummaryChanged",
-        "TextAttributeChanged",
-        "TextCaretMoved",
-        // TextChanged, deprecated, use TextUpdated
-        //TextColumnChanged = TextCaretMoved + 2,
-        "TextInserted",
-        "TextRemoved",
-        "TextUpdated",
-        "TextSelectionChanged",
-        "VisibleDataChanged",  /*= 0x0101+32*/
-        "ObjectCreated"        /*= 0x8000*/,    // 49
-        "ObjectDestroyed"      /*= 0x8001*/,
-        "ObjectShow"           /*= 0x8002*/,
-        "ObjectHide"           /*= 0x8003*/,
-        "ObjectReorder"        /*= 0x8004*/,
-        "Focus"                /*= 0x8005*/,
-        "Selection"            /*= 0x8006*/,
-        "SelectionAdd"         /*= 0x8007*/,
-        "SelectionRemove"      /*= 0x8008*/,
-        "SelectionWithin"      /*= 0x8009*/,
-        "StateChanged"         /*= 0x800A*/,
-        "LocationChanged"      /*= 0x800B*/,
-        "NameChanged"          /*= 0x800C*/,
-        "DescriptionChanged"   /*= 0x800D*/,
-        "ValueChanged"         /*= 0x800E*/,
-        "ParentChanged"        /*= 0x800F*/,
-        "HelpChanged"          /*= 0x80A0*/,
-        "DefaultActionChanged" /*= 0x80B0*/,
-        "AcceleratorChanged"   /*= 0x80C0*/
-    };
-    int e = int(ev);
-    if (e <= 0x80c0) {
-        const int last = sizeof(events)/sizeof(char*) - 1;
-
-        if (e <= 0x07)
-            return events[e];
-        else if (e <= 0x13)
-            return events[e - 0x0c + 8];
-        else if (e == 0x18)
-            return events[16];
-        else if (e <= 0x0101 + 32)
-            return events[e - 0x101 + 17];
-        else if (e <= 0x800f)
-            return events[e - 0x8000 + 49];
-        else if (e == 0x80a0)
-            return events[last - 2];
-        else if (e == 0x80b0)
-            return events[last - 1];
-        else if (e == 0x80c0)
-            return events[last];
-    }
-    return "unknown";
-};
-
-void showDebug(const char* funcName, const QAccessibleInterface *iface)
-{
-    qDebug() << "Role:" << roleString(iface->role(0)) 
-             << "Name:" << iface->text(QAccessible::Name, 0) 
-             << "State:" << QString::number(int(iface->state(0)), 16) 
-             << QLatin1String(funcName);
-}
-#else
-# define showDebug(f, iface)
-#endif
-
-// This stuff is used for widgets/items with no window handle:
-typedef QMap<int, QPair<QPointer<QObject>, int> > NotifyMap;
-Q_GLOBAL_STATIC(NotifyMap, qAccessibleRecentSentEvents)
-static int eventNum = 0;
-
-
-void QAccessible::initialize()
-{
-
-}
-void QAccessible::cleanup()
-{
-
-}
-
-void QAccessible::updateAccessibility(QObject *o, int who, Event reason)
-{
-    Q_ASSERT(o);
-
-    if (updateHandler) {
-        updateHandler(o, who, reason);
-        return;
-    }
-
-    QString soundName;
-    switch (reason) {
-    case PopupMenuStart:
-        soundName = QLatin1String("MenuPopup");
-        break;
-
-    case MenuCommand:
-        soundName = QLatin1String("MenuCommand");
-        break;
-
-    case Alert:
-        {
-#ifndef QT_NO_MESSAGEBOX
-            QMessageBox *mb = qobject_cast<QMessageBox*>(o);
-            if (mb) {
-                switch (mb->icon()) {
-                case QMessageBox::Warning:
-                    soundName = QLatin1String("SystemExclamation");
-                    break;
-                case QMessageBox::Critical:
-                    soundName = QLatin1String("SystemHand");
-                    break;
-                case QMessageBox::Information:
-                    soundName = QLatin1String("SystemAsterisk");
-                    break;
-                default:
-                    break;
-                }
-            } else
-#endif // QT_NO_MESSAGEBOX
-            {
-                soundName = QLatin1String("SystemAsterisk");
-            }
-
-        }
-        break;
-    default:
-        break;
-    }
-
-    if (soundName.size()) {
-#ifndef QT_NO_SETTINGS
-        QSettings settings(QLatin1String("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\.Default\\") + soundName,
-                           QSettings::NativeFormat);
-        QString file = settings.value(QLatin1String(".Current/.")).toString();
-#else
-        QString file;
-#endif
-        if (!file.isEmpty()) {
-                                   PlaySound(reinterpret_cast<const wchar_t *>(soundName.utf16()), 0, SND_ALIAS | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT);
-        }
-    }
-
-    if (!isActive())
-        return;
-
-    typedef void (WINAPI *PtrNotifyWinEvent)(DWORD, HWND, LONG, LONG);
-
-#if defined(Q_WS_WINCE) // ### TODO: check for NotifyWinEvent in CE 6.0
-    // There is no user32.lib nor NotifyWinEvent for CE
-    return;
-#else
-    static PtrNotifyWinEvent ptrNotifyWinEvent = 0;
-    static bool resolvedNWE = false;
-    if (!resolvedNWE) {
-        ptrNotifyWinEvent = (PtrNotifyWinEvent)QSystemLibrary::resolve(QLatin1String("user32"), "NotifyWinEvent");
-        resolvedNWE = true;
-    }
-    if (!ptrNotifyWinEvent)
-        return;
-
-    // An event has to be associated with a window,
-    // so find the first parent that is a widget.
-    QWidget *w = 0;
-    QObject *p = o;
-    do {
-        if (p->isWidgetType()) {
-            w = static_cast<QWidget*>(p);
-            if (w->internalWinId())
-                break;
-        }
-        if (QGraphicsObject *gfxObj = qobject_cast<QGraphicsObject*>(p)) {
-            QGraphicsItem *parentItem = gfxObj->parentItem();
-            if (parentItem) {
-                p = parentItem->toGraphicsObject();
-            } else {
-                QGraphicsView *view = 0;
-                if (QGraphicsScene *scene = gfxObj->scene()) {
-                    QWidget *fw = QApplication::focusWidget();
-                    const QList<QGraphicsView*> views = scene->views();
-                    for (int i = 0 ; i < views.count() && view != fw; ++i) {
-                        view = views.at(i);
-                    }
-                }
-                p = view;
-            }
-        } else {
-            p = p->parent();
-        }
-
-    } while (p);
-
-    //qDebug() << "updateAccessibility(), hwnd:" << w << ", object:" << o << "," << eventString(reason);
-    if (!w) {
-        if (reason != QAccessible::ContextHelpStart &&
-             reason != QAccessible::ContextHelpEnd)
-            w = QApplication::focusWidget();
-        if (!w) {
-            w = QApplication::activeWindow();
-
-            if (!w)
-                return;
-
-// ### Fixme
-//             if (!w) {
-//                 w = qApp->mainWidget();
-//                 if (!w)
-//                     return;
-//             }
-        }
-    }
-
-    WId wid = w->internalWinId();
-    if (reason != MenuCommand) { // MenuCommand is faked
-        if (w != o) {
-            // See comment "SENDING EVENTS TO OBJECTS WITH NO WINDOW HANDLE"
-            if (reason != QAccessible::ObjectDestroyed) {
-                /* In some rare occasions, the server (Qt) might get a ::get_accChild call with a
-                   childId that references an entry in the cache where there was a dangling
-                   QObject-pointer. Previously we crashed on this.
-
-                   There is no point in actually notifying the AT client that the object got destroyed,
-                   because the AT client won't query for get_accChild if the event is ObjectDestroyed
-                   anyway, and we have no other way of mapping the eventId argument to the actual
-                   child/descendant object. (Firefox seems to simply completely ignore
-                   EVENT_OBJECT_DESTROY).
-
-                   We therefore guard each QObject in the cache with a QPointer, and only notify the AT
-                   client if the type is not ObjectDestroyed.
-                */
-                eventNum %= 50;              //[0..49]
-                int eventId = - eventNum - 1;
-                qAccessibleRecentSentEvents()->insert(eventId, qMakePair(QPointer<QObject>(o), who));
-                ptrNotifyWinEvent(reason, wid, OBJID_CLIENT, eventId );
-                ++eventNum;
-            }
-        } else {
-            ptrNotifyWinEvent(reason, wid, OBJID_CLIENT, who);
-        }
-    }
-#endif // Q_WS_WINCE
-}
-
-/*  == SENDING EVENTS TO OBJECTS WITH NO WINDOW HANDLE ==
-
-    If the user requested to send the event to a widget with no window,
-    we need to send an event to an object with no hwnd.
-    The way we do that is to send it to the *first* ancestor widget
-    with a window.
-    Then we'll need a way of identifying the child:
-    We'll just keep a list of the most recent events that we have sent,
-    where each entry in the list is identified by a negative value
-    between [-50,-1]. This negative value we will pass on to
-    NotifyWinEvent() as the child id. When the negative value have
-    reached -50, it will wrap around to -1. This seems to be enough
-
-    Now, when the client receives that event, he will first call
-    AccessibleObjectFromEvent() where dwChildID is the special
-    negative value. AccessibleObjectFromEvent does two steps:
-    1. It will first sent a WM_GETOBJECT to the server, asking
-       for the IAccessible interface for the HWND.
-    2. With the IAccessible interface it got hold of it will call
-       acc_getChild where the child id argument is the special
-       negative identifier. In our reimplementation of get_accChild
-       we check for this if the child id is negative. If it is, then
-       we'll look up in our table for the entry that is associated
-       with that value.
-       The entry will then contain a pointer to the QObject /QWidget
-       that we can use to call queryAccessibleInterface() on.
-
-
-    The following figure shows how the interaction between server and
-    client is in the case when the server is sending an event.
-
-SERVER (Qt)                                 | CLIENT                                |
---------------------------------------------+---------------------------------------+
-                                            |
-acc->updateAccessibility(obj,  childIndex)  |
-                                            |
-recentEvents()->insert(- 1 - eventNum,      |
-            qMakePair(obj, childIndex)      |
-NotifyWinEvent(hwnd, childId) =>            |
-                                            |   AccessibleObjectFromEvent(event, hwnd, OBJID_CLIENT, childId )
-                                            |   will do:
-                                          <===  1. send WM_GETOBJECT(hwnd, OBJID_CLIENT)
-widget ~= hwnd
-iface = queryAccessibleInteface(widget)
-(create IAccessible interface wrapper for
- iface)
- return iface                              ===> IAccessible* iface; (for hwnd)
-                                            |
-                                          <===  call iface->get_accChild(childId)
-get_accChild() {                            |
-    if (varChildID.lVal < 0) {
-        QPair ref = recentEvents().value(varChildID.lVal);
-        [...]
-    }
-*/
-
-
-void QAccessible::setRootObject(QObject *o)
-{
-    if (rootObjectHandler) {
-        rootObjectHandler(o);
-    }
-}
-
-class QWindowsEnumerate : public IEnumVARIANT
-{
-public:
-    QWindowsEnumerate(const QVector<int> &a)
-        : ref(0), current(0),array(a)
-    {
-    }
-
-    virtual ~QWindowsEnumerate() {}
-
-    HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, LPVOID *);
-    ULONG STDMETHODCALLTYPE AddRef();
-    ULONG STDMETHODCALLTYPE Release();
-
-    HRESULT STDMETHODCALLTYPE Clone(IEnumVARIANT **ppEnum);
-    HRESULT STDMETHODCALLTYPE Next(unsigned long  celt, VARIANT FAR*  rgVar, unsigned long FAR*  pCeltFetched);
-    HRESULT STDMETHODCALLTYPE Reset();
-    HRESULT STDMETHODCALLTYPE Skip(unsigned long celt);
-
-private:
-    ULONG ref;
-    ULONG current;
-    QVector<int> array;
-};
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::QueryInterface(REFIID id, LPVOID *iface)
-{
-    *iface = 0;
-    if (id == IID_IUnknown)
-        *iface = (IUnknown*)this;
-    else if (id == IID_IEnumVARIANT)
-        *iface = (IEnumVARIANT*)this;
-
-    if (*iface) {
-        AddRef();
-        return S_OK;
-    }
-
-    return E_NOINTERFACE;
-}
-
-ULONG STDMETHODCALLTYPE QWindowsEnumerate::AddRef()
-{
-    return ++ref;
-}
-
-ULONG STDMETHODCALLTYPE QWindowsEnumerate::Release()
-{
-    if (!--ref) {
-        delete this;
-        return 0;
-    }
-    return ref;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Clone(IEnumVARIANT **ppEnum)
-{
-    QWindowsEnumerate *penum = 0;
-    *ppEnum = 0;
-
-    penum = new QWindowsEnumerate(array);
-    if (!penum)
-        return E_OUTOFMEMORY;
-    penum->current = current;
-    penum->array = array;
-    penum->AddRef();
-    *ppEnum = penum;
-
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Next(unsigned long  celt, VARIANT FAR*  rgVar, unsigned long FAR*  pCeltFetched)
-{
-    if (pCeltFetched)
-        *pCeltFetched = 0;
-
-    ULONG l;
-    for (l = 0; l < celt; l++) {
-        VariantInit(&rgVar[l]);
-        if ((current+1) > (ULONG)array.size()) {
-            *pCeltFetched = l;
-            return S_FALSE;
-        }
-
-        rgVar[l].vt = VT_I4;
-        rgVar[l].lVal = array[(int)current];
-        ++current;
-    }
-    *pCeltFetched = l;
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Reset()
-{
-    current = 0;
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsEnumerate::Skip(unsigned long celt)
-{
-    current += celt;
-    if (current > (ULONG)array.size()) {
-        current = array.size();
-        return S_FALSE;
-    }
-    return S_OK;
-}
-
-struct AccessibleElement {
-    AccessibleElement(int entryId, QAccessibleInterface *accessible) {
-        if (entryId < 0) {
-            QPair<QPointer<QObject>, int> ref = qAccessibleRecentSentEvents()->value(entryId);
-            iface = QAccessible::queryAccessibleInterface(ref.first.data());
-            entry = ref.second;
-            cleanupInterface = true;
-        } else {
-            iface = accessible;
-            entry = entryId;
-            cleanupInterface = false;
-        }
-    }
-
-    QString text(QAccessible::Text t) const {
-        return iface ? iface->text(t, entry) : QString();
-    }
-
-    ~AccessibleElement() {
-        if (cleanupInterface)
-            delete iface;
-    }
-
-    QAccessibleInterface *iface;
-    int entry;
-private:
-    bool cleanupInterface;
-};
-
-/*
-*/
-class QWindowsAccessible : public IAccessible, IOleWindow, QAccessible
-{
-public:
-    QWindowsAccessible(QAccessibleInterface *a)
-        : ref(0), accessible(a)
-    {
-    }
-
-    virtual ~QWindowsAccessible()
-    {
-        delete accessible;
-    }
-
-    /* IUnknown */
-    HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, LPVOID *);
-    ULONG STDMETHODCALLTYPE AddRef();
-    ULONG STDMETHODCALLTYPE Release();
-
-    /* IDispatch */
-    HRESULT STDMETHODCALLTYPE GetTypeInfoCount(unsigned int *);
-    HRESULT STDMETHODCALLTYPE GetTypeInfo(unsigned int, unsigned long, ITypeInfo **);
-    HRESULT STDMETHODCALLTYPE GetIDsOfNames(const _GUID &, wchar_t **, unsigned int, unsigned long, long *);
-    HRESULT STDMETHODCALLTYPE Invoke(long, const _GUID &, unsigned long, unsigned short, tagDISPPARAMS *, tagVARIANT *, tagEXCEPINFO *, unsigned int *);
-
-    /* IAccessible */
-    HRESULT STDMETHODCALLTYPE accHitTest(long xLeft, long yTop, VARIANT *pvarID);
-    HRESULT STDMETHODCALLTYPE accLocation(long *pxLeft, long *pyTop, long *pcxWidth, long *pcyHeight, VARIANT varID);
-    HRESULT STDMETHODCALLTYPE accNavigate(long navDir, VARIANT varStart, VARIANT *pvarEnd);
-    HRESULT STDMETHODCALLTYPE get_accChild(VARIANT varChildID, IDispatch** ppdispChild);
-    HRESULT STDMETHODCALLTYPE get_accChildCount(long* pcountChildren);
-    HRESULT STDMETHODCALLTYPE get_accParent(IDispatch** ppdispParent);
-
-    HRESULT STDMETHODCALLTYPE accDoDefaultAction(VARIANT varID);
-    HRESULT STDMETHODCALLTYPE get_accDefaultAction(VARIANT varID, BSTR* pszDefaultAction);
-    HRESULT STDMETHODCALLTYPE get_accDescription(VARIANT varID, BSTR* pszDescription);
-    HRESULT STDMETHODCALLTYPE get_accHelp(VARIANT varID, BSTR *pszHelp);
-    HRESULT STDMETHODCALLTYPE get_accHelpTopic(BSTR *pszHelpFile, VARIANT varChild, long *pidTopic);
-    HRESULT STDMETHODCALLTYPE get_accKeyboardShortcut(VARIANT varID, BSTR *pszKeyboardShortcut);
-    HRESULT STDMETHODCALLTYPE get_accName(VARIANT varID, BSTR* pszName);
-    HRESULT STDMETHODCALLTYPE put_accName(VARIANT varChild, BSTR szName);
-    HRESULT STDMETHODCALLTYPE get_accRole(VARIANT varID, VARIANT *pvarRole);
-    HRESULT STDMETHODCALLTYPE get_accState(VARIANT varID, VARIANT *pvarState);
-    HRESULT STDMETHODCALLTYPE get_accValue(VARIANT varID, BSTR* pszValue);
-    HRESULT STDMETHODCALLTYPE put_accValue(VARIANT varChild, BSTR szValue);
-
-    HRESULT STDMETHODCALLTYPE accSelect(long flagsSelect, VARIANT varID);
-    HRESULT STDMETHODCALLTYPE get_accFocus(VARIANT *pvarID);
-    HRESULT STDMETHODCALLTYPE get_accSelection(VARIANT *pvarChildren);
-
-    /* IOleWindow */
-    HRESULT STDMETHODCALLTYPE GetWindow(HWND *phwnd);
-    HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(BOOL fEnterMode);
-
-private:
-    ULONG ref;
-    QAccessibleInterface *accessible;
-};
-
-static inline BSTR QStringToBSTR(const QString &str)
-{
-    return SysAllocStringLen((OLECHAR*)str.unicode(), str.length());
-}
-
-/*
-*/
-IAccessible *qt_createWindowsAccessible(QAccessibleInterface *access)
-{
-    QWindowsAccessible *acc = new QWindowsAccessible(access);
-    IAccessible *iface;
-    acc->QueryInterface(IID_IAccessible, (void**)&iface);
-
-    return iface;
-}
-
-/*
-  IUnknown
-*/
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::QueryInterface(REFIID id, LPVOID *iface)
-{
-    *iface = 0;
-    if (id == IID_IUnknown)
-        *iface = (IUnknown*)(IDispatch*)this;
-    else if (id == IID_IDispatch)
-        *iface = (IDispatch*)this;
-    else if (id == IID_IAccessible)
-        *iface = (IAccessible*)this;
-    else if (id == IID_IOleWindow)
-        *iface = (IOleWindow*)this;
-    else
-        return E_NOINTERFACE;
-
-    AddRef();
-    return S_OK;
-}
-
-ULONG STDMETHODCALLTYPE QWindowsAccessible::AddRef()
-{
-    return ++ref;
-}
-
-ULONG STDMETHODCALLTYPE QWindowsAccessible::Release()
-{
-    if (!--ref) {
-        delete this;
-        return 0;
-    }
-    return ref;
-}
-
-/*
-  IDispatch
-*/
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::GetTypeInfoCount(unsigned int * pctinfo)
-{
-    // We don't use a type library
-    *pctinfo = 0;
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::GetTypeInfo(unsigned int, unsigned long, ITypeInfo **pptinfo)
-{
-    // We don't use a type library
-    *pptinfo = 0;
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::GetIDsOfNames(const _GUID &, wchar_t **rgszNames, unsigned int, unsigned long, long *rgdispid)
-{
-#if !defined(Q_CC_BOR) && !defined(Q_CC_GNU)
-    // PROPERTIES:  Hierarchical
-    if (_bstr_t(rgszNames[0]) == _bstr_t(L"accParent"))
-        rgdispid[0] = DISPID_ACC_PARENT;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accChildCount"))
-        rgdispid[0] = DISPID_ACC_CHILDCOUNT;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accChild"))
-        rgdispid[0] = DISPID_ACC_CHILD;
-
-    // PROPERTIES:  Descriptional
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accName("))
-        rgdispid[0] = DISPID_ACC_NAME;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accValue"))
-        rgdispid[0] = DISPID_ACC_VALUE;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accDescription"))
-        rgdispid[0] = DISPID_ACC_DESCRIPTION;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accRole"))
-        rgdispid[0] = DISPID_ACC_ROLE;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accState"))
-        rgdispid[0] = DISPID_ACC_STATE;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accHelp"))
-        rgdispid[0] = DISPID_ACC_HELP;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accHelpTopic"))
-        rgdispid[0] = DISPID_ACC_HELPTOPIC;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accKeyboardShortcut"))
-        rgdispid[0] = DISPID_ACC_KEYBOARDSHORTCUT;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accFocus"))
-        rgdispid[0] = DISPID_ACC_FOCUS;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accSelection"))
-        rgdispid[0] = DISPID_ACC_SELECTION;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accDefaultAction"))
-        rgdispid[0] = DISPID_ACC_DEFAULTACTION;
-
-    // METHODS
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accSelect"))
-        rgdispid[0] = DISPID_ACC_SELECT;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accLocation"))
-        rgdispid[0] = DISPID_ACC_LOCATION;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accNavigate"))
-        rgdispid[0] = DISPID_ACC_NAVIGATE;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accHitTest"))
-        rgdispid[0] = DISPID_ACC_HITTEST;
-    else if(_bstr_t(rgszNames[0]) == _bstr_t(L"accDoDefaultAction"))
-        rgdispid[0] = DISPID_ACC_DODEFAULTACTION;
-    else
-        return DISP_E_UNKNOWNINTERFACE;
-
-    return S_OK;
-#else
-    Q_UNUSED(rgszNames);
-    Q_UNUSED(rgdispid);
-
-    return DISP_E_MEMBERNOTFOUND;
-#endif
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::Invoke(long dispIdMember, const _GUID &, unsigned long, unsigned short wFlags, tagDISPPARAMS *pDispParams, tagVARIANT *pVarResult, tagEXCEPINFO *, unsigned int *)
-{
-    HRESULT hr = DISP_E_MEMBERNOTFOUND;
-
-    switch(dispIdMember)
-    {
-        case DISPID_ACC_PARENT:
-            if (wFlags == DISPATCH_PROPERTYGET) {
-                if (!pVarResult)
-                    return E_INVALIDARG;
-                hr = get_accParent(&pVarResult->pdispVal);
-            } else {
-                hr = DISP_E_MEMBERNOTFOUND;
-            }
-            break;
-
-        case DISPID_ACC_CHILDCOUNT:
-            if (wFlags == DISPATCH_PROPERTYGET) {
-                if (!pVarResult)
-                    return E_INVALIDARG;
-                hr = get_accChildCount(&pVarResult->lVal);
-            } else {
-                hr = DISP_E_MEMBERNOTFOUND;
-            }
-            break;
-
-        case DISPID_ACC_CHILD:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accChild(pDispParams->rgvarg[0], &pVarResult->pdispVal);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_NAME:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accName(pDispParams->rgvarg[0], &pVarResult->bstrVal);
-            else if (wFlags == DISPATCH_PROPERTYPUT)
-                hr = put_accName(pDispParams->rgvarg[0], pVarResult->bstrVal);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_VALUE:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accValue(pDispParams->rgvarg[0], &pVarResult->bstrVal);
-            else if (wFlags == DISPATCH_PROPERTYPUT)
-                hr = put_accValue(pDispParams->rgvarg[0], pVarResult->bstrVal);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_DESCRIPTION:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accDescription(pDispParams->rgvarg[0], &pVarResult->bstrVal);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_ROLE:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accRole(pDispParams->rgvarg[0], pVarResult);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_STATE:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accState(pDispParams->rgvarg[0], pVarResult);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_HELP:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accHelp(pDispParams->rgvarg[0], &pVarResult->bstrVal);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_HELPTOPIC:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accHelpTopic(&pDispParams->rgvarg[2].bstrVal, pDispParams->rgvarg[1], &pDispParams->rgvarg[0].lVal);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_KEYBOARDSHORTCUT:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accKeyboardShortcut(pDispParams->rgvarg[0], &pVarResult->bstrVal);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_FOCUS:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accFocus(pVarResult);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_SELECTION:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accSelection(pVarResult);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_DEFAULTACTION:
-            if (wFlags == DISPATCH_PROPERTYGET)
-                hr = get_accDefaultAction(pDispParams->rgvarg[0], &pVarResult->bstrVal);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_SELECT:
-            if (wFlags == DISPATCH_METHOD)
-                hr = accSelect(pDispParams->rgvarg[1].lVal, pDispParams->rgvarg[0]);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_LOCATION:
-            if (wFlags == DISPATCH_METHOD)
-                hr = accLocation(&pDispParams->rgvarg[4].lVal, &pDispParams->rgvarg[3].lVal, &pDispParams->rgvarg[2].lVal, &pDispParams->rgvarg[1].lVal, pDispParams->rgvarg[0]);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_NAVIGATE:
-            if (wFlags == DISPATCH_METHOD)
-                hr = accNavigate(pDispParams->rgvarg[1].lVal, pDispParams->rgvarg[0], pVarResult);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_HITTEST:
-            if (wFlags == DISPATCH_METHOD)
-                hr = accHitTest(pDispParams->rgvarg[1].lVal, pDispParams->rgvarg[0].lVal, pVarResult);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        case DISPID_ACC_DODEFAULTACTION:
-            if (wFlags == DISPATCH_METHOD)
-                hr = accDoDefaultAction(pDispParams->rgvarg[0]);
-            else
-                hr = DISP_E_MEMBERNOTFOUND;
-            break;
-
-        default:
-            hr = DISP_E_MEMBERNOTFOUND;
-            break;
-    }
-
-    if (!SUCCEEDED(hr)) {
-        return hr;
-    }
-    return hr;
-}
-
-/*
-  IAccessible
-*/
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accHitTest(long xLeft, long yTop, VARIANT *pvarID)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    int control = accessible->childAt(xLeft, yTop);
-    if (control == -1) {
-        (*pvarID).vt = VT_EMPTY;
-        return S_FALSE;
-    }
-    QAccessibleInterface *acc = 0;
-    if (control)
-        accessible->navigate(Child, control, &acc);
-    if (!acc) {
-        (*pvarID).vt = VT_I4;
-        (*pvarID).lVal = control;
-        return S_OK;
-    }
-
-    QWindowsAccessible* wacc = new QWindowsAccessible(acc);
-    IDispatch *iface = 0;
-    wacc->QueryInterface(IID_IDispatch, (void**)&iface);
-    if (iface) {
-        (*pvarID).vt = VT_DISPATCH;
-        (*pvarID).pdispVal = iface;
-        return S_OK;
-    } else {
-        delete wacc;
-    }
-
-    (*pvarID).vt = VT_EMPTY;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accLocation(long *pxLeft, long *pyTop, long *pcxWidth, long *pcyHeight, VARIANT varID)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    QRect rect = elem.iface ? elem.iface->rect(elem.entry) : QRect();
-    if (rect.isValid()) {
-        *pxLeft = rect.x();
-        *pyTop = rect.y();
-        *pcxWidth = rect.width();
-        *pcyHeight = rect.height();
-    } else {
-        *pxLeft = 0;
-        *pyTop = 0;
-        *pcxWidth = 0;
-        *pcyHeight = 0;
-    }
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accNavigate(long navDir, VARIANT varStart, VARIANT *pvarEnd)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    QAccessibleInterface *acc = 0;
-    int control = -1;
-    switch(navDir) {
-    case NAVDIR_FIRSTCHILD:
-        control = accessible->navigate(Child, 1, &acc);
-        break;
-    case NAVDIR_LASTCHILD:
-        control = accessible->navigate(Child, accessible->childCount(), &acc);
-        break;
-    case NAVDIR_NEXT:
-    case NAVDIR_PREVIOUS:
-        if (!varStart.lVal){
-            QAccessibleInterface *parent = 0;
-            accessible->navigate(Ancestor, 1, &parent);
-            if (parent) {
-                int index = parent->indexOfChild(accessible);
-                index += (navDir == NAVDIR_NEXT) ? 1 : -1;
-                if (index > 0 && index <= parent->childCount())
-                    control = parent->navigate(Child, index, &acc);
-                delete parent;
-            }
-        } else {
-            int index = varStart.lVal;
-            index += (navDir == NAVDIR_NEXT) ? 1 : -1;
-            if (index > 0 && index <= accessible->childCount())
-                control = accessible->navigate(Child, index, &acc);
-        }
-        break;
-    case NAVDIR_UP:
-        control = accessible->navigate(Up, varStart.lVal, &acc);
-        break;
-    case NAVDIR_DOWN:
-        control = accessible->navigate(Down, varStart.lVal, &acc);
-        break;
-    case NAVDIR_LEFT:
-        control = accessible->navigate(Left, varStart.lVal, &acc);
-        break;
-    case NAVDIR_RIGHT:
-        control = accessible->navigate(Right, varStart.lVal, &acc);
-        break;
-    default:
-        break;
-    }
-    if (control == -1) {
-        (*pvarEnd).vt = VT_EMPTY;
-        return S_FALSE;
-    }
-    if (!acc) {
-        (*pvarEnd).vt = VT_I4;
-        (*pvarEnd).lVal = control;
-        return S_OK;
-    }
-
-    QWindowsAccessible* wacc = new QWindowsAccessible(acc);
-
-    IDispatch *iface = 0;
-    wacc->QueryInterface(IID_IDispatch, (void**)&iface);
-    if (iface) {
-        (*pvarEnd).vt = VT_DISPATCH;
-        (*pvarEnd).pdispVal = iface;
-        return S_OK;
-    } else {
-        delete wacc;
-    }
-
-    (*pvarEnd).vt = VT_EMPTY;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accChild(VARIANT varChildID, IDispatch** ppdispChild)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    if (varChildID.vt == VT_EMPTY)
-        return E_INVALIDARG;
-
-
-    int childIndex = varChildID.lVal;
-    QAccessibleInterface *acc = 0;
-
-    AccessibleElement elem(childIndex, accessible);
-    if (elem.iface) {
-        RelationFlag rel = elem.entry ? Child : Self;
-        int index = elem.iface->navigate(rel, elem.entry, &acc);
-        if (index == -1)
-            return E_INVALIDARG;
-    }
-
-    if (acc) {
-        QWindowsAccessible* wacc = new QWindowsAccessible(acc);
-        wacc->QueryInterface(IID_IDispatch, (void**)ppdispChild);
-        return S_OK;
-    }
-
-    *ppdispChild = 0;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accChildCount(long* pcountChildren)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    *pcountChildren = accessible->childCount();
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accParent(IDispatch** ppdispParent)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    QAccessibleInterface *acc = 0;
-    accessible->navigate(Ancestor, 1, &acc);
-    if (acc) {
-        QWindowsAccessible* wacc = new QWindowsAccessible(acc);
-        wacc->QueryInterface(IID_IDispatch, (void**)ppdispParent);
-
-        if (*ppdispParent)
-            return S_OK;
-    }
-
-    *ppdispParent = 0;
-    return S_FALSE;
-}
-
-/*
-  Properties and methods
-*/
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accDoDefaultAction(VARIANT varID)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    const bool res = elem.iface ? elem.iface->doAction(DefaultAction, elem.entry, QVariantList()) : false;
-    return res ? S_OK : S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accDefaultAction(VARIANT varID, BSTR* pszDefaultAction)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    QString def = elem.iface ? elem.iface->actionText(DefaultAction, Name, elem.entry) : QString();
-    if (def.isEmpty()) {
-        *pszDefaultAction = 0;
-        return S_FALSE;
-    }
-
-    *pszDefaultAction = QStringToBSTR(def);
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accDescription(VARIANT varID, BSTR* pszDescription)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    QString descr = elem.text(Description);
-    if (descr.size()) {
-        *pszDescription = QStringToBSTR(descr);
-        return S_OK;
-    }
-
-    *pszDescription = 0;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accHelp(VARIANT varID, BSTR *pszHelp)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    QString help = elem.text(Help);
-    if (help.size()) {
-        *pszHelp = QStringToBSTR(help);
-        return S_OK;
-    }
-
-    *pszHelp = 0;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accHelpTopic(BSTR *, VARIANT, long *)
-{
-    return DISP_E_MEMBERNOTFOUND;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accKeyboardShortcut(VARIANT varID, BSTR *pszKeyboardShortcut)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    QString sc = elem.text(Accelerator);
-    if (sc.size()) {
-        *pszKeyboardShortcut = QStringToBSTR(sc);
-        return S_OK;
-    }
-
-    *pszKeyboardShortcut = 0;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accName(VARIANT varID, BSTR* pszName)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    QString n = elem.text(Name);
-    if (n.size()) {
-        *pszName = QStringToBSTR(n);
-        return S_OK;
-    }
-
-    *pszName = 0;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::put_accName(VARIANT, BSTR)
-{
-    showDebug(__FUNCTION__, accessible);
-    return DISP_E_MEMBERNOTFOUND;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accRole(VARIANT varID, VARIANT *pvarRole)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    Role role = elem.iface ? elem.iface->role(elem.entry) : NoRole;
-    if (role != NoRole) {
-        if (role == LayeredPane)
-            role = QAccessible::Pane;
-        (*pvarRole).vt = VT_I4;
-        (*pvarRole).lVal = role;
-    } else {
-        (*pvarRole).vt = VT_EMPTY;
-    }
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accState(VARIANT varID, VARIANT *pvarState)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    (*pvarState).vt = VT_I4;
-    AccessibleElement elem(varID.lVal, accessible);
-    (*pvarState).lVal = elem.iface ? elem.iface->state(elem.entry) : State(Normal);
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accValue(VARIANT varID, BSTR* pszValue)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    QString value = elem.text(Value);
-    if (!value.isNull()) {
-        *pszValue = QStringToBSTR(value);
-        return S_OK;
-    }
-
-    *pszValue = 0;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::put_accValue(VARIANT, BSTR)
-{
-    showDebug(__FUNCTION__, accessible);
-    return DISP_E_MEMBERNOTFOUND;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::accSelect(long flagsSelect, VARIANT varID)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    bool res = false;
-
-    AccessibleElement elem(varID.lVal, accessible);
-    QAccessibleInterface *acc = elem.iface;
-    if (acc) {
-        const int entry = elem.entry;
-        if (flagsSelect & SELFLAG_TAKEFOCUS)
-            res = acc->doAction(SetFocus, entry, QVariantList());
-        if (flagsSelect & SELFLAG_TAKESELECTION) {
-            acc->doAction(ClearSelection, 0, QVariantList());   //### bug, 0 should be entry??
-            res = acc->doAction(AddToSelection, entry, QVariantList());
-        }
-        if (flagsSelect & SELFLAG_EXTENDSELECTION)
-            res = acc->doAction(ExtendSelection, entry, QVariantList());
-        if (flagsSelect & SELFLAG_ADDSELECTION)
-            res = acc->doAction(AddToSelection, entry, QVariantList());
-        if (flagsSelect & SELFLAG_REMOVESELECTION)
-            res = acc->doAction(RemoveSelection, entry, QVariantList());
-    }
-    return res ? S_OK : S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accFocus(VARIANT *pvarID)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    QAccessibleInterface *acc = 0;
-    int control = accessible->navigate(FocusChild, 1, &acc);
-    if (control == -1) {
-        (*pvarID).vt = VT_EMPTY;
-        return S_FALSE;
-    }
-    if (!acc || control == 0) {
-        (*pvarID).vt = VT_I4;
-        (*pvarID).lVal = control ? control : CHILDID_SELF;
-        return S_OK;
-    }
-
-    QWindowsAccessible* wacc = new QWindowsAccessible(acc);
-    IDispatch *iface = 0;
-    wacc->QueryInterface(IID_IDispatch, (void**)&iface);
-    if (iface) {
-        (*pvarID).vt = VT_DISPATCH;
-        (*pvarID).pdispVal = iface;
-        return S_OK;
-    } else {
-        delete wacc;
-    }
-
-    (*pvarID).vt = VT_EMPTY;
-    return S_FALSE;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::get_accSelection(VARIANT *pvarChildren)
-{
-    showDebug(__FUNCTION__, accessible);
-    if (!accessible->isValid())
-        return E_FAIL;
-
-    int cc = accessible->childCount();
-    QVector<int> sel(cc);
-    int selIndex = 0;
-    for (int i = 1; i <= cc; ++i) {
-        QAccessibleInterface *child = 0;
-        int i2 = accessible->navigate(Child, i, &child);
-        bool isSelected = false;
-        if (child) {
-            isSelected = child->state(0) & Selected;
-            delete child;
-            child = 0;
-        } else {
-            isSelected = accessible->state(i2) & Selected;
-        }
-        if (isSelected)
-            sel[selIndex++] = i;
-    }
-    sel.resize(selIndex);
-    if (sel.isEmpty()) {
-        (*pvarChildren).vt = VT_EMPTY;
-        return S_FALSE;
-    }
-    if (sel.size() == 1) {
-        (*pvarChildren).vt = VT_I4;
-        (*pvarChildren).lVal = sel[0];
-        return S_OK;
-    }
-    IEnumVARIANT *iface = new QWindowsEnumerate(sel);
-    IUnknown *uiface;
-    iface->QueryInterface(IID_IUnknown, (void**)&uiface);
-    (*pvarChildren).vt = VT_UNKNOWN;
-    (*pvarChildren).punkVal = uiface;
-
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::GetWindow(HWND *phwnd)
-{
-    *phwnd = 0;
-    if (!accessible->isValid())
-        return E_UNEXPECTED;
-
-    QObject *o = accessible->object();
-    if (!o || !o->isWidgetType())
-        return E_FAIL;
-
-    *phwnd = static_cast<QWidget*>(o)->effectiveWinId();
-    return S_OK;
-}
-
-HRESULT STDMETHODCALLTYPE QWindowsAccessible::ContextSensitiveHelp(BOOL)
-{
-    return S_OK;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_ACCESSIBILITY
diff --git a/src/gui/dialogs/qcolordialog_mac.mm b/src/gui/dialogs/qcolordialog_mac.mm
deleted file mode 100644 (file)
index b7e26ac..0000000
+++ /dev/null
@@ -1,510 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qcolordialog_p.h"
-#if !defined(QT_NO_COLORDIALOG) && defined(Q_WS_MAC)
-#include <qapplication.h>
-#include <qtimer.h>
-#include <qdialogbuttonbox.h>
-#include <qabstracteventdispatcher.h>
-#include <qapplication_p.h>
-#include <qt_mac_p.h>
-#include <qdebug.h>
-#import <AppKit/AppKit.h>
-#import <Foundation/Foundation.h>
-
-#if !CGFLOAT_DEFINED
-typedef float CGFloat;  // Should only not be defined on 32-bit platforms
-#endif
-
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-@protocol NSWindowDelegate <NSObject>
-- (void)windowDidResize:(NSNotification *)notification;
-- (BOOL)windowShouldClose:(id)window;
-@end
-#endif
-
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate);
-
-@interface QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) : NSObject<NSWindowDelegate> {
-    NSColorPanel *mColorPanel;
-    NSView *mStolenContentView;
-    NSButton *mOkButton;
-    NSButton *mCancelButton;
-    QColorDialogPrivate *mPriv;
-    QColor *mQtColor;
-    CGFloat mMinWidth;  // currently unused
-    CGFloat mExtraHeight;   // currently unused
-    BOOL mHackedPanel;
-    NSInteger mResultCode;
-    BOOL mDialogIsExecuting;
-    BOOL mResultSet;
-}
-- (id)initWithColorPanel:(NSColorPanel *)panel
-       stolenContentView:(NSView *)stolenContentView
-                okButton:(NSButton *)okButton
-            cancelButton:(NSButton *)cancelButton
-                    priv:(QColorDialogPrivate *)priv;
-- (void)colorChanged:(NSNotification *)notification;
-- (void)relayout;
-- (void)onOkClicked;
-- (void)onCancelClicked;
-- (void)updateQtColor;
-- (NSColorPanel *)colorPanel;
-- (QColor)qtColor;
-- (void)finishOffWithCode:(NSInteger)result;
-- (void)showColorPanel;
-- (void)exec;
-- (void)setResultSet:(BOOL)result;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate)
-- (id)initWithColorPanel:(NSColorPanel *)panel
-       stolenContentView:(NSView *)stolenContentView
-                okButton:(NSButton *)okButton
-            cancelButton:(NSButton *)cancelButton
-                    priv:(QColorDialogPrivate *)priv
-{
-    self = [super init];
-
-    mColorPanel = panel;
-    mStolenContentView = stolenContentView;
-    mOkButton = okButton;
-    mCancelButton = cancelButton;
-    mPriv = priv;
-    mMinWidth = 0.0;
-    mExtraHeight = 0.0;
-    mHackedPanel = (okButton != 0);
-    mResultCode = NSCancelButton;
-    mDialogIsExecuting = false;
-    mResultSet = false;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7)
-        [mColorPanel setRestorable:NO];
-#endif
-
-    if (mHackedPanel) {
-        [self relayout];
-
-        [okButton setAction:@selector(onOkClicked)];
-        [okButton setTarget:self];
-
-        [cancelButton setAction:@selector(onCancelClicked)];
-        [cancelButton setTarget:self];
-    }
-
-    [[NSNotificationCenter defaultCenter] addObserver:self
-        selector:@selector(colorChanged:)
-        name:NSColorPanelColorDidChangeNotification
-        object:mColorPanel];
-
-    mQtColor = new QColor();
-    return self;
-}
-
-- (void)dealloc
-{
-    QMacCocoaAutoReleasePool pool;
-    if (mHackedPanel) {
-        NSView *ourContentView = [mColorPanel contentView];
-
-        // return stolen stuff to its rightful owner
-        [mStolenContentView removeFromSuperview];
-        [mColorPanel setContentView:mStolenContentView];
-
-        [mOkButton release];
-        [mCancelButton release];
-        [ourContentView release];
-    }
-    [mColorPanel setDelegate:nil];
-    [[NSNotificationCenter defaultCenter] removeObserver:self];
-    delete mQtColor;
-    [super dealloc];
-}
-
-- (void)setResultSet:(BOOL)result
-{
-    mResultSet = result;
-}
-
-- (BOOL)windowShouldClose:(id)window
-{
-    Q_UNUSED(window);
-    if (!mHackedPanel)
-        [self updateQtColor];
-    if (mDialogIsExecuting) {
-        [self finishOffWithCode:NSCancelButton];
-    } else {
-        mResultSet = true;
-        mPriv->colorDialog()->reject();
-    }
-    return true;
-}
-
-- (void)windowDidResize:(NSNotification *)notification
-{
-    Q_UNUSED(notification);
-    if (mHackedPanel)
-        [self relayout];
-}
-
-- (void)colorChanged:(NSNotification *)notification
-{
-    Q_UNUSED(notification);
-    [self updateQtColor];
-}
-
-- (void)relayout
-{
-    Q_ASSERT(mHackedPanel);
-
-    NSRect rect = [[mStolenContentView superview] frame];
-
-    // should a priori be kept in sync with qfontdialog_mac.mm
-    const CGFloat ButtonMinWidth = 78.0; // 84.0 for Carbon
-    const CGFloat ButtonMinHeight = 32.0;
-    const CGFloat ButtonSpacing = 0.0;
-    const CGFloat ButtonTopMargin = 0.0;
-    const CGFloat ButtonBottomMargin = 7.0;
-    const CGFloat ButtonSideMargin = 9.0;
-
-    [mOkButton sizeToFit];
-    NSSize okSizeHint = [mOkButton frame].size;
-
-    [mCancelButton sizeToFit];
-    NSSize cancelSizeHint = [mCancelButton frame].size;
-
-    const CGFloat ButtonWidth = qMin(qMax(ButtonMinWidth,
-                                          qMax(okSizeHint.width, cancelSizeHint.width)),
-                                     CGFloat((rect.size.width - 2.0 * ButtonSideMargin - ButtonSpacing) * 0.5));
-    const CGFloat ButtonHeight = qMax(ButtonMinHeight,
-                                     qMax(okSizeHint.height, cancelSizeHint.height));
-
-    NSRect okRect = { { rect.size.width - ButtonSideMargin - ButtonWidth,
-                        ButtonBottomMargin },
-                      { ButtonWidth, ButtonHeight } };
-    [mOkButton setFrame:okRect];
-    [mOkButton setNeedsDisplay:YES];
-
-    NSRect cancelRect = { { okRect.origin.x - ButtonSpacing - ButtonWidth,
-                            ButtonBottomMargin },
-                            { ButtonWidth, ButtonHeight } };
-    [mCancelButton setFrame:cancelRect];
-    [mCancelButton setNeedsDisplay:YES];
-
-    const CGFloat Y = ButtonBottomMargin + ButtonHeight + ButtonTopMargin;
-    NSRect stolenCVRect = { { 0.0, Y },
-                            { rect.size.width, rect.size.height - Y } };
-    [mStolenContentView setFrame:stolenCVRect];
-    [mStolenContentView setNeedsDisplay:YES];
-
-    [[mStolenContentView superview] setNeedsDisplay:YES];
-    mMinWidth = 2 * ButtonSideMargin + ButtonSpacing + 2 * ButtonWidth;
-    mExtraHeight = Y;
-}
-
-- (void)onOkClicked
-{
-    Q_ASSERT(mHackedPanel);
-    [[mStolenContentView window] close];
-    [self updateQtColor];
-    [self finishOffWithCode:NSOKButton];
-}
-
-- (void)onCancelClicked
-{
-    if (mHackedPanel) {
-        [[mStolenContentView window] close];
-        delete mQtColor;
-        mQtColor = new QColor();
-        [self finishOffWithCode:NSCancelButton];
-    }
-}
-
-- (void)updateQtColor
-{
-    delete mQtColor;
-    mQtColor = new QColor();
-    NSColor *color = [mColorPanel color];
-    NSString *colorSpaceName = [color colorSpaceName];
-    if (colorSpaceName == NSDeviceCMYKColorSpace) {
-        CGFloat cyan = 0, magenta = 0, yellow = 0, black = 0, alpha = 0;
-        [color getCyan:&cyan magenta:&magenta yellow:&yellow black:&black alpha:&alpha];
-        mQtColor->setCmykF(cyan, magenta, yellow, black, alpha);
-    } else if (colorSpaceName == NSCalibratedRGBColorSpace || colorSpaceName == NSDeviceRGBColorSpace)  {
-        CGFloat red = 0, green = 0, blue = 0, alpha = 0;
-        [color getRed:&red green:&green blue:&blue alpha:&alpha];
-        mQtColor->setRgbF(red, green, blue, alpha);
-    } else if (colorSpaceName == NSNamedColorSpace) {
-        NSColor *tmpColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
-        CGFloat red = 0, green = 0, blue = 0, alpha = 0;
-        [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
-        mQtColor->setRgbF(red, green, blue, alpha);
-    } else {
-        NSColorSpace *colorSpace = [color colorSpace];
-        if ([colorSpace colorSpaceModel] == NSCMYKColorSpaceModel && [color numberOfComponents] == 5){
-            CGFloat components[5];
-            [color getComponents:components];
-            mQtColor->setCmykF(components[0], components[1], components[2], components[3], components[4]);
-        } else {
-            NSColor *tmpColor = [color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
-            CGFloat red = 0, green = 0, blue = 0, alpha = 0;
-            [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
-            mQtColor->setRgbF(red, green, blue, alpha);
-        }
-    }
-
-    mPriv->setCurrentQColor(*mQtColor);
-}
-
-- (NSColorPanel *)colorPanel
-{
-    return mColorPanel;
-}
-
-- (QColor)qtColor
-{
-    return *mQtColor;
-}
-
-- (void)finishOffWithCode:(NSInteger)code
-{
-    mResultCode = code;
-    if (mDialogIsExecuting) {
-        // We stop the current modal event loop. The control
-        // will then return inside -(void)exec below.
-        // It's important that the modal event loop is stopped before
-        // we accept/reject QColorDialog, since QColorDialog has its
-        // own event loop that needs to be stopped last. 
-        [[NSApplication sharedApplication] stopModalWithCode:code];
-    } else {
-        // Since we are not in a modal event loop, we can safely close
-        // down QColorDialog
-        // Calling accept() or reject() can in turn call closeCocoaColorPanel.
-        // This check will prevent any such recursion.
-        if (!mResultSet) {
-            mResultSet = true;
-            if (mResultCode == NSCancelButton) {
-                mPriv->colorDialog()->reject();
-            } else {
-                mPriv->colorDialog()->accept();
-            }
-        } 
-    }
-}
-
-- (void)showColorPanel
-{
-    mDialogIsExecuting = false;
-    [mColorPanel makeKeyAndOrderFront:mColorPanel];
-}
-
-- (void)exec
-{
-    QBoolBlocker nativeDialogOnTop(QApplicationPrivate::native_modal_dialog_active);
-    QMacCocoaAutoReleasePool pool;
-    mDialogIsExecuting = true;
-    bool modalEnded = false;
-    while (!modalEnded) {
-#ifndef QT_NO_EXCEPTIONS
-        @try {
-            [[NSApplication sharedApplication] runModalForWindow:mColorPanel];
-            modalEnded = true;
-        } @catch (NSException *) {
-            // For some reason, NSColorPanel throws an exception when
-            // clicking on 'SelectedMenuItemColor' from the 'Developer'
-            // palette (tab three).
-        }
-#else
-        [[NSApplication sharedApplication] runModalForWindow:mColorPanel];
-        modalEnded = true;
-#endif
-    }
-
-    QAbstractEventDispatcher::instance()->interrupt();
-    if (mResultCode == NSCancelButton)
-        mPriv->colorDialog()->reject();
-    else
-        mPriv->colorDialog()->accept();
-}
-
-@end
-
-QT_BEGIN_NAMESPACE
-
-extern void macStartInterceptNSPanelCtor();
-extern void macStopInterceptNSPanelCtor();
-extern NSButton *macCreateButton(const char *text, NSView *superview);
-
-void QColorDialogPrivate::openCocoaColorPanel(const QColor &initial,
-        QWidget *parent, const QString &title, QColorDialog::ColorDialogOptions options)
-{
-    Q_UNUSED(parent);   // we would use the parent if only NSColorPanel could be a sheet
-    QMacCocoaAutoReleasePool pool;
-
-    if (!delegate) {
-        /*
-           The standard Cocoa color panel has no OK or Cancel button and
-           is created as a utility window, whereas we want something like
-           the Carbon color panel. We need to take the following steps:
-
-           1. Intercept the color panel constructor to turn off the
-           NSUtilityWindowMask flag. This is done by temporarily
-           replacing initWithContentRect:styleMask:backing:defer:
-           in NSPanel by our own method.
-
-           2. Modify the color panel so that its content view is part
-           of a new content view that contains it as well as two
-           buttons (OK and Cancel).
-
-           3. Lay out the original content view and the buttons when
-           the color panel is shown and whenever it is resized.
-
-           4. Clean up after ourselves.
-         */
-
-        bool hackColorPanel = !(options & QColorDialog::NoButtons);
-
-        if (hackColorPanel)
-            macStartInterceptNSPanelCtor();
-        NSColorPanel *colorPanel = [NSColorPanel sharedColorPanel];
-        if (hackColorPanel)
-            macStopInterceptNSPanelCtor();
-
-        [colorPanel setHidesOnDeactivate:false];
-
-        // set up the Cocoa color panel
-        [colorPanel setShowsAlpha:options & QColorDialog::ShowAlphaChannel];
-        [colorPanel setTitle:(NSString*)(CFStringRef)QCFString(title)];
-
-        NSView *stolenContentView = 0;
-        NSButton *okButton = 0;
-        NSButton *cancelButton = 0;
-
-        if (hackColorPanel) {
-            // steal the color panel's contents view
-            stolenContentView = [colorPanel contentView];
-            [stolenContentView retain];
-            [colorPanel setContentView:0];
-
-            // create a new content view and add the stolen one as a subview
-            NSRect frameRect = { { 0.0, 0.0 }, { 0.0, 0.0 } };
-            NSView *ourContentView = [[NSView alloc] initWithFrame:frameRect];
-            [ourContentView addSubview:stolenContentView];
-
-            // create OK and Cancel buttons and add these as subviews
-            okButton = macCreateButton("&OK", ourContentView);
-            cancelButton = macCreateButton("Cancel", ourContentView);
-
-            [colorPanel setContentView:ourContentView];
-            [colorPanel setDefaultButtonCell:[okButton cell]];
-        }
-
-        delegate = [[QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) alloc] initWithColorPanel:colorPanel
-            stolenContentView:stolenContentView
-            okButton:okButton
-            cancelButton:cancelButton
-            priv:this];
-        [colorPanel setDelegate:static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate)];
-    }
-    [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) setResultSet:NO];
-    setCocoaPanelColor(initial);
-    [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) showColorPanel];
-}
-
-void QColorDialogPrivate::closeCocoaColorPanel()
-{
-    [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) onCancelClicked];
-}
-
-void QColorDialogPrivate::releaseCocoaColorPanelDelegate()
-{
-    [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) release];
-}
-
-void QColorDialogPrivate::mac_nativeDialogModalHelp()
-{
-    // Do a queued meta-call to open the native modal dialog so it opens after the new
-    // event loop has started to execute (in QDialog::exec). Using a timer rather than
-    // a queued meta call is intentional to ensure that the call is only delivered when
-    // [NSApplication run] runs (timers are handeled special in cocoa). If NSApplication is not
-    // running (which is the case if e.g a top-most QEventLoop has been
-    // interrupted, and the second-most event loop has not yet been reactivated (regardless
-    // if [NSApplication run] is still on the stack)), showing a native modal dialog will fail.
-    if (delegate){
-        Q_Q(QColorDialog);
-        QTimer::singleShot(1, q, SLOT(_q_macRunNativeAppModalPanel()));
-    }
-}
-
-void QColorDialogPrivate::_q_macRunNativeAppModalPanel()
-{
-    [static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate) exec];
-}
-
-void QColorDialogPrivate::setCocoaPanelColor(const QColor &color)
-{
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *theDelegate = static_cast<QT_MANGLE_NAMESPACE(QCocoaColorPanelDelegate) *>(delegate);
-    NSColor *nsColor;
-    const QColor::Spec spec = color.spec();
-    if (spec == QColor::Cmyk) {
-        nsColor = [NSColor colorWithDeviceCyan:color.cyanF()
-                                       magenta:color.magentaF()
-                                        yellow:color.yellowF()
-                                         black:color.blackF()
-                                         alpha:color.alphaF()];
-    } else {
-        nsColor = [NSColor colorWithCalibratedRed:color.redF()
-                                            green:color.greenF()
-                                             blue:color.blueF()
-                                            alpha:color.alphaF()];
-    }
-    [[theDelegate colorPanel] setColor:nsColor];
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qfiledialog_mac.mm b/src/gui/dialogs/qfiledialog_mac.mm
deleted file mode 100644 (file)
index 2fbdaaa..0000000
+++ /dev/null
@@ -1,1206 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfiledialog.h"
-
-#ifndef QT_NO_FILEDIALOG
-
-/*****************************************************************************
-  QFileDialog debug facilities
- *****************************************************************************/
-//#define DEBUG_FILEDIALOG_FILTERS
-
-#include <qapplication.h>
-#include <qapplication_p.h>
-#include <qfiledialog_p.h>
-#include <qt_mac_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qregexp.h>
-#include <qbuffer.h>
-#include <qdebug.h>
-#include <qstringlist.h>
-#include <qaction.h>
-#include <qtextcodec.h>
-#include <qdesktopwidget.h>
-#include <stdlib.h>
-#include <qabstracteventdispatcher.h>
-#import <AppKit/NSSavePanel.h>
-#include "ui_qfiledialog.h"
-
-QT_BEGIN_NAMESPACE
-
-extern QStringList qt_make_filter_list(const QString &filter); // qfiledialog.cpp
-extern QStringList qt_clean_filter_list(const QString &filter); // qfiledialog.cpp
-extern const char *qt_file_dialog_filter_reg_exp; // qfiledialog.cpp
-extern bool qt_mac_is_macsheet(const QWidget *w); // qwidget_mac.mm
-
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QFileDialogPrivate)
-QT_FORWARD_DECLARE_CLASS(QString)
-QT_FORWARD_DECLARE_CLASS(QStringList)
-QT_FORWARD_DECLARE_CLASS(QWidget)
-QT_FORWARD_DECLARE_CLASS(QAction)
-QT_FORWARD_DECLARE_CLASS(QFileInfo)
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate);
-
-@interface QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate)
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-    : NSObject<NSOpenSavePanelDelegate>
-#else
-    : NSObject
-#endif
-{
-    @public
-    NSOpenPanel *mOpenPanel;
-    NSSavePanel *mSavePanel;
-    NSView *mAccessoryView;
-    NSPopUpButton *mPopUpButton;
-    NSTextField *mTextField;
-    QFileDialogPrivate *mPriv;
-    NSString *mCurrentDir;
-    bool mConfirmOverwrite;
-    int mReturnCode;
-
-    QT_PREPEND_NAMESPACE(QFileDialog::AcceptMode) mAcceptMode;
-    QT_PREPEND_NAMESPACE(QDir::Filters) *mQDirFilter;
-    QT_PREPEND_NAMESPACE(QFileDialog::FileMode) mFileMode;
-    QT_PREPEND_NAMESPACE(QFileDialog::Options) *mFileOptions;
-
-    QString *mLastFilterCheckPath;
-    QString *mCurrentSelection;
-    QStringList *mQDirFilterEntryList;
-    QStringList *mNameFilterDropDownList;
-    QStringList *mSelectedNameFilter;
-}
-
-- (NSString *)strip:(const QString &)label;
-- (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename;
-- (void)filterChanged:(id)sender;
-- (void)showModelessPanel;
-- (BOOL)runApplicationModalPanel;
-- (void)showWindowModalSheet:(QWidget *)docWidget;
-- (void)updateProperties;
-- (QStringList)acceptableExtensionsForSave;
-- (QString)removeExtensions:(const QString &)filter;
-- (void)createTextField;
-- (void)createPopUpButton:(const QString &)selectedFilter hideDetails:(BOOL)hideDetails;
-- (QStringList)findStrippedFilterWithVisualFilterName:(QString)name;
-- (void)createAccessory;
-
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate)
-
-- (id)initWithAcceptMode:(QT_PREPEND_NAMESPACE(QFileDialog::AcceptMode))acceptMode
-    title:(const QString &)title
-    hideNameFilterDetails:(bool)hideNameFilterDetails
-    qDirFilter:(QT_PREPEND_NAMESPACE(QDir::Filters))qDirFilter
-    fileOptions:(QT_PREPEND_NAMESPACE(QFileDialog::Options))fileOptions
-    fileMode:(QT_PREPEND_NAMESPACE(QFileDialog::FileMode))fileMode
-    selectFile:(const QString &)selectFile
-    confirmOverwrite:(bool)confirm
-    priv:(QFileDialogPrivate *)priv
-{
-    self = [super init];
-
-    mAcceptMode = acceptMode;
-    if (mAcceptMode == QT_PREPEND_NAMESPACE(QFileDialog::AcceptOpen)){
-        mOpenPanel = [NSOpenPanel openPanel];
-        mSavePanel = mOpenPanel;
-    } else {
-        mSavePanel = [NSSavePanel savePanel];
-        mOpenPanel = 0;
-    }
-
-    if ([mSavePanel respondsToSelector:@selector(setLevel:)])
-        [mSavePanel setLevel:NSModalPanelWindowLevel];
-    [mSavePanel setDelegate:self];
-    mQDirFilter = new QT_PREPEND_NAMESPACE(QDir::Filters)(qDirFilter);
-    mFileOptions = new QT_PREPEND_NAMESPACE(QFileDialog::Options)(fileOptions);
-    mFileMode = fileMode;
-    mConfirmOverwrite = confirm;
-    mReturnCode = -1;
-    mPriv = priv;
-    mLastFilterCheckPath = new QString;
-    mQDirFilterEntryList = new QStringList;
-    mNameFilterDropDownList = new QStringList(priv->nameFilters);
-    QString selectedVisualNameFilter = priv->qFileDialogUi->fileTypeCombo->currentText();
-    mSelectedNameFilter = new QStringList([self findStrippedFilterWithVisualFilterName:selectedVisualNameFilter]);
-
-    QFileInfo sel(selectFile);
-    if (sel.isDir() && !sel.isBundle()){
-        mCurrentDir = [qt_mac_QStringToNSString(sel.absoluteFilePath()) retain];
-        mCurrentSelection = new QString;
-    } else {
-        mCurrentDir = [qt_mac_QStringToNSString(sel.absolutePath()) retain];
-        mCurrentSelection = new QString(sel.absoluteFilePath());
-    }
-
-    [mSavePanel setTitle:qt_mac_QStringToNSString(title)];
-    [self createPopUpButton:selectedVisualNameFilter hideDetails:hideNameFilterDetails];
-    [self createTextField];
-    [self createAccessory];
-    [mSavePanel setAccessoryView:mNameFilterDropDownList->size() > 1 ? mAccessoryView : nil];
-
-    if (mPriv){
-        [mSavePanel setPrompt:[self strip:mPriv->acceptLabel]];
-        if (mPriv->fileNameLabelExplicitlySat)
-            [mSavePanel setNameFieldLabel:[self strip:mPriv->qFileDialogUi->fileNameLabel->text()]];
-    }
-
-    [self updateProperties];
-    [mSavePanel retain];
-    return self;
-}
-
-- (void)dealloc
-{
-    delete mQDirFilter;
-    delete mFileOptions;
-    delete mLastFilterCheckPath;
-    delete mQDirFilterEntryList;
-    delete mNameFilterDropDownList;
-    delete mSelectedNameFilter;
-    delete mCurrentSelection;
-
-    if ([mSavePanel respondsToSelector:@selector(orderOut:)])
-        [mSavePanel orderOut:mSavePanel];
-    [mSavePanel setAccessoryView:nil];
-    [mPopUpButton release];
-    [mTextField release];
-    [mAccessoryView release];
-    [mSavePanel setDelegate:nil];
-    [mSavePanel release];
-    [mCurrentDir release];
-    [super dealloc];
-}
-
-- (NSString *)strip:(const QString &)label
-{
-    QAction a(label, 0);
-    return qt_mac_QStringToNSString(a.iconText());
-}
-
-- (void)closePanel
-{
-    *mCurrentSelection = QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)([mSavePanel filename]);
-    if ([mSavePanel respondsToSelector:@selector(close)])
-        [mSavePanel close];
-    if ([mSavePanel isSheet])
-        [[NSApplication sharedApplication] endSheet: mSavePanel];
-}
-
-- (void)showModelessPanel
-{
-    if (mOpenPanel){
-        QFileInfo info(*mCurrentSelection);
-        NSString *filename = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.fileName());
-        NSString *filepath = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.filePath());
-        bool selectable = (mAcceptMode == QFileDialog::AcceptSave)
-            || [self panel:nil shouldShowFilename:filepath];
-        [mOpenPanel 
-            beginForDirectory:mCurrentDir
-            file:selectable ? filename : nil
-            types:nil
-            modelessDelegate:self
-            didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
-            contextInfo:nil];
-    }
-}
-
-- (BOOL)runApplicationModalPanel
-{
-    QFileInfo info(*mCurrentSelection);
-    NSString *filename = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.fileName());
-    NSString *filepath = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.filePath());
-    bool selectable = (mAcceptMode == QFileDialog::AcceptSave)
-        || [self panel:nil shouldShowFilename:filepath];
-    mReturnCode = [mSavePanel 
-        runModalForDirectory:mCurrentDir
-        file:selectable ? filename : @"untitled"];
-
-    QAbstractEventDispatcher::instance()->interrupt();
-    return (mReturnCode == NSOKButton);
-}
-
-- (QT_PREPEND_NAMESPACE(QDialog::DialogCode))dialogResultCode
-{
-    return (mReturnCode == NSOKButton) ? QT_PREPEND_NAMESPACE(QDialog::Accepted) : QT_PREPEND_NAMESPACE(QDialog::Rejected);
-}
-
-- (void)showWindowModalSheet:(QWidget *)docWidget
-{
-    Q_UNUSED(docWidget);
-    QFileInfo info(*mCurrentSelection);
-    NSString *filename = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.fileName());
-    NSString *filepath = QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(info.filePath());
-    bool selectable = (mAcceptMode == QFileDialog::AcceptSave)
-        || [self panel:nil shouldShowFilename:filepath];
-    [mSavePanel 
-        beginSheetForDirectory:mCurrentDir
-        file:selectable ? filename : nil
-#ifdef QT_MAC_USE_COCOA
-        modalForWindow:QT_PREPEND_NAMESPACE(qt_mac_window_for)(docWidget)
-#else
-        modalForWindow:nil
-#endif
-        modalDelegate:self
-        didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:)
-        contextInfo:nil];
-}
-
-- (BOOL)isHiddenFile:(NSString *)filename isDir:(BOOL)isDir
-{
-#ifdef QT_MAC_USE_COCOA
-    CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)filename, kCFURLPOSIXPathStyle, isDir);
-    CFBooleanRef isHidden;
-    Boolean errorOrHidden = false;
-    if (!CFURLCopyResourcePropertyForKey(url, kCFURLIsHiddenKey, &isHidden, NULL)) {
-        errorOrHidden = true;
-    } else {
-        if (CFBooleanGetValue(isHidden))
-            errorOrHidden = true;
-        CFRelease(isHidden);
-    }
-    CFRelease(url);
-    return errorOrHidden;
-#else
-    Q_UNUSED(filename);
-    Q_UNUSED(isDir);
-    return false;
-#endif
-}
-
-- (BOOL)panel:(id)sender shouldShowFilename:(NSString *)filename
-{
-    Q_UNUSED(sender);
-
-    if ([filename length] == 0)
-        return NO;
-
-    // Always accept directories regardless of their names (unless it is a bundle):
-    NSFileManager *fm = [NSFileManager defaultManager];
-    NSDictionary *fileAttrs = [fm attributesOfItemAtPath:filename error:nil];
-    if (!fileAttrs)
-        return NO; // Error accessing the file means 'no'.
-    NSString *fileType = [fileAttrs fileType];
-    bool isDir = [fileType isEqualToString:NSFileTypeDirectory];
-    if (isDir) {
-        if ([mSavePanel treatsFilePackagesAsDirectories] == NO) {
-            if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:filename] == NO)
-                return YES;
-        }
-    }
-
-    QString qtFileName
-        = QFileInfo(QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)(filename)).fileName();
-    // No filter means accept everything
-    bool nameMatches = mSelectedNameFilter->isEmpty();
-    // Check if the current file name filter accepts the file:
-    for (int i = 0; !nameMatches && i < mSelectedNameFilter->size(); ++i) {
-        if (QDir::match(mSelectedNameFilter->at(i), qtFileName))
-            nameMatches = true;
-    }
-    if (!nameMatches)
-        return NO;
-
-    QDir::Filters filter = *mQDirFilter;
-    if ((!(filter & (QDir::Dirs | QDir::AllDirs)) && isDir)
-        || (!(filter & QDir::Files) && [fileType isEqualToString:NSFileTypeRegular])
-        || ((filter & QDir::NoSymLinks) && [fileType isEqualToString:NSFileTypeSymbolicLink]))
-        return NO;
-
-    bool filterPermissions = ((filter & QDir::PermissionMask)
-                              && (filter & QDir::PermissionMask) != QDir::PermissionMask);
-    if (filterPermissions) {
-        if ((!(filter & QDir::Readable) && [fm isReadableFileAtPath:filename])
-            || (!(filter & QDir::Writable) && [fm isWritableFileAtPath:filename])
-            || (!(filter & QDir::Executable) && [fm isExecutableFileAtPath:filename]))
-            return NO;
-    }
-    if (!(filter & QDir::Hidden)
-        && (qtFileName.startsWith(QLatin1Char('.')) || [self isHiddenFile:filename isDir:isDir]))
-            return NO;
-
-    return YES;
-}
-
-- (NSString *)panel:(id)sender userEnteredFilename:(NSString *)filename confirmed:(BOOL)okFlag
-{
-    Q_UNUSED(sender);
-    if (!okFlag)
-        return filename;
-    if (mConfirmOverwrite)
-        return filename;
-
-    // User has clicked save, and no overwrite confirmation should occur.
-    // To get the latter, we need to change the name we return (hence the prefix):
-    return [@"___qt_very_unlikely_prefix_" stringByAppendingString:filename];
-}
-
-- (void)setNameFilters:(const QStringList &)filters hideDetails:(BOOL)hideDetails
-{
-    [mPopUpButton removeAllItems];
-    *mNameFilterDropDownList = filters;
-    if (filters.size() > 0){
-        for (int i=0; i<filters.size(); ++i) {
-            QString filter = hideDetails ? [self removeExtensions:filters.at(i)] : filters.at(i);
-            [mPopUpButton addItemWithTitle:QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(filter)];
-        }
-        [mPopUpButton selectItemAtIndex:0];
-        [mSavePanel setAccessoryView:mAccessoryView];
-    } else
-        [mSavePanel setAccessoryView:nil];
-
-    [self filterChanged:self];
-}
-
-- (void)filterChanged:(id)sender
-{
-    // This mDelegate function is called when the _name_ filter changes.
-    Q_UNUSED(sender);
-    QString selection = mNameFilterDropDownList->value([mPopUpButton indexOfSelectedItem]);
-    *mSelectedNameFilter = [self findStrippedFilterWithVisualFilterName:selection];
-    if ([mSavePanel respondsToSelector:@selector(validateVisibleColumns)])
-        [mSavePanel validateVisibleColumns];
-    [self updateProperties];
-    if (mPriv)
-        mPriv->QNSOpenSavePanelDelegate_filterSelected([mPopUpButton indexOfSelectedItem]);
-}
-
-- (QString)currentNameFilter
-{
-    return mNameFilterDropDownList->value([mPopUpButton indexOfSelectedItem]);
-}
-
-- (QStringList)selectedFiles
-{
-    if (mOpenPanel)
-        return QT_PREPEND_NAMESPACE(qt_mac_NSArrayToQStringList)([mOpenPanel filenames]);
-    else{
-        QStringList result;
-        QString filename = QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)([mSavePanel filename]);
-        result << filename.remove(QLatin1String("___qt_very_unlikely_prefix_"));
-        return result;
-    }
-}
-
-- (void)updateProperties
-{
-    // Call this functions if mFileMode, mFileOptions,
-    // mNameFilterDropDownList or mQDirFilter changes.
-    // The savepanel does not contain the neccessary functions for this.
-    bool chooseFilesOnly = mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::ExistingFile)
-        || mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::ExistingFiles);
-    bool chooseDirsOnly = mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::Directory)
-        || mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::DirectoryOnly)
-        || *mFileOptions & QT_PREPEND_NAMESPACE(QFileDialog::ShowDirsOnly);
-
-    [mOpenPanel setCanChooseFiles:!chooseDirsOnly];
-    [mOpenPanel setCanChooseDirectories:!chooseFilesOnly];
-    [mSavePanel setCanCreateDirectories:!(*mFileOptions & QT_PREPEND_NAMESPACE(QFileDialog::ReadOnly))];
-    [mOpenPanel setAllowsMultipleSelection:(mFileMode == QT_PREPEND_NAMESPACE(QFileDialog::ExistingFiles))];
-    [mOpenPanel setResolvesAliases:!(*mFileOptions & QT_PREPEND_NAMESPACE(QFileDialog::DontResolveSymlinks))];
-
-    QStringList ext = [self acceptableExtensionsForSave];
-    if (mPriv && !ext.isEmpty() && !mPriv->defaultSuffix.isEmpty())
-        ext.prepend(mPriv->defaultSuffix);
-    [mSavePanel setAllowedFileTypes:ext.isEmpty() ? nil : QT_PREPEND_NAMESPACE(qt_mac_QStringListToNSMutableArray(ext))];
-
-    if ([mSavePanel respondsToSelector:@selector(isVisible)] && [mSavePanel isVisible])
-    {
-        if ([mOpenPanel respondsToSelector:@selector(validateVisibleColumns)])
-            [mOpenPanel validateVisibleColumns];
-    }
-}
-
-- (void)panelSelectionDidChange:(id)sender
-{
-    Q_UNUSED(sender);
-    if (mPriv && [mSavePanel isVisible]) {
-        QString selection = QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString([mSavePanel filename]));
-        if (selection != mCurrentSelection) {
-            *mCurrentSelection = selection;
-            mPriv->QNSOpenSavePanelDelegate_selectionChanged(selection);
-        }
-    }
-}
-
-- (void)openPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode  contextInfo:(void *)contextInfo
-{
-    Q_UNUSED(panel);
-    Q_UNUSED(contextInfo);
-    mReturnCode = returnCode;
-    if (mPriv)
-        mPriv->QNSOpenSavePanelDelegate_panelClosed(returnCode == NSOKButton);
-}
-
-- (void)panel:(id)sender directoryDidChange:(NSString *)path
-{
-    Q_UNUSED(sender);
-    if (!mPriv)
-        return;
-    if ([path isEqualToString:mCurrentDir])
-        return;
-
-    if ([mSavePanel respondsToSelector:@selector(isVisible)] && ![mSavePanel isVisible])
-        return;
-    [mCurrentDir release];
-    mCurrentDir = [path retain];
-    mPriv->QNSOpenSavePanelDelegate_directoryEntered(QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString(mCurrentDir)));
-}
-
-/*
-    Returns a list of extensions (e.g. "png", "jpg", "gif")
-    for the current name filter. If a filter do not conform
-    to the format *.xyz or * or *.*, an empty list
-    is returned meaning accept everything.
-*/
-- (QStringList)acceptableExtensionsForSave
-{
-    QStringList result;
-    for (int i=0; i<mSelectedNameFilter->count(); ++i) {
-        const QString &filter = mSelectedNameFilter->at(i);
-        if (filter.startsWith(QLatin1String("*."))
-                && !filter.contains(QLatin1Char('?'))
-                && filter.count(QLatin1Char('*')) == 1) {
-            result += filter.mid(2);
-        } else {
-            return QStringList(); // Accept everything
-        }
-    }
-    return result;
-}
-
-- (QString)removeExtensions:(const QString &)filter
-{
-    QRegExp regExp(QT_PREPEND_NAMESPACE(QString::fromLatin1)(QT_PREPEND_NAMESPACE(qt_file_dialog_filter_reg_exp)));
-    if (regExp.indexIn(filter) != -1)
-        return regExp.cap(1).trimmed();
-    return filter;
-}
-
-- (void)createTextField
-{
-    NSRect textRect = { { 0.0, 3.0 }, { 100.0, 25.0 } };
-    mTextField = [[NSTextField alloc] initWithFrame:textRect];
-    [[mTextField cell] setFont:[NSFont systemFontOfSize:
-            [NSFont systemFontSizeForControlSize:NSRegularControlSize]]];
-    [mTextField setAlignment:NSRightTextAlignment];
-    [mTextField setEditable:false];
-    [mTextField setSelectable:false];
-    [mTextField setBordered:false];
-    [mTextField setDrawsBackground:false];
-    if (mPriv){
-        [mTextField setStringValue:[self strip:mPriv->qFileDialogUi->fileTypeLabel->text()]];
-    } else
-        [mTextField setStringValue:QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(QT_PREPEND_NAMESPACE(QFileDialog::tr)("Files of type:"))];
-}
-
-- (void)createPopUpButton:(const QString &)selectedFilter hideDetails:(BOOL)hideDetails
-{
-    NSRect popUpRect = { { 100.0, 5.0 }, { 250.0, 25.0 } };
-    mPopUpButton = [[NSPopUpButton alloc] initWithFrame:popUpRect pullsDown:NO];
-    [mPopUpButton setTarget:self];
-    [mPopUpButton setAction:@selector(filterChanged:)];
-
-    if (mNameFilterDropDownList->size() > 0) {
-        int filterToUse = -1;
-        for (int i=0; i<mNameFilterDropDownList->size(); ++i) {
-            QString currentFilter = mNameFilterDropDownList->at(i);
-            if (selectedFilter == currentFilter ||
-                (filterToUse == -1 && currentFilter.startsWith(selectedFilter)))
-                filterToUse = i;
-            QString filter = hideDetails ? [self removeExtensions:currentFilter] : currentFilter;
-            [mPopUpButton addItemWithTitle:QT_PREPEND_NAMESPACE(qt_mac_QStringToNSString)(filter)];
-        }
-        if (filterToUse != -1)
-            [mPopUpButton selectItemAtIndex:filterToUse];
-    }
-}
-
-- (QStringList) findStrippedFilterWithVisualFilterName:(QString)name
-{
-    for (int i=0; i<mNameFilterDropDownList->size(); ++i) {
-        if (mNameFilterDropDownList->at(i).startsWith(name))
-            return qt_clean_filter_list(mNameFilterDropDownList->at(i));
-    }
-    return QStringList();
-}
-
-- (void)createAccessory
-{
-    NSRect accessoryRect = { { 0.0, 0.0 }, { 450.0, 33.0 } };
-    mAccessoryView = [[NSView alloc] initWithFrame:accessoryRect];
-    [mAccessoryView addSubview:mTextField];
-    [mAccessoryView addSubview:mPopUpButton];
-}
-
-@end
-
-QT_BEGIN_NAMESPACE
-
-void QFileDialogPrivate::QNSOpenSavePanelDelegate_selectionChanged(const QString &newPath)
-{
-    emit q_func()->currentChanged(newPath);
-}
-
-void QFileDialogPrivate::QNSOpenSavePanelDelegate_panelClosed(bool accepted)
-{
-    if (accepted)
-        q_func()->accept();
-    else
-        q_func()->reject();
-}
-
-void QFileDialogPrivate::QNSOpenSavePanelDelegate_directoryEntered(const QString &newDir)
-{
-    setLastVisitedDirectory(newDir);
-    emit q_func()->directoryEntered(newDir);
-}
-
-void QFileDialogPrivate::QNSOpenSavePanelDelegate_filterSelected(int menuIndex)
-{
-    emit q_func()->filterSelected(nameFilters.at(menuIndex));
-}
-
-void QFileDialogPrivate::setDirectory_sys(const QString &directory)
-{
-#ifndef QT_MAC_USE_COCOA
-    if (directory == mCurrentLocation)
-        return;
-    mCurrentLocation = directory;
-    emit q_func()->directoryEntered(mCurrentLocation);
-
-    FSRef fsRef;
-    if (qt_mac_create_fsref(directory, &fsRef) == noErr) {
-        AEDesc desc;
-        if (AECreateDesc(typeFSRef, &fsRef, sizeof(FSRef), &desc) == noErr)
-            NavCustomControl(mDialog, kNavCtlSetLocation, (void*)&desc);
-    }
-#else
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    [delegate->mSavePanel setDirectory:qt_mac_QStringToNSString(directory)];
-#endif
-}
-
-QString QFileDialogPrivate::directory_sys() const
-{
-#ifndef QT_MAC_USE_COCOA
-    return mCurrentLocation;
-#else
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    return qt_mac_NSStringToQString([delegate->mSavePanel directory]);
-#endif
-}
-
-void QFileDialogPrivate::selectFile_sys(const QString &filename)
-{
-    QString filePath = filename;
-    if (QDir::isRelativePath(filePath))
-        filePath = QFileInfo(directory_sys(), filePath).filePath();
-
-#ifndef QT_MAC_USE_COCOA
-    // Update the selection list immidiatly, so
-    // subsequent calls to selectedFiles() gets correct:
-    mCurrentSelectionList.clear();
-    mCurrentSelectionList << filename;
-    if (mCurrentSelection != filename){
-        mCurrentSelection = filename;
-        emit q_func()->currentChanged(mCurrentSelection);
-    }
-
-    AEDescList descList;
-    if (AECreateList(0, 0, false, &descList) != noErr)
-        return;
-
-    FSRef fsRef;
-    if (qt_mac_create_fsref(filePath, &fsRef) == noErr) {
-        AEDesc desc;
-        if (AECreateDesc(typeFSRef, &fsRef, sizeof(FSRef), &desc) == noErr){
-            if (AEPutDesc(&descList, 0, &desc) == noErr)
-                NavCustomControl(mDialog, kNavCtlSetSelection, (void*)&descList);
-        }
-    }
-
-    // Type the file name into the save dialog's text field:
-    UInt8 *strBuffer = (UInt8 *)malloc(1024);
-    qt_mac_to_pascal_string(QFileInfo(filename).fileName(), strBuffer);
-    NavCustomControl(mDialog, kNavCtlSetEditFileName, strBuffer);
-    free(strBuffer);
-#else
-    // There seems to no way to select a file once the dialog is running.
-    // So do the next best thing, set the file's directory:
-    setDirectory_sys(QFileInfo(filePath).absolutePath());
-#endif
-}
-
-QStringList QFileDialogPrivate::selectedFiles_sys() const
-{
-#ifndef QT_MAC_USE_COCOA
-    if (q_func()->acceptMode() == QFileDialog::AcceptOpen){
-        return mCurrentSelectionList;
-    } else {
-        return QStringList() << mCurrentLocation + QLatin1Char('/')
-                                + QCFString::toQString(NavDialogGetSaveFileName(mDialog));
-    }
-#else
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    return [delegate selectedFiles];
-#endif
-}
-
-void QFileDialogPrivate::setNameFilters_sys(const QStringList &filters)
-{
-#ifndef QT_MAC_USE_COCOA
-    Q_UNUSED(filters);
-#else
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    bool hideDetails = q_func()->testOption(QFileDialog::HideNameFilterDetails);
-    [delegate setNameFilters:filters hideDetails:hideDetails];
-#endif
-}
-
-void QFileDialogPrivate::setFilter_sys()
-{
-#ifndef QT_MAC_USE_COCOA
-#else
-    Q_Q(QFileDialog);
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    *(delegate->mQDirFilter) = model->filter();
-    delegate->mFileMode = fileMode;
-    [delegate->mSavePanel setTitle:qt_mac_QStringToNSString(q->windowTitle())];
-    [delegate->mSavePanel setPrompt:[delegate strip:acceptLabel]];
-    if (fileNameLabelExplicitlySat)
-        [delegate->mSavePanel setNameFieldLabel:[delegate strip:qFileDialogUi->fileNameLabel->text()]];
-
-    [delegate updateProperties];
-#endif
-}
-
-void QFileDialogPrivate::selectNameFilter_sys(const QString &filter)
-{
-    int index = nameFilters.indexOf(filter);
-    if (index != -1) {
-#ifndef QT_MAC_USE_COCOA
-        NavMenuItemSpec navSpec;
-        bzero(&navSpec, sizeof(NavMenuItemSpec));
-        navSpec.menuType = index;
-        NavCustomControl(mDialog, kNavCtlSelectCustomType, &navSpec);
-#else
-        QMacCocoaAutoReleasePool pool;
-        QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-        [delegate->mPopUpButton selectItemAtIndex:index];
-        [delegate filterChanged:nil];
-#endif
-    }
-}
-
-QString QFileDialogPrivate::selectedNameFilter_sys() const
-{
-#ifndef QT_MAC_USE_COCOA
-    int index = filterInfo.currentSelection;
-#else
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    int index = [delegate->mPopUpButton indexOfSelectedItem];
-#endif
-    return index != -1 ? nameFilters.at(index) : QString();
-}
-
-void QFileDialogPrivate::deleteNativeDialog_sys()
-{
-#ifndef QT_MAC_USE_COCOA
-    if (mDialog)
-        NavDialogDispose(mDialog);
-    mDialog = 0;
-    mDialogStarted = false;
-#else
-    QMacCocoaAutoReleasePool pool;
-    [reinterpret_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate) release];
-    mDelegate = 0;
-#endif
-    nativeDialogInUse = false;
-}
-
-bool QFileDialogPrivate::setVisible_sys(bool visible)
-{
-    Q_Q(QFileDialog);
-    if (!visible == q->isHidden())
-        return false;
-
-    if (q->windowFlags() & Qt::WindowStaysOnTopHint) {
-        // The native file dialog tries all it can to stay
-        // on the NSModalPanel level. And it might also show
-        // its own "create directory" dialog that we cannot control.
-        // So we need to use the non-native version in this case...
-        return false;
-    }
-
-#ifndef QT_MAC_USE_COCOA
-    return visible ? showCarbonNavServicesDialog() : hideCarbonNavServicesDialog();
-#else
-    return visible ? showCocoaFilePanel() : hideCocoaFilePanel();
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-Boolean QFileDialogPrivate::qt_mac_filedialog_filter_proc(AEDesc *theItem, void *info,
-                                                                 void *data, NavFilterModes)
-{
-    QFileDialogPrivate *fileDialogPrivate = static_cast<QFileDialogPrivate *>(data);
-
-    if (!fileDialogPrivate || fileDialogPrivate->filterInfo.filters.isEmpty()
-        || (fileDialogPrivate->filterInfo.currentSelection < 0
-                && fileDialogPrivate->filterInfo.currentSelection
-                        >= fileDialogPrivate->filterInfo.filters.size()))
-        return true;
-
-    NavFileOrFolderInfo *theInfo = static_cast<NavFileOrFolderInfo *>(info);
-    QString file;
-    QString path;
-    const QtMacFilterName &fn
-           = fileDialogPrivate->filterInfo.filters.at(fileDialogPrivate->filterInfo.currentSelection);
-    if (theItem->descriptorType == typeFSRef) {
-        FSRef ref;
-        AEGetDescData(theItem, &ref, sizeof(ref));
-        UInt8 str_buffer[1024];
-        FSRefMakePath(&ref, str_buffer, 1024);
-        path = QString::fromUtf8(reinterpret_cast<const char *>(str_buffer));
-        int slsh = path.lastIndexOf(QLatin1Char('/'));
-        if (slsh != -1)
-            file = path.right(path.length() - slsh - 1);
-        else
-            file = path;
-    }
-    QStringList reg = fn.regexp.split(QLatin1String(";"));
-    for (QStringList::const_iterator it = reg.constBegin(); it != reg.constEnd(); ++it) {
-        QRegExp rg(*it, Qt::CaseInsensitive, QRegExp::Wildcard);
-#ifdef DEBUG_FILEDIALOG_FILTERS
-        qDebug("QFileDialogPrivate::qt_mac_filedialog_filter_proc:%d, asked to filter.. %s (%s)", __LINE__,
-                qPrintable(file), qPrintable(*it));
-#endif
-        if (rg.exactMatch(file))
-            return true;
-    }
-
-    if (theInfo->isFolder) {
-        if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath:qt_mac_QStringToNSString(path)])
-            return false;
-        return true;
-    }
-    return false;
-}
-
-void QFileDialogPrivate::qt_mac_filedialog_event_proc(const NavEventCallbackMessage msg,
-        NavCBRecPtr p, NavCallBackUserData data)
-{
-    QFileDialogPrivate *fileDialogPrivate = static_cast<QFileDialogPrivate *>(data);
-
-    switch(msg) {
-    case kNavCBPopupMenuSelect: {
-        NavMenuItemSpec *s = static_cast<NavMenuItemSpec *>(p->eventData.eventDataParms.param);
-        if (int(s->menuType) != fileDialogPrivate->filterInfo.currentSelection) {
-            fileDialogPrivate->filterInfo.currentSelection = s->menuType;
-            emit fileDialogPrivate->q_func()->filterSelected(fileDialogPrivate->nameFilters.at(s->menuType));
-        }
-        if (fileDialogPrivate->acceptMode == QFileDialog::AcceptSave) {
-            QString base = QCFString::toQString(NavDialogGetSaveFileName(p->context));
-            QFileInfo fi(base);
-            base = fi.completeBaseName();
-            const QtMacFilterName &fn = fileDialogPrivate->filterInfo.filters.at(
-                                                       fileDialogPrivate->filterInfo.currentSelection);
-            QStringList reg = fn.regexp.split(QLatin1String(";"), QString::SkipEmptyParts);
-            if (reg.count()) {
-                QString r = reg.first();
-                r  = r.right(r.length()-1);      // Strip the *
-                base += r;                        //"." + QString::number(s->menuType);
-            }
-            NavDialogSetSaveFileName(p->context, QCFString::toCFStringRef(base));
-        }
-#ifdef DEBUG_FILEDIALOG_FILTERS
-        qDebug("QFileDialogPrivate::qt_mac_filedialog_event_proc:%d - Selected a filter: %ld", __LINE__, s->menuType);
-#endif
-        break; }
-    case kNavCBStart:{
-        fileDialogPrivate->mDialogStarted = true;
-        // Set selected file:
-        QModelIndexList indexes = fileDialogPrivate->qFileDialogUi->listView->selectionModel()->selectedRows();
-        QString selected;
-        if (!indexes.isEmpty())
-            selected = indexes.at(0).data(QFileSystemModel::FilePathRole).toString();
-        else
-            selected = fileDialogPrivate->typedFiles().value(0);
-        fileDialogPrivate->selectFile_sys(selected);
-        fileDialogPrivate->selectNameFilter_sys(fileDialogPrivate->qFileDialogUi->fileTypeCombo->currentText());
-        break; }
-    case kNavCBSelectEntry:{
-        // Event: Current selection has changed.
-        QStringList prevSelectionList = fileDialogPrivate->mCurrentSelectionList;
-        fileDialogPrivate->mCurrentSelectionList.clear();
-        QString fileNameToEmit;
-
-        AEDescList *descList = (AEDescList *)p->eventData.eventDataParms.param;
-        // Get the number of files selected:
-        UInt8 strBuffer[1024];
-        long count;
-        OSErr err = AECountItems(descList, &count);
-        if (err != noErr || !count)
-            break;
-
-        for (long index=1; index<=count; ++index) {
-            FSRef ref;
-            err = AEGetNthPtr(descList, index, typeFSRef, 0, 0, &ref, sizeof(ref), 0);
-            if (err != noErr)
-                break;
-            FSRefMakePath(&ref, strBuffer, 1024);
-            QString selected = QString::fromUtf8((const char *)strBuffer);
-            fileDialogPrivate->mCurrentSelectionList << selected;
-            if (!prevSelectionList.contains(selected))
-                fileNameToEmit = selected;
-        }
-
-        if (!fileNameToEmit.isEmpty() && fileNameToEmit != fileDialogPrivate->mCurrentSelection)
-            emit fileDialogPrivate->q_func()->currentChanged(fileNameToEmit);
-        fileDialogPrivate->mCurrentSelection = fileNameToEmit;
-        break; }
-    case kNavCBShowDesktop:
-    case kNavCBNewLocation:{
-        // Event: Current directory has changed.
-        AEDesc *desc = (AEDesc *)p->eventData.eventDataParms.param;
-        FSRef ref;
-        AEGetDescData(desc, &ref, sizeof(ref));
-        UInt8 *strBuffer = (UInt8 *)malloc(1024);
-        FSRefMakePath(&ref, strBuffer, 1024);
-        QString newLocation = QString::fromUtf8((const char *)strBuffer);
-        free(strBuffer);
-        if (fileDialogPrivate->mCurrentLocation != newLocation){
-            fileDialogPrivate->mCurrentLocation = newLocation;
-            QFileDialog::FileMode mode = fileDialogPrivate->fileMode;
-            if (mode == QFileDialog::AnyFile || mode == QFileDialog::ExistingFile
-                    || mode == QFileDialog::ExistingFiles){
-                // When changing directory, the current selection is cleared if
-                // we are supposed to be selecting files only:
-                if (!fileDialogPrivate->mCurrentSelection.isEmpty()){
-                    fileDialogPrivate->mCurrentSelectionList.clear();
-                    fileDialogPrivate->mCurrentSelection.clear();
-                    emit fileDialogPrivate->q_func()->currentChanged(fileDialogPrivate->mCurrentSelection);
-                }
-            }
-            fileDialogPrivate->setLastVisitedDirectory(newLocation);
-            emit fileDialogPrivate->q_func()->directoryEntered(newLocation);
-        }
-        break; }
-    case kNavCBAccept:
-        fileDialogPrivate->mDialogClosed = true;
-        fileDialogPrivate->q_func()->accept();
-        break;
-    case kNavCBCancel:
-        fileDialogPrivate->mDialogClosed = true;
-        fileDialogPrivate->q_func()->reject();
-        break;
-    }
-}
-
-static QFileDialogPrivate::QtMacFilterName qt_mac_extract_filter(const QString &rawFilter, bool showDetails)
-{
-    QFileDialogPrivate::QtMacFilterName ret;
-    ret.filter = rawFilter;
-    QString result = rawFilter;
-    QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
-    int index = r.indexIn(result);
-    if (index >= 0)
-        result = r.cap(2);
-
-    if (showDetails) {
-        ret.description = rawFilter;
-    } else {
-        if (index >= 0)
-            ret.description = r.cap(1).trimmed();
-        if (ret.description.isEmpty())
-            ret.description = result;
-    }
-    ret.regexp = result.replace(QLatin1Char(' '), QLatin1Char(';'));
-    return ret;
-}
-
-static QList<QFileDialogPrivate::QtMacFilterName> qt_mac_make_filters_list(const QString &filter, bool showDetails)
-{
-#ifdef DEBUG_FILEDIALOG_FILTERS
-    qDebug("QFileDialog:%d - Got filter (%s)", __LINE__, filter.latin1());
-#endif
-
-    QList<QFileDialogPrivate::QtMacFilterName> ret;
-    QString f(filter);
-    if (f.isEmpty())
-        f = QFileDialog::tr("All Files (*)");
-    if (f.isEmpty())
-        return ret;
-    QStringList filts = qt_make_filter_list(f);
-    for (QStringList::const_iterator it = filts.constBegin(); it != filts.constEnd(); ++it) {
-        QFileDialogPrivate::QtMacFilterName filter = qt_mac_extract_filter(*it, showDetails);
-#ifdef DEBUG_FILEDIALOG_FILTERS
-        qDebug("QFileDialog:%d Split out filter (%d) '%s' '%s' [%s]", __LINE__, ret.count(),
-                filter->regxp.latin1(), filter->description.latin1(), (*it).latin1());
-#endif
-        ret.append(filter);
-    }
-    return ret;
-}
-
-void QFileDialogPrivate::createNavServicesDialog()
-{
-    Q_Q(QFileDialog);
-    if (mDialog)
-        deleteNativeDialog_sys();
-
-    NavDialogCreationOptions navOptions;
-    NavGetDefaultDialogCreationOptions(&navOptions);
-
-    // Translate QFileDialog settings into NavDialog options:
-    if (qt_mac_is_macsheet(q)) {
-        navOptions.modality = kWindowModalityWindowModal;
-        navOptions.parentWindow = qt_mac_window_for(q->parentWidget());
-    } else if (q->windowModality() ==  Qt::ApplicationModal)
-        navOptions.modality = kWindowModalityAppModal;
-    else
-        navOptions.modality = kWindowModalityNone;
-    navOptions.optionFlags |= kNavSupportPackages;
-    if (q->testOption(QFileDialog::DontConfirmOverwrite))
-        navOptions.optionFlags |= kNavDontConfirmReplacement;
-    if (fileMode != QFileDialog::ExistingFiles)
-        navOptions.optionFlags &= ~kNavAllowMultipleFiles;
-
-    navOptions.windowTitle = QCFString::toCFStringRef(q->windowTitle());
-
-    navOptions.location.h = -1;
-    navOptions.location.v = -1;
-
-    QWidget *parent = q->parentWidget();
-    if (parent && parent->isVisible()) {
-        WindowClass wclass;
-        GetWindowClass(qt_mac_window_for(parent), &wclass);
-        parent = parent->window();
-        QString s = parent->windowTitle();
-        navOptions.clientName = QCFString::toCFStringRef(s);
-    }
-
-    filterInfo.currentSelection = 0;
-    filterInfo.filters = qt_mac_make_filters_list(nameFilters.join(QLatin1String(";;")), q->isNameFilterDetailsVisible());
-    QCFType<CFArrayRef> filterArray;
-    if (filterInfo.filters.size() > 1) {
-        int i = 0;
-        CFStringRef *cfstringArray = static_cast<CFStringRef *>(malloc(sizeof(CFStringRef)
-                                                                   * filterInfo.filters.size()));
-        for (i = 0; i < filterInfo.filters.size(); ++i) {
-            cfstringArray[i] = QCFString::toCFStringRef(filterInfo.filters.at(i).description);
-        }
-        filterArray = CFArrayCreate(kCFAllocatorDefault,
-                        reinterpret_cast<const void **>(cfstringArray), filterInfo.filters.size(),
-                        &kCFTypeArrayCallBacks);
-        navOptions.popupExtension = filterArray;
-        free(cfstringArray);
-    }
-
-    if (q->acceptMode() == QFileDialog::AcceptSave) {
-        if (NavCreatePutFileDialog(&navOptions, 'cute', kNavGenericSignature,
-                    QFileDialogPrivate::qt_mac_filedialog_event_proc, this, &mDialog)) {
-            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
-            return;
-        }
-    } else if (fileMode == QFileDialog::DirectoryOnly || fileMode == QFileDialog::Directory) {
-        if (NavCreateChooseFolderDialog(&navOptions,
-                    QFileDialogPrivate::qt_mac_filedialog_event_proc, 0, this, &mDialog)) {
-            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
-            return;
-        }
-    } else {
-        if (NavCreateGetFileDialog(&navOptions, 0,
-                    QFileDialogPrivate::qt_mac_filedialog_event_proc, 0,
-                    QFileDialogPrivate::qt_mac_filedialog_filter_proc, this, &mDialog)) {
-            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
-            return;
-        }
-    }
-
-    // Set start-up directory:
-    if (mCurrentLocation.isEmpty())
-        mCurrentLocation = rootPath();
-    FSRef fsRef;
-    if (qt_mac_create_fsref(mCurrentLocation, &fsRef) == noErr) {
-        AEDesc desc;
-        if (AECreateDesc(typeFSRef, &fsRef, sizeof(FSRef), &desc) == noErr)
-            NavCustomControl(mDialog, kNavCtlSetLocation, (void*)&desc);
-    }
-}
-
-bool QFileDialogPrivate::showCarbonNavServicesDialog()
-{
-    Q_Q(QFileDialog);
-    if (q->acceptMode() == QFileDialog::AcceptSave && q->windowModality() == Qt::NonModal)
-        return false; // cannot do native no-modal save dialogs.
-    createNavServicesDialog();
-    mDialogClosed = false;
-    if (q->windowModality() != Qt::ApplicationModal)
-        NavDialogRun(mDialog);
-    return true;
-}
-
-bool QFileDialogPrivate::hideCarbonNavServicesDialog()
-{
-    if (!mDialogClosed){
-        mDialogClosed = true;
-        NavCustomControl(mDialog, kNavCtlCancel, 0);
-    }
-    return true;
-}
-
-#else // Cocoa
-
-void QFileDialogPrivate::createNSOpenSavePanelDelegate()
-{
-    Q_Q(QFileDialog);
-    if (mDelegate)
-        return;
-
-    bool selectDir = q->selectedFiles().isEmpty();
-    QString selection(selectDir ? q->directory().absolutePath() : q->selectedFiles().value(0));
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = [[QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) alloc]
-        initWithAcceptMode:acceptMode
-        title:q->windowTitle()
-        hideNameFilterDetails:q->testOption(QFileDialog::HideNameFilterDetails)
-        qDirFilter:model->filter()
-        fileOptions:opts
-        fileMode:fileMode
-        selectFile:selection
-        confirmOverwrite:!q->testOption(QFileDialog::DontConfirmOverwrite)
-        priv:this];
-
-    mDelegate = delegate;
-}
-
-bool QFileDialogPrivate::showCocoaFilePanel()
-{
-    Q_Q(QFileDialog);
-    QMacCocoaAutoReleasePool pool;
-    createNSOpenSavePanelDelegate();
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    if (qt_mac_is_macsheet(q))
-        [delegate showWindowModalSheet:q->parentWidget()];
-    else if (!q->testAttribute(Qt::WA_ShowModal))
-        [delegate showModelessPanel];
-    return true;
-}
-
-bool QFileDialogPrivate::hideCocoaFilePanel()
-{
-    if (!mDelegate){
-        // Nothing to do. We return false to leave the question
-        // open regarding whether or not to go native:
-        return false;
-    } else {
-        QMacCocoaAutoReleasePool pool;
-        QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-        [delegate closePanel];
-        // Even when we hide it, we are still using a
-        // native dialog, so return true:
-        return true;
-    }
-}
-
-#endif
-
-void QFileDialogPrivate::mac_nativeDialogModalHelp()
-{
-    // Do a queued meta-call to open the native modal dialog so it opens after the new
-    // event loop has started to execute (in QDialog::exec). Using a timer rather than
-    // a queued meta call is intentional to ensure that the call is only delivered when
-    // [NSApplication run] runs (timers are handeled special in cocoa). If NSApplication is not
-    // running (which is the case if e.g a top-most QEventLoop has been
-    // interrupted, and the second-most event loop has not yet been reactivated (regardless
-    // if [NSApplication run] is still on the stack)), showing a native modal dialog will fail.
-    if (nativeDialogInUse){
-        Q_Q(QFileDialog);
-        QTimer::singleShot(1, q, SLOT(_q_macRunNativeAppModalPanel()));
-    }
-}
-
-void QFileDialogPrivate::_q_macRunNativeAppModalPanel()
-{
-    QBoolBlocker nativeDialogOnTop(QApplicationPrivate::native_modal_dialog_active);
-#ifndef QT_MAC_USE_COCOA
-    NavDialogRun(mDialog);
-#else
-    Q_Q(QFileDialog);
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    [delegate runApplicationModalPanel];
-    dialogResultCode_sys() == QDialog::Accepted ? q->accept() : q->reject();
-#endif
-}
-
-QDialog::DialogCode QFileDialogPrivate::dialogResultCode_sys()
-{
-#ifndef QT_MAC_USE_COCOA
-    NavUserAction result = NavDialogGetUserAction(mDialog);
-    if (result == kNavUserActionCancel || result == kNavUserActionNone)
-        return QDialog::Rejected;
-    else
-        return QDialog::Accepted;
-#else
-    QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *delegate = static_cast<QT_MANGLE_NAMESPACE(QNSOpenSavePanelDelegate) *>(mDelegate);
-    return [delegate dialogResultCode];
-#endif
-}
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_FILEDIALOG
-
diff --git a/src/gui/dialogs/qfiledialog_win.cpp b/src/gui/dialogs/qfiledialog_win.cpp
deleted file mode 100644 (file)
index 4fcc4e7..0000000
+++ /dev/null
@@ -1,809 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfiledialog.h"
-
-#ifndef QT_NO_FILEDIALOG
-
-#include <qfiledialog_p.h>
-#include <qapplication.h>
-#include <qapplication_p.h>
-#include <qt_windows.h>
-#include <qglobal.h>
-#include <qregexp.h>
-#include <qbuffer.h>
-#include <qdir.h>
-#include <qstringlist.h>
-#include <qsystemlibrary_p.h>
-#include "qfiledialog_win_p.h"
-
-#ifdef Q_WS_WINCE
-#include <commdlg.h>
-bool qt_priv_ptr_valid = false;
-#else
-//we have to declare them here because they're not present for all SDK/compilers
-static const IID   QT_IID_IFileOpenDialog  = {0xd57c7288, 0xd4ad, 0x4768, {0xbe, 0x02, 0x9d, 0x96, 0x95, 0x32, 0xd9, 0x60} };
-static const IID   QT_IID_IShellItem       = {0x43826d1e, 0xe718, 0x42ee, {0xbc, 0x55, 0xa1, 0xe2, 0x61, 0xc3, 0x7b, 0xfe} };
-static const CLSID QT_CLSID_FileOpenDialog = {0xdc1c5a9c, 0xe88a, 0x4dde, {0xa5, 0xa1, 0x60, 0xf8, 0x2a, 0x20, 0xae, 0xf7} };
-#endif
-
-
-typedef qt_LPITEMIDLIST (WINAPI *PtrSHBrowseForFolder)(qt_BROWSEINFO*);
-static PtrSHBrowseForFolder ptrSHBrowseForFolder = 0;
-typedef BOOL (WINAPI *PtrSHGetPathFromIDList)(qt_LPITEMIDLIST, LPWSTR);
-static PtrSHGetPathFromIDList ptrSHGetPathFromIDList = 0;
-typedef HRESULT (WINAPI *PtrSHGetMalloc)(LPMALLOC *);
-static PtrSHGetMalloc ptrSHGetMalloc = 0;
-
-
-QT_BEGIN_NAMESPACE
-
-static void qt_win_resolve_libs()
-{
-    static bool triedResolve = false;
-    if (!triedResolve) {
-#if !defined(Q_WS_WINCE)
-        QSystemLibrary lib(QLatin1String("shell32"));
-        ptrSHBrowseForFolder = (PtrSHBrowseForFolder)lib.resolve("SHBrowseForFolderW");
-        ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList)lib.resolve("SHGetPathFromIDListW");
-        ptrSHGetMalloc = (PtrSHGetMalloc)lib.resolve("SHGetMalloc");
-#else
-        // CE stores them in a different lib and does not use unicode version
-        QSystemLibrary lib(QLatin1String("Ceshell"));
-        ptrSHBrowseForFolder = (PtrSHBrowseForFolder)lib.resolve("SHBrowseForFolder");
-        ptrSHGetPathFromIDList = (PtrSHGetPathFromIDList)lib.resolve("SHGetPathFromIDList");
-        ptrSHGetMalloc = (PtrSHGetMalloc)lib.resolve("SHGetMalloc");
-        if (ptrSHBrowseForFolder && ptrSHGetPathFromIDList && ptrSHGetMalloc)
-            qt_priv_ptr_valid = true;
-#endif
-
-        triedResolve = true;
-    }
-}
-
-extern const char* qt_file_dialog_filter_reg_exp; // defined in qfiledialog.cpp
-extern QStringList qt_make_filter_list(const QString &filter);
-
-const int maxNameLen = 1023;
-const int maxMultiLen = 65535;
-
-// Returns the wildcard part of a filter.
-static QString qt_win_extract_filter(const QString &rawFilter)
-{
-    QString result = rawFilter;
-    QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
-    int index = r.indexIn(result);
-    if (index >= 0)
-        result = r.cap(2);
-    QStringList list = result.split(QLatin1Char(' '));
-    for(QStringList::iterator it = list.begin(); it < list.end(); ++it) {
-        if (*it == QLatin1String("*")) {
-            *it = QLatin1String("*.*");
-            break;
-        }
-    }
-    return list.join(QLatin1String(";"));
-}
-
-static QStringList qt_win_make_filters_list(const QString &filter)
-{
-    QString f(filter);
-
-    if (f.isEmpty())
-        f = QFileDialog::tr("All Files (*.*)");
-
-    return qt_make_filter_list(f);
-}
-
-// Makes a NUL-oriented Windows filter from a Qt filter.
-static QString qt_win_filter(const QString &filter, bool hideFiltersDetails)
-{
-    QStringList filterLst = qt_win_make_filters_list(filter);
-    QStringList::Iterator it = filterLst.begin();
-    QString winfilters;
-    QRegExp r(QString::fromLatin1(qt_file_dialog_filter_reg_exp));
-    for (; it != filterLst.end(); ++it) {
-        QString subfilter = *it;
-        if (!subfilter.isEmpty()) {
-            if (hideFiltersDetails) {
-                int index = r.indexIn(subfilter);
-                if (index >= 0)
-                    winfilters += r.cap(1);
-            } else {
-                winfilters += subfilter;
-            }
-            winfilters += QChar();
-            winfilters += qt_win_extract_filter(subfilter);
-            winfilters += QChar();
-        }
-    }
-    winfilters += QChar();
-    return winfilters;
-}
-
-static QString qt_win_selected_filter(const QString &filter, DWORD idx)
-{
-    return qt_win_make_filters_list(filter).at((int)idx - 1);
-}
-
-static QString tFilters, tTitle, tInitDir;
-
-static OPENFILENAME* qt_win_make_OFN(QWidget *parent,
-                                     const QString& initialSelection,
-                                     const QString& initialDirectory,
-                                     const QString& title,
-                                     const QString& filters,
-                                     QFileDialog::FileMode mode,
-                                     QFileDialog::Options options)
-{
-    if (parent)
-        parent = parent->window();
-    else
-        parent = QApplication::activeWindow();
-
-    tInitDir = QDir::toNativeSeparators(initialDirectory);
-    tFilters = filters;
-    tTitle = title;
-    QString initSel = QDir::toNativeSeparators(initialSelection);
-    if (!initSel.isEmpty()) {
-        initSel.remove(QLatin1Char('<'));
-        initSel.remove(QLatin1Char('>'));
-        initSel.remove(QLatin1Char('\"'));
-        initSel.remove(QLatin1Char('|'));
-    }
-
-    int maxLen = mode == QFileDialog::ExistingFiles ? maxMultiLen : maxNameLen;
-    wchar_t *tInitSel = new wchar_t[maxLen + 1];
-    if (initSel.length() > 0 && initSel.length() <= maxLen)
-        memcpy(tInitSel, initSel.utf16(), (initSel.length()+1)*sizeof(QChar));
-    else
-        tInitSel[0] = 0;
-
-    OPENFILENAME* ofn = new OPENFILENAME;
-    memset(ofn, 0, sizeof(OPENFILENAME));
-
-    ofn->lStructSize = sizeof(OPENFILENAME);
-    ofn->hwndOwner = parent ? parent->winId() : 0;
-    ofn->lpstrFilter = (wchar_t*)tFilters.utf16();
-    ofn->lpstrFile = tInitSel;
-    ofn->nMaxFile = maxLen;
-    ofn->lpstrInitialDir = (wchar_t*)tInitDir.utf16();
-    ofn->lpstrTitle = (wchar_t*)tTitle.utf16();
-    ofn->Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY | OFN_EXPLORER | OFN_PATHMUSTEXIST);
-    if (mode == QFileDialog::ExistingFile ||
-         mode == QFileDialog::ExistingFiles)
-        ofn->Flags |= (OFN_FILEMUSTEXIST);
-    if (mode == QFileDialog::ExistingFiles)
-        ofn->Flags |= (OFN_ALLOWMULTISELECT);
-    if (!(options & QFileDialog::DontConfirmOverwrite))
-        ofn->Flags |= OFN_OVERWRITEPROMPT;
-
-    return ofn;
-}
-
-static void qt_win_clean_up_OFN(OPENFILENAME **ofn)
-{
-    delete [] (*ofn)->lpstrFile;
-    delete *ofn;
-    *ofn = 0;
-}
-
-extern void qt_win_eatMouseMove();
-
-QString qt_win_get_open_file_name(const QFileDialogArgs &args,
-                                  QString *initialDirectory,
-                                  QString *selectedFilter)
-{
-    QString result;
-
-    QString isel = args.selection;
-
-    if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
-        initialDirectory->remove(0, 5);
-    QFileInfo fi(*initialDirectory);
-
-    if (initialDirectory && !fi.isDir()) {
-        *initialDirectory = fi.absolutePath();
-        if (isel.isEmpty())
-            isel = fi.fileName();
-    }
-
-    if (!fi.exists())
-        *initialDirectory = QDir::homePath();
-
-    DWORD selFilIdx = 0;
-
-    int idx = 0;
-    if (selectedFilter) {
-        QStringList filterLst = qt_win_make_filters_list(args.filter);
-        idx = filterLst.indexOf(*selectedFilter);
-    }
-
-    QDialog modal_widget;
-    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
-    modal_widget.setParent(args.parent, Qt::Window);
-    QApplicationPrivate::enterModal(&modal_widget);
-
-    bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
-    OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection,
-                                        args.directory, args.caption,
-                                        qt_win_filter(args.filter, hideFiltersDetails),
-                                        QFileDialog::ExistingFile,
-                                        args.options);
-    if (idx)
-        ofn->nFilterIndex = idx + 1;
-    if (GetOpenFileName(ofn)) {
-        result = QString::fromWCharArray(ofn->lpstrFile);
-        selFilIdx = ofn->nFilterIndex;
-    }
-    qt_win_clean_up_OFN(&ofn);
-
-    QApplicationPrivate::leaveModal(&modal_widget);
-
-    qt_win_eatMouseMove();
-
-    if (result.isEmpty())
-        return result;
-
-    fi = result;
-    *initialDirectory = fi.path();
-    if (selectedFilter)
-        *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
-    return fi.absoluteFilePath();
-}
-
-QString qt_win_get_save_file_name(const QFileDialogArgs &args,
-                                  QString *initialDirectory,
-                                  QString *selectedFilter)
-{
-    QString result;
-
-    QString isel = args.selection;
-    if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
-        initialDirectory->remove(0, 5);
-    QFileInfo fi(*initialDirectory);
-
-    if (initialDirectory && !fi.isDir()) {
-        *initialDirectory = fi.absolutePath();
-        if (isel.isEmpty())
-            isel = fi.fileName();
-    }
-
-    if (!fi.exists())
-        *initialDirectory = QDir::homePath();
-
-    DWORD selFilIdx = 0;
-
-    int idx = 0;
-    if (selectedFilter) {
-        QStringList filterLst = qt_win_make_filters_list(args.filter);
-        idx = filterLst.indexOf(*selectedFilter);
-    }
-
-    QDialog modal_widget;
-    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
-    modal_widget.setParent(args.parent, Qt::Window);
-    QApplicationPrivate::enterModal(&modal_widget);
-    bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
-    // This block is used below for the lpstrDefExt member.
-    // Note that the current MSDN docs document this member wrong.
-    // It should rather be documented as "the default extension if no extension was given and if the
-    // current filter does not have a extension (e.g (*)). If the current filter have an extension, use
-    // the extension of the current filter"
-    QString defaultSaveExt;
-    if (selectedFilter && !selectedFilter->isEmpty()) {
-        defaultSaveExt = qt_win_extract_filter(*selectedFilter);
-        // make sure we only have the extension
-        int firstDot = defaultSaveExt.indexOf(QLatin1Char('.'));
-        if (firstDot != -1) {
-            defaultSaveExt.remove(0, firstDot + 1);
-        } else {
-            defaultSaveExt.clear();
-        }
-    }
-
-    OPENFILENAME *ofn = qt_win_make_OFN(args.parent, args.selection,
-                                        args.directory, args.caption,
-                                        qt_win_filter(args.filter, hideFiltersDetails),
-                                        QFileDialog::AnyFile,
-                                        args.options);
-
-    ofn->lpstrDefExt = (wchar_t*)defaultSaveExt.utf16();
-
-    if (idx)
-        ofn->nFilterIndex = idx + 1;
-    if (GetSaveFileName(ofn)) {
-        result = QString::fromWCharArray(ofn->lpstrFile);
-        selFilIdx = ofn->nFilterIndex;
-    }
-    qt_win_clean_up_OFN(&ofn);
-
-#if defined(Q_WS_WINCE)
-    int semIndex = result.indexOf(QLatin1Char(';'));
-    if (semIndex >= 0)
-        result = result.left(semIndex);
-#endif
-
-    QApplicationPrivate::leaveModal(&modal_widget);
-
-    qt_win_eatMouseMove();
-
-    if (result.isEmpty())
-        return result;
-
-    fi = result;
-    *initialDirectory = fi.path();
-    if (selectedFilter)
-        *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
-    return fi.absoluteFilePath();
-}
-
-
-#ifndef Q_WS_WINCE
-
-typedef HRESULT (WINAPI *PtrSHCreateItemFromParsingName)(PCWSTR pszPath, IBindCtx *pbc, REFIID riid, void **ppv);
-static PtrSHCreateItemFromParsingName pSHCreateItemFromParsingName = 0;
-
-static bool qt_win_set_IFileDialogOptions(IFileDialog *pfd,
-                                          const QString& initialSelection,
-                                          const QString& initialDirectory,
-                                          const QString& title,
-                                          const QStringList& filterLst,
-                                          QFileDialog::FileMode mode,
-                                          QFileDialog::Options options)
-{
-    if (!pSHCreateItemFromParsingName) {
-        // This function is available only in Vista & above.
-        QSystemLibrary shellLib(QLatin1String("Shell32"));
-        pSHCreateItemFromParsingName = (PtrSHCreateItemFromParsingName)
-            shellLib.resolve("SHCreateItemFromParsingName");
-        if (!pSHCreateItemFromParsingName)
-            return false;
-    }
-    HRESULT hr;
-    QString winfilters;
-    int numFilters = 0;
-    quint32 currentOffset = 0;
-    QList<quint32> offsets;
-    QStringList::ConstIterator it = filterLst.begin();
-    // Create the native filter string and save offset to each entry.
-    for (; it != filterLst.end(); ++it) {
-        QString subfilter = *it;
-        if (!subfilter.isEmpty()) {
-            offsets<<currentOffset;
-            //Here the COMMON_ITEM_DIALOG API always add the details for the filter (e.g. *.txt)
-            //so we don't need to handle the flag HideNameFilterDetails.
-            winfilters += subfilter; // The name of the filter.
-            winfilters += QChar();
-            currentOffset += subfilter.size()+1;
-            offsets<<currentOffset;
-            QString spec = qt_win_extract_filter(subfilter);
-            winfilters += spec; // The actual filter spec.
-            winfilters += QChar();
-            currentOffset += spec.size()+1;
-            numFilters++;
-        }
-    }
-    // Add the filters to the file dialog.
-    if (numFilters) {
-        wchar_t *szData = (wchar_t*)winfilters.utf16();
-        qt_COMDLG_FILTERSPEC *filterSpec = new qt_COMDLG_FILTERSPEC[numFilters];
-        for(int i = 0; i<numFilters; i++) {
-            filterSpec[i].pszName = szData+offsets[i*2];
-            filterSpec[i].pszSpec = szData+offsets[(i*2)+1];
-        }
-        hr = pfd->SetFileTypes(numFilters, filterSpec);
-        delete []filterSpec;
-    }
-    // Set the starting folder.
-    tInitDir = QDir::toNativeSeparators(initialDirectory);
-    if (!tInitDir.isEmpty()) {
-        IShellItem *psiDefaultFolder;
-        hr = pSHCreateItemFromParsingName((wchar_t*)tInitDir.utf16(), NULL, QT_IID_IShellItem, 
-            reinterpret_cast<void**>(&psiDefaultFolder));
-
-        if (SUCCEEDED(hr)) {
-            hr = pfd->SetFolder(psiDefaultFolder);
-            psiDefaultFolder->Release();
-        }
-    }
-    // Set the currently selected file.
-    QString initSel = QDir::toNativeSeparators(initialSelection);
-    if (!initSel.isEmpty()) {
-        initSel.remove(QLatin1Char('<'));
-        initSel.remove(QLatin1Char('>'));
-        initSel.remove(QLatin1Char('\"'));
-        initSel.remove(QLatin1Char('|'));
-    }
-    if (!initSel.isEmpty()) {
-        hr = pfd->SetFileName((wchar_t*)initSel.utf16());
-    }
-    // Set the title for the file dialog.
-    if (!title.isEmpty()) {
-        hr = pfd->SetTitle((wchar_t*)title.utf16());
-    }
-    // Set other flags for the dialog.
-    DWORD newOptions;
-    hr = pfd->GetOptions(&newOptions);
-    if (SUCCEEDED(hr)) {
-        newOptions |= FOS_NOCHANGEDIR;
-        if (mode == QFileDialog::ExistingFile ||
-             mode == QFileDialog::ExistingFiles)
-            newOptions |= (FOS_FILEMUSTEXIST | FOS_PATHMUSTEXIST);
-        if (mode == QFileDialog::ExistingFiles)
-            newOptions |= FOS_ALLOWMULTISELECT;
-        if (!(options & QFileDialog::DontConfirmOverwrite))
-            newOptions |= FOS_OVERWRITEPROMPT;
-        hr = pfd->SetOptions(newOptions);
-    }
-    return SUCCEEDED(hr);
-}
-
-static QStringList qt_win_CID_get_open_file_names(const QFileDialogArgs &args,
-                                       QString *initialDirectory,
-                                       const QStringList &filterList,
-                                       QString *selectedFilter,
-                                       int selectedFilterIndex)
-{
-    QStringList result;
-    QDialog modal_widget;
-    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
-    modal_widget.setParent(args.parent, Qt::Window);
-    QApplicationPrivate::enterModal(&modal_widget);
-    // Multiple selection is allowed only in IFileOpenDialog.
-    IFileOpenDialog *pfd = 0;
-    HRESULT hr = CoCreateInstance(QT_CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, QT_IID_IFileOpenDialog, 
-        reinterpret_cast<void**>(&pfd));
-
-    if (SUCCEEDED(hr)) {
-        qt_win_set_IFileDialogOptions(pfd, args.selection,
-                                      args.directory, args.caption,
-                                      filterList, QFileDialog::ExistingFiles,
-                                      args.options);
-        // Set the currently selected filter (one-based index).
-        hr = pfd->SetFileTypeIndex(selectedFilterIndex+1);
-        QWidget *parentWindow = args.parent;
-        if (parentWindow)
-            parentWindow = parentWindow->window();
-        else
-            parentWindow = QApplication::activeWindow();
-        // Show the file dialog.
-        hr = pfd->Show(parentWindow ? parentWindow->winId() : 0);
-        if (SUCCEEDED(hr)) {
-            // Retrieve the results.
-            IShellItemArray *psiaResults;
-            hr = pfd->GetResults(&psiaResults);
-            if (SUCCEEDED(hr)) {
-                DWORD numItems = 0;
-                psiaResults->GetCount(&numItems);
-                for (DWORD i = 0; i<numItems; i++) {
-                    IShellItem *psi = 0;
-                    hr = psiaResults->GetItemAt(i, &psi);
-                    if (SUCCEEDED(hr)) {
-                        // Retrieve the file name from shell item.
-                        wchar_t *pszPath;
-                        hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
-                        if (SUCCEEDED(hr)) {
-                            QString fileName = QString::fromWCharArray(pszPath);
-                            result.append(fileName);
-                            CoTaskMemFree(pszPath);
-                        }
-                        psi->Release(); // Free the current item.
-                    }
-                }
-                psiaResults->Release(); // Free the array of items.
-            }
-        }
-    }
-    QApplicationPrivate::leaveModal(&modal_widget);
-
-    qt_win_eatMouseMove();
-
-    if (!result.isEmpty()) {
-        // Retrieve the current folder name.
-        IShellItem *psi = 0;
-        hr = pfd->GetFolder(&psi);
-        if (SUCCEEDED(hr)) {
-            wchar_t *pszPath;
-            hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
-            if (SUCCEEDED(hr)) {
-                *initialDirectory = QString::fromWCharArray(pszPath);
-                CoTaskMemFree(pszPath);
-            }
-            psi->Release();
-        }
-        // Retrieve the currently selected filter.
-        if (selectedFilter) {
-            quint32 filetype = 0;
-            hr = pfd->GetFileTypeIndex(&filetype);
-            if (SUCCEEDED(hr) && filetype && filetype <= (quint32)filterList.length()) {
-                // This is a one-based index, not zero-based.
-                *selectedFilter = filterList[filetype-1];
-            }
-        }
-    }
-    if (pfd)
-        pfd->Release();
-    return result;
-}
-
-QString qt_win_CID_get_existing_directory(const QFileDialogArgs &args)
-{
-    QString result;
-    QDialog modal_widget;
-    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
-    modal_widget.setParent(args.parent, Qt::Window);
-    QApplicationPrivate::enterModal(&modal_widget);
-
-    IFileOpenDialog *pfd = 0;
-    HRESULT hr = CoCreateInstance(QT_CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER,
-                                  QT_IID_IFileOpenDialog, reinterpret_cast<void**>(&pfd));
-
-    if (SUCCEEDED(hr)) {
-        qt_win_set_IFileDialogOptions(pfd, args.selection,
-                                      args.directory, args.caption,
-                                      QStringList(), QFileDialog::ExistingFile,
-                                      args.options);
-
-        // Set the FOS_PICKFOLDERS flag
-        DWORD newOptions;
-        hr = pfd->GetOptions(&newOptions);
-        newOptions |= (FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
-        if (SUCCEEDED(hr) && SUCCEEDED((hr = pfd->SetOptions(newOptions)))) {
-            QWidget *parentWindow = args.parent;
-            if (parentWindow)
-                parentWindow = parentWindow->window();
-            else
-                parentWindow = QApplication::activeWindow();
-
-            // Show the file dialog.
-            hr = pfd->Show(parentWindow ? parentWindow->winId() : 0);
-            if (SUCCEEDED(hr)) {
-                // Retrieve the result
-                IShellItem *psi = 0;
-                hr = pfd->GetResult(&psi);
-                if (SUCCEEDED(hr)) {
-                    // Retrieve the file name from shell item.
-                    wchar_t *pszPath;
-                    hr = psi->GetDisplayName(SIGDN_FILESYSPATH, &pszPath);
-                    if (SUCCEEDED(hr)) {
-                        result = QString::fromWCharArray(pszPath);
-                        CoTaskMemFree(pszPath);
-                    }
-                    psi->Release(); // Free the current item.
-                }
-            }
-        }
-    }
-    QApplicationPrivate::leaveModal(&modal_widget);
-
-    qt_win_eatMouseMove();
-
-    if (pfd)
-        pfd->Release();
-    return result;
-}
-
-#endif
-
-QStringList qt_win_get_open_file_names(const QFileDialogArgs &args,
-                                       QString *initialDirectory,
-                                       QString *selectedFilter)
-{
-    QFileInfo fi;
-    QDir dir;
-
-    if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
-        initialDirectory->remove(0, 5);
-    fi = QFileInfo(*initialDirectory);
-
-    if (initialDirectory && !fi.isDir()) {
-        *initialDirectory = fi.absolutePath();
-    }
-
-    if (!fi.exists())
-        *initialDirectory = QDir::homePath();
-
-    DWORD selFilIdx = 0;
-
-    QStringList filterLst = qt_win_make_filters_list(args.filter);
-    int idx = 0;
-    if (selectedFilter) {
-        idx = filterLst.indexOf(*selectedFilter);
-    }
-    // Windows Vista (& above) allows users to search from file dialogs. If user selects
-    // multiple files belonging to different folders from these search results, the
-    // GetOpenFileName() will return only one folder name for all the files. To retrieve
-    // the correct path for all selected files, we have to use Common Item Dialog interfaces.
-#ifndef Q_WS_WINCE
-    if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based))
-        return qt_win_CID_get_open_file_names(args, initialDirectory, filterLst, selectedFilter, idx);
-#endif
-
-    QStringList result;
-    QDialog modal_widget;
-    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
-    modal_widget.setParent(args.parent, Qt::Window);
-    QApplicationPrivate::enterModal(&modal_widget);
-
-    bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
-    OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection,
-                                        args.directory, args.caption,
-                                        qt_win_filter(args.filter, hideFiltersDetails),
-                                        QFileDialog::ExistingFiles,
-                                        args.options);
-    if (idx)
-        ofn->nFilterIndex = idx + 1;
-    if (GetOpenFileName(ofn)) {
-        QString fileOrDir = QString::fromWCharArray(ofn->lpstrFile);
-        selFilIdx = ofn->nFilterIndex;
-        int offset = fileOrDir.length() + 1;
-        if (ofn->lpstrFile[offset] == 0) {
-            // Only one file selected; has full path
-            fi.setFile(fileOrDir);
-            QString res = fi.absoluteFilePath();
-            if (!res.isEmpty())
-                result.append(res);
-        }
-        else {
-            // Several files selected; first string is path
-            dir.setPath(fileOrDir);
-            QString f;
-            while(!(f = QString::fromWCharArray(ofn->lpstrFile + offset)).isEmpty()) {
-                fi.setFile(dir, f);
-                QString res = fi.absoluteFilePath();
-                if (!res.isEmpty())
-                    result.append(res);
-                offset += f.length() + 1;
-            }
-        }
-    }
-    qt_win_clean_up_OFN(&ofn);
-
-    QApplicationPrivate::leaveModal(&modal_widget);
-
-    qt_win_eatMouseMove();
-
-    if (!result.isEmpty()) {
-        *initialDirectory = fi.path();    // only save the path if there is a result
-        if (selectedFilter)
-            *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
-    }
-    return result;
-}
-
-// MFC Directory Dialog. Contrib: Steve Williams (minor parts from Scott Powers)
-
-static int __stdcall winGetExistDirCallbackProc(HWND hwnd,
-                                                UINT uMsg,
-                                                LPARAM lParam,
-                                                LPARAM lpData)
-{
-    if (uMsg == BFFM_INITIALIZED && lpData != 0) {
-        QString *initDir = (QString *)(lpData);
-        if (!initDir->isEmpty()) {
-            SendMessage(hwnd, BFFM_SETSELECTION, TRUE, LPARAM(initDir->utf16()));
-        }
-    } else if (uMsg == BFFM_SELCHANGED) {
-        qt_win_resolve_libs();
-        if (ptrSHGetPathFromIDList) {
-            wchar_t path[MAX_PATH];
-            ptrSHGetPathFromIDList(qt_LPITEMIDLIST(lParam), path);
-            QString tmpStr = QString::fromWCharArray(path);
-            if (!tmpStr.isEmpty())
-                SendMessage(hwnd, BFFM_ENABLEOK, 1, 1);
-            else
-                SendMessage(hwnd, BFFM_ENABLEOK, 0, 0);
-            SendMessage(hwnd, BFFM_SETSTATUSTEXT, 1, LPARAM(path));
-        }
-    }
-    return 0;
-}
-
-QString qt_win_get_existing_directory(const QFileDialogArgs &args)
-{
-#ifndef Q_WS_WINCE
-    if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based))
-        return qt_win_CID_get_existing_directory(args);
-#endif
-
-    QString currentDir = QDir::currentPath();
-    QString result;
-    QWidget *parent = args.parent;
-    if (parent)
-        parent = parent->window();
-    else
-        parent = QApplication::activeWindow();
-    if (parent)
-        parent->createWinId();
-
-    QDialog modal_widget;
-    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
-    modal_widget.setParent(parent, Qt::Window);
-    QApplicationPrivate::enterModal(&modal_widget);
-
-    QString initDir = QDir::toNativeSeparators(args.directory);
-    wchar_t path[MAX_PATH];
-    wchar_t initPath[MAX_PATH];
-    initPath[0] = 0;
-    path[0] = 0;
-    tTitle = args.caption;
-
-    qt_BROWSEINFO bi;
-
-    Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created));
-    bi.hwndOwner = (parent ? parent->winId() : 0);
-    bi.pidlRoot = NULL;
-    //### This does not seem to be respected? - the dialog always displays "Browse for folder"
-    bi.lpszTitle = (wchar_t*)tTitle.utf16();
-    bi.pszDisplayName = initPath;
-    bi.ulFlags = BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT | BIF_NEWDIALOGSTYLE;
-    bi.lpfn = winGetExistDirCallbackProc;
-    bi.lParam = LPARAM(&initDir);
-
-    qt_win_resolve_libs();
-    if (ptrSHBrowseForFolder) {
-        qt_LPITEMIDLIST pItemIDList = ptrSHBrowseForFolder(&bi);
-        if (pItemIDList) {
-            ptrSHGetPathFromIDList(pItemIDList, path);
-            IMalloc *pMalloc;
-            if (ptrSHGetMalloc(&pMalloc) == NOERROR) {
-                pMalloc->Free(pItemIDList);
-                pMalloc->Release();
-                result = QString::fromWCharArray(path);
-            }
-        }
-    }
-    tTitle = QString();
-
-    QApplicationPrivate::leaveModal(&modal_widget);
-
-    qt_win_eatMouseMove();
-
-    if (!result.isEmpty())
-        result.replace(QLatin1Char('\\'), QLatin1Char('/'));
-    return result;
-}
-
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qfiledialog_win_p.h b/src/gui/dialogs/qfiledialog_win_p.h
deleted file mode 100644 (file)
index ed9904c..0000000
+++ /dev/null
@@ -1,243 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <objbase.h>
-#ifndef QFILEDIAG_WIN_P_H
-#define QFILEDIAG_WIN_P_H
-
-//these are the interface declarations needed for the file dialog on Vista and up
-
-//At some point we can hope that all compilers/sdk will support that interface
-//and we won't have to declare it ourselves
-
-//declarations
-#define FOS_OVERWRITEPROMPT       0x2
-#define FOS_STRICTFILETYPES       0x4
-#define FOS_NOCHANGEDIR               0x8
-#define FOS_PICKFOLDERS               0x20
-#define FOS_FORCEFILESYSTEM       0x40
-#define FOS_ALLNONSTORAGEITEMS 0x80
-#define FOS_NOVALIDATE         0x100
-#define FOS_ALLOWMULTISELECT   0x200
-#define FOS_PATHMUSTEXIST      0x800
-#define FOS_FILEMUSTEXIST      0x1000
-#define FOS_CREATEPROMPT       0x2000
-#define FOS_SHAREAWARE         0x4000
-#define FOS_NOREADONLYRETURN   0x8000
-#define FOS_NOTESTFILECREATE   0x10000
-#define FOS_HIDEMRUPLACES      0x20000
-#define FOS_HIDEPINNEDPLACES   0x40000
-#define FOS_NODEREFERENCELINKS 0x100000
-#define FOS_DONTADDTORECENT    0x2000000
-#define FOS_FORCESHOWHIDDEN    0x10000000
-#define FOS_DEFAULTNOMINIMODE  0x20000000
-#define FOS_FORCEPREVIEWPANEON 0x40000000
-
-typedef int GETPROPERTYSTOREFLAGS;
-#define GPS_DEFAULT               0x00000000
-#define GPS_HANDLERPROPERTIESONLY 0x00000001
-#define GPS_READWRITE             0x00000002
-#define GPS_TEMPORARY             0x00000004
-#define GPS_FASTPROPERTIESONLY    0x00000008
-#define GPS_OPENSLOWITEM          0x00000010
-#define GPS_DELAYCREATION         0x00000020
-#define GPS_BESTEFFORT            0x00000040
-#define GPS_MASK_VALID            0x0000007F
-
-typedef int (QT_WIN_CALLBACK* BFFCALLBACK)(HWND hwnd, UINT uMsg, LPARAM lParam, LPARAM lpData);
-// message from browser
-#define BFFM_INITIALIZED        1
-#define BFFM_SELCHANGED         2
-#define BFFM_ENABLEOK           (WM_USER + 101)
-#define BFFM_SETSELECTION       (WM_USER + 103)
-#define BFFM_SETSTATUSTEXT      (WM_USER + 104)
-
-// Browsing for directory.
-#define BIF_RETURNONLYFSDIRS   0x0001
-#define BIF_DONTGOBELOWDOMAIN  0x0002
-#define BIF_STATUSTEXT         0x0004
-#define BIF_RETURNFSANCESTORS  0x0008
-#define BIF_EDITBOX            0x0010
-#define BIF_VALIDATE           0x0020
-#define BIF_NEWDIALOGSTYLE     0x0040
-#define BIF_BROWSEINCLUDEURLS  0x0080
-#define BIF_UAHINT             0x0100
-#define BIF_NONEWFOLDERBUTTON  0x0200
-#define BIF_NOTRANSLATETARGETS 0x0400
-#define BIF_BROWSEFORCOMPUTER  0x1000
-#define BIF_BROWSEFORPRINTER   0x2000
-#define BIF_BROWSEINCLUDEFILES 0x4000
-#define BIF_SHAREABLE          0x8000
-
-//the enums
-typedef enum {
-    SIATTRIBFLAGS_AND  = 0x1,
-    SIATTRIBFLAGS_OR   = 0x2,
-    SIATTRIBFLAGS_APPCOMPAT    = 0x3,
-    SIATTRIBFLAGS_MASK = 0x3
-}      SIATTRIBFLAGS;
-typedef enum {
-    SIGDN_NORMALDISPLAY = 0x00000000,
-    SIGDN_PARENTRELATIVEPARSING = 0x80018001,
-    SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8001c001,
-    SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
-    SIGDN_PARENTRELATIVEEDITING = 0x80031001,
-    SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
-    SIGDN_FILESYSPATH = 0x80058000,
-    SIGDN_URL = 0x80068000
-} SIGDN;
-typedef enum {
-    FDAP_BOTTOM = 0x00000000,
-    FDAP_TOP = 0x00000001
-} FDAP;
-typedef enum {
-    FDESVR_DEFAULT = 0x00000000,
-    FDESVR_ACCEPT = 0x00000001,
-    FDESVR_REFUSE = 0x00000002
-} FDE_SHAREVIOLATION_RESPONSE;
-typedef FDE_SHAREVIOLATION_RESPONSE FDE_OVERWRITE_RESPONSE;
-
-//the structs
-typedef struct {
-    LPCWSTR pszName;
-    LPCWSTR pszSpec;
-} qt_COMDLG_FILTERSPEC;
-typedef struct {
-    GUID fmtid;
-    DWORD pid;
-} qt_PROPERTYKEY;
-
-typedef struct {
-       USHORT  cb;
-       BYTE    abID[1];
-} qt_SHITEMID, *qt_LPSHITEMID;
-typedef struct {
-       qt_SHITEMID mkid;
-} qt_ITEMIDLIST, *qt_LPITEMIDLIST;
-typedef const qt_ITEMIDLIST *qt_LPCITEMIDLIST;
-typedef struct {
-    HWND          hwndOwner;
-    qt_LPCITEMIDLIST pidlRoot;
-    LPWSTR        pszDisplayName;
-    LPCWSTR       lpszTitle;
-    UINT          ulFlags;
-    BFFCALLBACK   lpfn;
-    LPARAM        lParam;
-    int           iImage;
-} qt_BROWSEINFO;
-
-DECLARE_INTERFACE(IFileDialogEvents);
-DECLARE_INTERFACE_(IShellItem, IUnknown)
-{
-    STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID bhid, REFIID riid, void **ppv) PURE;
-    STDMETHOD(GetParent)(THIS_ IShellItem **ppsi) PURE;
-    STDMETHOD(GetDisplayName)(THIS_ SIGDN sigdnName, LPWSTR *ppszName) PURE;
-    STDMETHOD(GetAttributes)(THIS_ ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE;
-    STDMETHOD(Compare)(THIS_ IShellItem *psi, DWORD hint, int *piOrder) PURE;
-};
-DECLARE_INTERFACE_(IShellItemFilter, IUnknown)
-{
-    STDMETHOD(IncludeItem)(THIS_ IShellItem *psi) PURE;
-    STDMETHOD(GetEnumFlagsForItem)(THIS_ IShellItem *psi, DWORD *pgrfFlags) PURE;
-};
-DECLARE_INTERFACE_(IEnumShellItems, IUnknown)
-{
-    STDMETHOD(Next)(THIS_ ULONG celt, IShellItem **rgelt, ULONG *pceltFetched) PURE;
-    STDMETHOD(Skip)(THIS_ ULONG celt) PURE;
-    STDMETHOD(Reset)(THIS_) PURE;
-    STDMETHOD(Clone)(THIS_ IEnumShellItems **ppenum) PURE;
-};
-DECLARE_INTERFACE_(IShellItemArray, IUnknown)
-{
-    STDMETHOD(BindToHandler)(THIS_ IBindCtx *pbc, REFGUID rbhid, REFIID riid, void **ppvOut) PURE;
-    STDMETHOD(GetPropertyStore)(THIS_ GETPROPERTYSTOREFLAGS flags, REFIID riid, void **ppv) PURE;
-    STDMETHOD(GetPropertyDescriptionList)(THIS_ const qt_PROPERTYKEY *keyType, REFIID riid, void **ppv) PURE;
-    STDMETHOD(GetAttributes)(THIS_ SIATTRIBFLAGS dwAttribFlags, ULONG sfgaoMask, ULONG *psfgaoAttribs) PURE;
-    STDMETHOD(GetCount)(THIS_ DWORD *pdwNumItems) PURE;
-    STDMETHOD(GetItemAt)(THIS_ DWORD dwIndex, IShellItem **ppsi) PURE;
-    STDMETHOD(EnumItems)(THIS_ IEnumShellItems **ppenumShellItems) PURE;
-};
-DECLARE_INTERFACE_(IModalWindow, IUnknown)
-{
-    STDMETHOD(Show)(THIS_ HWND hwndParent) PURE;
-};
-DECLARE_INTERFACE_(IFileDialog, IModalWindow)
-{
-    STDMETHOD(SetFileTypes)(THIS_ UINT cFileTypes, const qt_COMDLG_FILTERSPEC *rgFilterSpec) PURE;
-    STDMETHOD(SetFileTypeIndex)(THIS_ UINT iFileType) PURE;
-    STDMETHOD(GetFileTypeIndex)(THIS_ UINT *piFileType) PURE;
-    STDMETHOD(Advise)(THIS_ IFileDialogEvents *pfde, DWORD *pdwCookie) PURE;
-    STDMETHOD(Unadvise)(THIS_ DWORD dwCookie) PURE;
-    STDMETHOD(SetOptions)(THIS_ DWORD fos) PURE;
-    STDMETHOD(GetOptions)(THIS_ DWORD *pfos) PURE;
-    STDMETHOD(SetDefaultFolder)(THIS_ IShellItem *psi) PURE;
-    STDMETHOD(SetFolder)(THIS_ IShellItem *psi) PURE;
-    STDMETHOD(GetFolder)(THIS_ IShellItem **ppsi) PURE;
-    STDMETHOD(GetCurrentSelection)(THIS_ IShellItem **ppsi) PURE;
-    STDMETHOD(SetFileName)(THIS_ LPCWSTR pszName) PURE;
-    STDMETHOD(GetFileName)(THIS_ LPWSTR *pszName) PURE;
-    STDMETHOD(SetTitle)(THIS_ LPCWSTR pszTitle) PURE;
-    STDMETHOD(SetOkButtonLabel)(THIS_ LPCWSTR pszText) PURE;
-    STDMETHOD(SetFileNameLabel)(THIS_ LPCWSTR pszLabel) PURE;
-    STDMETHOD(GetResult)(THIS_ IShellItem **ppsi) PURE;
-    STDMETHOD(AddPlace)(THIS_ IShellItem *psi, FDAP fdap) PURE;
-    STDMETHOD(SetDefaultExtension)(THIS_ LPCWSTR pszDefaultExtension) PURE;
-    STDMETHOD(Close)(THIS_ HRESULT hr) PURE;
-    STDMETHOD(SetClientGuid)(THIS_ REFGUID guid) PURE;
-    STDMETHOD(ClearClientData)(THIS_) PURE;
-    STDMETHOD(SetFilter)(THIS_ IShellItemFilter *pFilter) PURE;
-};
-DECLARE_INTERFACE_(IFileDialogEvents, IUnknown)
-{
-    STDMETHOD(OnFileOk)(THIS_ IFileDialog *pfd) PURE;
-    STDMETHOD(OnFolderChanging)(THIS_ IFileDialog *pfd, IShellItem *psiFolder) PURE;
-    STDMETHOD(OnFolderChange)(THIS_ IFileDialog *pfd) PURE;
-    STDMETHOD(OnSelectionChange)(THIS_ IFileDialog *pfd) PURE;
-    STDMETHOD(OnShareViolation)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_SHAREVIOLATION_RESPONSE *pResponse) PURE;
-    STDMETHOD(OnTypeChange)(THIS_ IFileDialog *pfd) PURE;
-    STDMETHOD(OnOverwrite)(THIS_ IFileDialog *pfd, IShellItem *psi, FDE_OVERWRITE_RESPONSE *pResponse) PURE;
-};
-DECLARE_INTERFACE_(IFileOpenDialog, IFileDialog)
-{
-    STDMETHOD(GetResults)(THIS_ IShellItemArray **ppenum) PURE;
-    STDMETHOD(GetSelectedItems)(THIS_ IShellItemArray **ppsai) PURE;
-};
-#endif
diff --git a/src/gui/dialogs/qfontdialog_mac.mm b/src/gui/dialogs/qfontdialog_mac.mm
deleted file mode 100644 (file)
index f992adc..0000000
+++ /dev/null
@@ -1,700 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfontdialog_p.h"
-#if !defined(QT_NO_FONTDIALOG) && defined(Q_WS_MAC)
-#include <qapplication.h>
-#include <qdialogbuttonbox.h>
-#include <qlineedit.h>
-#include <qapplication_p.h>
-#include <qfont_p.h>
-#include <qfontengine_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qt_mac_p.h>
-#include <qabstracteventdispatcher.h>
-#include <qdebug.h>
-#include <qfontengine_coretext_p.h>
-#import <AppKit/AppKit.h>
-#import <Foundation/Foundation.h>
-
-#if !CGFLOAT_DEFINED
-typedef float CGFloat;  // Should only not be defined on 32-bit platforms
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern void macStartInterceptNSPanelCtor();
-extern void macStopInterceptNSPanelCtor();
-extern NSButton *macCreateButton(const char *text, NSView *superview);
-extern bool qt_mac_is_macsheet(const QWidget *w); // qwidget_mac.mm
-
-QT_END_NAMESPACE
-QT_USE_NAMESPACE
-
-// should a priori be kept in sync with qcolordialog_mac.mm
-const CGFloat ButtonMinWidth = 78.0;
-const CGFloat ButtonMinHeight = 32.0;
-const CGFloat ButtonSpacing = 0.0;
-const CGFloat ButtonTopMargin = 0.0;
-const CGFloat ButtonBottomMargin = 7.0;
-const CGFloat ButtonSideMargin = 9.0;
-
-// looks better with some margins
-const CGFloat DialogTopMargin = 7.0;
-const CGFloat DialogSideMargin = 9.0;
-
-const int StyleMask = NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask;
-
-@class QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate);
-
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-
-@protocol NSWindowDelegate <NSObject>
-- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize;
-@end
-
-#endif
-
-@interface QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) : NSObject <NSWindowDelegate> {
-    NSFontPanel *mFontPanel;
-    NSView *mStolenContentView;
-    NSButton *mOkButton;
-    NSButton *mCancelButton;
-    QFontDialogPrivate *mPriv;
-    QFont *mQtFont;
-    BOOL mPanelHackedWithButtons;
-    CGFloat mDialogExtraWidth;
-    CGFloat mDialogExtraHeight;
-    int mReturnCode;
-    BOOL mAppModal;
-}
-- (id)initWithFontPanel:(NSFontPanel *)panel
-      stolenContentView:(NSView *)stolenContentView
-               okButton:(NSButton *)okButton
-           cancelButton:(NSButton *)cancelButton
-                   priv:(QFontDialogPrivate *)priv
-             extraWidth:(CGFloat)extraWidth
-            extraHeight:(CGFloat)extraHeight;
-- (void)showModelessPanel;
-- (void)showWindowModalSheet:(QWidget *)docWidget;
-- (void)runApplicationModalPanel;
-- (BOOL)isAppModal;
-- (void)changeFont:(id)sender;
-- (void)changeAttributes:(id)sender;
-- (BOOL)windowShouldClose:(id)window;
-- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize;
-- (void)relayout;
-- (void)relayoutToContentSize:(NSSize)frameSize;
-- (void)onOkClicked;
-- (void)onCancelClicked;
-- (NSFontPanel *)fontPanel;
-- (NSWindow *)actualPanel;
-- (NSSize)dialogExtraSize;
-- (void)setQtFont:(const QFont &)newFont;
-- (QFont)qtFont;
-- (void)finishOffWithCode:(NSInteger)result;
-- (void)cleanUpAfterMyself;
-- (void)setSubwindowStacking;
-@end
-
-static QFont qfontForCocoaFont(NSFont *cocoaFont, const QFont &resolveFont)
-{
-    QFont newFont;
-    if (cocoaFont) {
-        int pSize = qRound([cocoaFont pointSize]);
-        CTFontDescriptorRef font = CTFontCopyFontDescriptor((CTFontRef)cocoaFont);
-        // QCoreTextFontDatabase::populateFontDatabase() is using localized names
-        QString family = QCFString::toQString((CFStringRef) CTFontDescriptorCopyLocalizedAttribute(font, kCTFontFamilyNameAttribute, NULL));
-        QString style = QCFString::toQString((CFStringRef) CTFontDescriptorCopyLocalizedAttribute(font, kCTFontStyleNameAttribute, NULL));
-
-        newFont = QFontDatabase().font(family, style, pSize);
-        newFont.setUnderline(resolveFont.underline());
-        newFont.setStrikeOut(resolveFont.strikeOut());
-
-        CFRelease(font);
-    }
-    return newFont;
-}
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate)
-- (id)initWithFontPanel:(NSFontPanel *)panel
-       stolenContentView:(NSView *)stolenContentView
-                okButton:(NSButton *)okButton
-            cancelButton:(NSButton *)cancelButton
-                    priv:(QFontDialogPrivate *)priv
-              extraWidth:(CGFloat)extraWidth
-             extraHeight:(CGFloat)extraHeight
-{
-    self = [super init];
-    mFontPanel = panel;
-    mStolenContentView = stolenContentView;
-    mOkButton = okButton;
-    mCancelButton = cancelButton;
-    mPriv = priv;
-    mPanelHackedWithButtons = (okButton != 0);
-    mDialogExtraWidth = extraWidth;
-    mDialogExtraHeight = extraHeight;
-    mReturnCode = -1;
-    mAppModal = false;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7)
-        [mFontPanel setRestorable:NO];
-#endif
-
-    if (mPanelHackedWithButtons) {
-        [self relayout];
-
-        [okButton setAction:@selector(onOkClicked)];
-        [okButton setTarget:self];
-
-        [cancelButton setAction:@selector(onCancelClicked)];
-        [cancelButton setTarget:self];
-    }
-
-    mQtFont = new QFont();
-    return self;
-}
-
-- (void)setSubwindowStacking
-{
-#ifdef QT_MAC_USE_COCOA
-    // Stack the native dialog in front of its parent, if any:
-    QFontDialog *q = mPriv->fontDialog();
-    if (!qt_mac_is_macsheet(q)) {
-        if (QWidget *parent = q->parentWidget()) {
-            if (parent->isWindow()) {
-                [qt_mac_window_for(parent)
-                    addChildWindow:[mStolenContentView window] ordered:NSWindowAbove];
-            }
-        }
-    }
-#endif
-}
-
-- (void)dealloc
-{
-    delete mQtFont;
-    [super dealloc];
-}
-
-- (void)showModelessPanel
-{
-    mAppModal = false;
-    NSWindow *ourPanel = [mStolenContentView window];
-    [ourPanel makeKeyAndOrderFront:self];
-}
-
-- (void)runApplicationModalPanel
-{
-    QBoolBlocker nativeDialogOnTop(QApplicationPrivate::native_modal_dialog_active);
-    mAppModal = true;
-    NSWindow *ourPanel = [mStolenContentView window];
-    [ourPanel setReleasedWhenClosed:NO];
-    [[NSApplication sharedApplication] runModalForWindow:ourPanel];
-    QAbstractEventDispatcher::instance()->interrupt();
-
-    if (mReturnCode == NSOKButton)
-        mPriv->fontDialog()->accept();
-    else
-        mPriv->fontDialog()->reject();
-}
-
-- (BOOL)isAppModal
-{
-    return mAppModal;
-}
-
-- (void)showWindowModalSheet:(QWidget *)docWidget
-{
-#ifdef QT_MAC_USE_COCOA
-    NSWindow *window = qt_mac_window_for(docWidget);
-#else
-    WindowRef hiwindowRef = qt_mac_window_for(docWidget);
-    NSWindow *window = [[NSWindow alloc] initWithWindowRef:hiwindowRef];
-    CFRetain(hiwindowRef);
-#endif
-
-    mAppModal = false;
-    NSWindow *ourPanel = [mStolenContentView window];
-    [[NSApplication sharedApplication] beginSheet:ourPanel
-        modalForWindow:window
-        modalDelegate:0
-        didEndSelector:0
-        contextInfo:0 ];
-
-#ifndef QT_MAC_USE_COCOA
-    CFRelease(hiwindowRef);
-#endif
-}
-
-- (void)changeFont:(id)sender
-{
-    NSFont *dummyFont = [NSFont userFontOfSize:12.0];
-    [self setQtFont:qfontForCocoaFont([sender convertFont:dummyFont], *mQtFont)];
-    if (mPriv)
-        mPriv->updateSampleFont(*mQtFont);
-}
-
-- (void)changeAttributes:(id)sender
-{
-    NSDictionary *dummyAttribs = [NSDictionary dictionary];
-    NSDictionary *attribs = [sender convertAttributes:dummyAttribs];
-
-#ifdef QT_MAC_USE_COCOA
-    for (id key in attribs) {
-#else
-    NSEnumerator *enumerator = [attribs keyEnumerator];
-    id key;
-    while((key = [enumerator nextObject])) {
-#endif
-        NSNumber *number = static_cast<NSNumber *>([attribs objectForKey:key]);
-        if ([key isEqual:NSUnderlineStyleAttributeName]) {
-            mQtFont->setUnderline([number intValue] != NSUnderlineStyleNone);
-        } else if ([key isEqual:NSStrikethroughStyleAttributeName]) {
-            mQtFont->setStrikeOut([number intValue] != NSUnderlineStyleNone);
-        }
-    }
-
-    if (mPriv)
-        mPriv->updateSampleFont(*mQtFont);
-}
-
-- (BOOL)windowShouldClose:(id)window
-{
-    Q_UNUSED(window);
-    if (mPanelHackedWithButtons) {
-        [self onCancelClicked];
-    } else {
-        [self finishOffWithCode:NSCancelButton];
-    }
-    return true;
-}
-
-- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize
-{
-    if (mFontPanel == window) {
-        proposedFrameSize = [static_cast<id <NSWindowDelegate> >(mFontPanel) windowWillResize:mFontPanel toSize:proposedFrameSize];
-    } else {
-        /*
-            Ugly hack: NSFontPanel rearranges the layout of its main
-            component in windowWillResize:toSize:. So we temporarily
-            restore the stolen content view to its rightful owner,
-            call windowWillResize:toSize:, and steal the content view
-            again.
-        */
-        [mStolenContentView removeFromSuperview];
-        [mFontPanel setContentView:mStolenContentView];
-        NSSize extraSize = [self dialogExtraSize];
-        proposedFrameSize.width -= extraSize.width;
-        proposedFrameSize.height -= extraSize.height;
-        proposedFrameSize = [static_cast<id <NSWindowDelegate> >(mFontPanel) windowWillResize:mFontPanel toSize:proposedFrameSize];
-        NSRect frameRect = { { 0.0, 0.0 }, proposedFrameSize };
-        [mFontPanel setFrame:frameRect display:NO];
-        [mFontPanel setContentView:0];
-        [[window contentView] addSubview:mStolenContentView];
-        proposedFrameSize.width += extraSize.width;
-        proposedFrameSize.height += extraSize.height;
-    }
-    if (mPanelHackedWithButtons) {
-        NSRect frameRect = { { 0.0, 0.0 }, proposedFrameSize };
-        NSRect contentRect = [NSWindow contentRectForFrameRect:frameRect styleMask:[window styleMask]];
-        [self relayoutToContentSize:contentRect.size];
-    }
-    return proposedFrameSize;
-}
-
-- (void)relayout
-{
-    [self relayoutToContentSize:[[mStolenContentView superview] frame].size];
-}
-
-- (void)relayoutToContentSize:(NSSize)frameSize
-{
-    Q_ASSERT(mPanelHackedWithButtons);
-
-    [mOkButton sizeToFit];
-    NSSize okSizeHint = [mOkButton frame].size;
-
-    [mCancelButton sizeToFit];
-    NSSize cancelSizeHint = [mCancelButton frame].size;
-
-    const CGFloat ButtonWidth = qMin(qMax(ButtonMinWidth,
-                qMax(okSizeHint.width, cancelSizeHint.width)),
-            CGFloat((frameSize.width - 2.0 * ButtonSideMargin - ButtonSpacing) * 0.5));
-    const CGFloat ButtonHeight = qMax(ButtonMinHeight,
-                                     qMax(okSizeHint.height, cancelSizeHint.height));
-
-    const CGFloat X = DialogSideMargin;
-    const CGFloat Y = ButtonBottomMargin + ButtonHeight + ButtonTopMargin;
-
-    NSRect okRect = { { frameSize.width - ButtonSideMargin - ButtonWidth,
-                        ButtonBottomMargin },
-                      { ButtonWidth, ButtonHeight } };
-    [mOkButton setFrame:okRect];
-    [mOkButton setNeedsDisplay:YES];
-
-    NSRect cancelRect = { { okRect.origin.x - ButtonSpacing - ButtonWidth,
-                            ButtonBottomMargin },
-                            { ButtonWidth, ButtonHeight } };
-    [mCancelButton setFrame:cancelRect];
-    [mCancelButton setNeedsDisplay:YES];
-
-    NSRect stolenCVRect = { { X, Y },
-                            { frameSize.width - X - X, frameSize.height - Y - DialogTopMargin } };
-    [mStolenContentView setFrame:stolenCVRect];
-    [mStolenContentView setNeedsDisplay:YES];
-
-    [[mStolenContentView superview] setNeedsDisplay:YES];
-}
-
-- (void)onOkClicked
-{
-    Q_ASSERT(mPanelHackedWithButtons);
-    NSFontManager *fontManager = [NSFontManager sharedFontManager];
-    [self setQtFont:qfontForCocoaFont([fontManager convertFont:[fontManager selectedFont]],
-                                      *mQtFont)];
-    [self finishOffWithCode:NSOKButton];
-}
-
-- (void)onCancelClicked
-{
-    Q_ASSERT(mPanelHackedWithButtons);
-    [self finishOffWithCode:NSCancelButton];
-}
-
-- (NSFontPanel *)fontPanel
-{
-    return mFontPanel;
-}
-
-- (NSWindow *)actualPanel
-{
-    return [mStolenContentView window];
-}
-
-- (NSSize)dialogExtraSize
-{
-    // this must be recomputed each time, because sometimes the
-    // NSFontPanel has the NSDocModalWindowMask flag set, and sometimes
-    // not -- which affects the frame rect vs. content rect measurements
-
-    // take the different frame rectangles into account for dialogExtra{Width,Height}
-    NSRect someRect = { { 0.0, 0.0 }, { 100000.0, 100000.0 } };
-    NSRect sharedFontPanelContentRect = [mFontPanel contentRectForFrameRect:someRect];
-    NSRect ourPanelContentRect = [NSWindow contentRectForFrameRect:someRect styleMask:StyleMask];
-
-    NSSize result = { mDialogExtraWidth, mDialogExtraHeight };
-    result.width -= ourPanelContentRect.size.width - sharedFontPanelContentRect.size.width;
-    result.height -= ourPanelContentRect.size.height - sharedFontPanelContentRect.size.height;
-    return result;
-}
-
-- (void)setQtFont:(const QFont &)newFont
-{
-    delete mQtFont;
-    mQtFont = new QFont(newFont);
-}
-
-- (QFont)qtFont
-{
-    return *mQtFont;
-}
-
-- (void)finishOffWithCode:(NSInteger)code
-{
-#ifdef QT_MAC_USE_COCOA
-    QFontDialog *q = mPriv->fontDialog();
-    if (QWidget *parent = q->parentWidget()) {
-        if (parent->isWindow()) {
-            [qt_mac_window_for(parent) removeChildWindow:[mStolenContentView window]];
-        }
-    }
-#endif
-
-    if(code == NSOKButton)
-        mPriv->sampleEdit->setFont([self qtFont]);
-
-    if (mAppModal) {
-        mReturnCode = code;
-        [[NSApplication sharedApplication] stopModalWithCode:code];
-    } else {
-        if (code == NSOKButton)
-            mPriv->fontDialog()->accept();
-        else
-            mPriv->fontDialog()->reject();
-    }
-}
-
-- (void)cleanUpAfterMyself
-{
-    if (mPanelHackedWithButtons) {
-        NSView *ourContentView = [mFontPanel contentView];
-
-        // return stolen stuff to its rightful owner
-        [mStolenContentView removeFromSuperview];
-        [mFontPanel setContentView:mStolenContentView];
-
-        [mOkButton release];
-        [mCancelButton release];
-        [ourContentView release];
-    }
-    [mFontPanel setDelegate:nil];
-    [[NSFontManager sharedFontManager] setDelegate:nil];
-#ifdef QT_MAC_USE_COCOA
-    [[NSFontManager sharedFontManager] setTarget:nil];
-#endif
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-void QFontDialogPrivate::closeCocoaFontPanel()
-{
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *theDelegate = static_cast<QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *>(delegate);
-    NSWindow *ourPanel = [theDelegate actualPanel];
-    [ourPanel close];
-    if ([theDelegate isAppModal])
-        [ourPanel release];
-    [theDelegate cleanUpAfterMyself];
-    [theDelegate release];
-    this->delegate = 0;
-    sharedFontPanelAvailable = true;
-}
-
-void QFontDialogPrivate::setFont(void *delegate, const QFont &font)
-{
-    QMacCocoaAutoReleasePool pool;
-    QFontEngine *fe = font.d->engineForScript(QUnicodeTables::Common);
-    NSFontManager *mgr = [NSFontManager sharedFontManager];
-    const NSFont *nsFont = 0;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-    if (qstrcmp(fe->name(), "CoreText") == 0) {
-        nsFont = reinterpret_cast<const NSFont *>(static_cast<QCoreTextFontEngineMulti *>(fe)->ctfont);
-    } else
-#endif
-    {
-        int weight = 5;
-        NSFontTraitMask mask = 0;
-        if (font.style() == QFont::StyleItalic) {
-            mask |= NSItalicFontMask;
-        }
-        if (font.weight() == QFont::Bold) {
-            weight = 9;
-            mask |= NSBoldFontMask;
-        }
-
-        NSFontManager *mgr = [NSFontManager sharedFontManager];
-        QFontInfo fontInfo(font);
-        nsFont = [mgr fontWithFamily:qt_mac_QStringToNSString(fontInfo.family())
-            traits:mask
-            weight:weight
-            size:fontInfo.pointSize()];
-    }
-
-    [mgr setSelectedFont:const_cast<NSFont *>(nsFont) isMultiple:NO];
-    [static_cast<QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *>(delegate) setQtFont:font];
-}
-
-void QFontDialogPrivate::createNSFontPanelDelegate()
-{
-    if (delegate)
-        return;
-
-    sharedFontPanelAvailable = false;
-    QMacCocoaAutoReleasePool pool;
-    bool sharedFontPanelExisted = [NSFontPanel sharedFontPanelExists];
-    NSFontPanel *sharedFontPanel = [NSFontPanel sharedFontPanel];
-    [sharedFontPanel setHidesOnDeactivate:false];
-
-    // hack to ensure that QCocoaApplication's validModesForFontPanel:
-    // implementation is honored
-    if (!sharedFontPanelExisted) {
-        [sharedFontPanel makeKeyAndOrderFront:sharedFontPanel];
-        [sharedFontPanel close];
-    }
-
-    NSPanel *ourPanel = 0;
-    NSView *stolenContentView = 0;
-    NSButton *okButton = 0;
-    NSButton *cancelButton = 0;
-
-    CGFloat dialogExtraWidth = 0.0;
-    CGFloat dialogExtraHeight = 0.0;
-
-    // compute dialogExtra{Width,Height}
-    dialogExtraWidth = 2.0 * DialogSideMargin;
-    dialogExtraHeight = DialogTopMargin + ButtonTopMargin + ButtonMinHeight + ButtonBottomMargin;
-
-    // compute initial contents rectangle
-    NSRect contentRect = [sharedFontPanel contentRectForFrameRect:[sharedFontPanel frame]];
-    contentRect.size.width += dialogExtraWidth;
-    contentRect.size.height += dialogExtraHeight;
-
-    // create the new panel
-    ourPanel = [[NSPanel alloc] initWithContentRect:contentRect
-                styleMask:StyleMask
-                    backing:NSBackingStoreBuffered
-                        defer:YES];
-    [ourPanel setReleasedWhenClosed:YES];
-    stolenContentView = [sharedFontPanel contentView];
-
-    // steal the font panel's contents view
-    [stolenContentView retain];
-    [sharedFontPanel setContentView:0];
-
-    {
-        // create a new content view and add the stolen one as a subview
-        NSRect frameRect = { { 0.0, 0.0 }, { 0.0, 0.0 } };
-        NSView *ourContentView = [[NSView alloc] initWithFrame:frameRect];
-        [ourContentView addSubview:stolenContentView];
-
-        // create OK and Cancel buttons and add these as subviews
-        okButton = macCreateButton("&OK", ourContentView);
-        cancelButton = macCreateButton("Cancel", ourContentView);
-
-        [ourPanel setContentView:ourContentView];
-        [ourPanel setDefaultButtonCell:[okButton cell]];
-    }
-
-    // create the delegate and set it
-    QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *del = [[QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) alloc] initWithFontPanel:sharedFontPanel
-                                             stolenContentView:stolenContentView
-                                                      okButton:okButton
-                                                  cancelButton:cancelButton
-                                                          priv:this
-                                                    extraWidth:dialogExtraWidth
-                                                   extraHeight:dialogExtraHeight];
-    delegate = del;
-    [ourPanel setDelegate:del];
-
-    [[NSFontManager sharedFontManager] setDelegate:del];
-#ifdef QT_MAC_USE_COCOA
-    [[NSFontManager sharedFontManager] setTarget:del];
-#endif
-    setFont(del, q_func()->currentFont());
-
-    {
-        // hack to get correct initial layout
-        NSRect frameRect = [ourPanel frame];
-        frameRect.size.width += 1.0;
-        [ourPanel setFrame:frameRect display:NO];
-        frameRect.size.width -= 1.0;
-        frameRect.size = [del windowWillResize:ourPanel toSize:frameRect.size];
-        [ourPanel setFrame:frameRect display:NO];
-        [ourPanel center];
-    }
-    [del setSubwindowStacking];
-    NSString *title = @"Select font";
-    [ourPanel setTitle:title];
-}
-
-void QFontDialogPrivate::mac_nativeDialogModalHelp()
-{
-    // Copied from QFileDialogPrivate
-    // Do a queued meta-call to open the native modal dialog so it opens after the new
-    // event loop has started to execute (in QDialog::exec). Using a timer rather than
-    // a queued meta call is intentional to ensure that the call is only delivered when
-    // [NSApplication run] runs (timers are handeled special in cocoa). If NSApplication is not
-    // running (which is the case if e.g a top-most QEventLoop has been
-    // interrupted, and the second-most event loop has not yet been reactivated (regardless
-    // if [NSApplication run] is still on the stack)), showing a native modal dialog will fail.
-    if (nativeDialogInUse) {
-        Q_Q(QFontDialog);
-        QTimer::singleShot(1, q, SLOT(_q_macRunNativeAppModalPanel()));
-    }
-}
-
-// The problem with the native font dialog is that OS X does not
-// offer a proper dialog, but a panel (i.e. without Ok and Cancel buttons).
-// This means we need to "construct" a native dialog by taking the panel
-// and "adding" the buttons.
-void QFontDialogPrivate::_q_macRunNativeAppModalPanel()
-{
-    createNSFontPanelDelegate();
-    QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *del = static_cast<QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *>(delegate);
-    [del runApplicationModalPanel];
-}
-
-bool QFontDialogPrivate::showCocoaFontPanel()
-{
-    if (!sharedFontPanelAvailable)
-        return false;
-
-    Q_Q(QFontDialog);
-    QMacCocoaAutoReleasePool pool;
-    createNSFontPanelDelegate();
-    QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *del = static_cast<QT_MANGLE_NAMESPACE(QCocoaFontPanelDelegate) *>(delegate);
-    if (qt_mac_is_macsheet(q))
-        [del showWindowModalSheet:q->parentWidget()];
-    else
-        [del showModelessPanel];
-    return true;
-}
-
-bool QFontDialogPrivate::hideCocoaFontPanel()
-{
-    if (!delegate){
-        // Nothing to do. We return false to leave the question
-        // open regarding whether or not to go native:
-        return false;
-    } else {
-        closeCocoaFontPanel();
-        // Even when we hide it, we are still using a
-        // native dialog, so return true:
-        return true;
-    }
-}
-bool QFontDialogPrivate::setVisible_sys(bool visible)
-{
-    Q_Q(QFontDialog);
-    if (!visible == q->isHidden())
-        return false;
-
-    return visible ? showCocoaFontPanel() : hideCocoaFontPanel();
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qnspanelproxy_mac.mm b/src/gui/dialogs/qnspanelproxy_mac.mm
deleted file mode 100644 (file)
index ca8376b..0000000
+++ /dev/null
@@ -1,228 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qdialogbuttonbox.h>
-#if defined(Q_WS_MAC)
-#include <qt_mac_p.h>
-#include <qcocoaintrospection_p.h>
-#import <AppKit/AppKit.h>
-#import <Foundation/Foundation.h>
-#import <objc/objc-class.h>
-
-QT_BEGIN_NAMESPACE
-static QWidget *currentWindow = 0;
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QNSPanelProxy);
-
-@interface QT_MANGLE_NAMESPACE(QNSPanelProxy) : NSWindow {
-}
-- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
-    backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation;
-- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
-    backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation screen:(NSScreen *)screen;
-- (id)qt_fakeInitWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
-    backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation;
-- (id)qt_fakeInitWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
-    backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation screen:(NSScreen *)screen;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSPanelProxy)
-- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
-      backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation
-{
-    // remove evil flag
-    windowStyle &= ~NSUtilityWindowMask;
-       self = [self qt_fakeInitWithContentRect:contentRect styleMask:windowStyle
-                                       backing:bufferingType defer:deferCreation];
-    return self;
-}
-
-- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
-      backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation screen:(NSScreen *)screen
-{
-    // remove evil flag
-    windowStyle &= ~NSUtilityWindowMask;
-       return [self qt_fakeInitWithContentRect:contentRect styleMask:windowStyle
-                                       backing:bufferingType defer:deferCreation screen:screen];
-}
-
-- (id)qt_fakeInitWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
-    backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation
-{
-    Q_UNUSED(contentRect);
-    Q_UNUSED(windowStyle);
-    Q_UNUSED(bufferingType);
-    Q_UNUSED(deferCreation);
-    return nil;
-}
-
-- (id)qt_fakeInitWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)windowStyle
-    backing:(NSBackingStoreType)bufferingType defer:(BOOL)deferCreation screen:(NSScreen *)screen
-{
-    Q_UNUSED(contentRect);
-    Q_UNUSED(windowStyle);
-    Q_UNUSED(bufferingType);
-    Q_UNUSED(deferCreation);
-    Q_UNUSED(screen);
-    return nil;
-}
-@end
-
-@class QT_MANGLE_NAMESPACE(QNSWindowProxy);
-
-@interface QT_MANGLE_NAMESPACE(QNSWindowProxy) : NSWindow {
-}
-- (void)setTitle:(NSString *)title;
-- (void)qt_fakeSetTitle:(NSString *)title;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSWindowProxy)
-- (void)setTitle:(NSString *)title
-{
-    QCFString cftitle(currentWindow->windowTitle());
-
-    // evil reverse engineering
-    if ([title isEqualToString:@"Print"]
-            || [title isEqualToString:@"Page Setup"]
-            || [[self className] isEqualToString:@"PMPrintingWindow"])
-        title = (NSString *)(static_cast<CFStringRef>(cftitle));
-    return [self qt_fakeSetTitle:title];
-}
-
-- (void)qt_fakeSetTitle:(NSString *)title
-{
-    Q_UNUSED(title);
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-/*
-    Intercept the NSColorPanel constructor if the shared
-    color panel doesn't exist yet. What's going on here is
-    quite wacky, because we want to override the NSPanel
-    constructor and at the same time call the old NSPanel
-    constructor. So what we do is we effectively rename the
-    old NSPanel constructor qt_fakeInitWithContentRect:...
-    and have the new one call the old one.
-*/
-void macStartInterceptNSPanelCtor()
-{
-    qt_cocoa_change_implementation(
-            [NSPanel class],
-            @selector(initWithContentRect:styleMask:backing:defer:),
-            [QT_MANGLE_NAMESPACE(QNSPanelProxy) class],
-            @selector(initWithContentRect:styleMask:backing:defer:),
-            @selector(qt_fakeInitWithContentRect:styleMask:backing:defer:));
-    qt_cocoa_change_implementation(
-            [NSPanel class],
-            @selector(initWithContentRect:styleMask:backing:defer:screen:),
-            [QT_MANGLE_NAMESPACE(QNSPanelProxy) class],
-            @selector(initWithContentRect:styleMask:backing:defer:screen:),
-            @selector(qt_fakeInitWithContentRect:styleMask:backing:defer:screen:));
-}
-
-/*
-    Restore things as they were.
-*/
-void macStopInterceptNSPanelCtor()
-{
-    qt_cocoa_change_back_implementation(
-            [NSPanel class],
-            @selector(initWithContentRect:styleMask:backing:defer:screen:),
-            @selector(qt_fakeInitWithContentRect:styleMask:backing:defer:screen:));
-    qt_cocoa_change_back_implementation(
-            [NSPanel class],
-            @selector(initWithContentRect:styleMask:backing:defer:),
-            @selector(qt_fakeInitWithContentRect:styleMask:backing:defer:));
-}
-
-/*
-    Intercept the NSPrintPanel and NSPageLayout setTitle: calls. The
-    hack is similar as for NSColorPanel above.
-*/
-void macStartInterceptWindowTitle(QWidget *window)
-{
-    currentWindow = window;
-    qt_cocoa_change_implementation(
-            [NSWindow class],
-            @selector(setTitle:),
-            [QT_MANGLE_NAMESPACE(QNSWindowProxy) class],
-            @selector(setTitle:),
-            @selector(qt_fakeSetTitle:));
-}
-
-/*
-    Restore things as they were.
-*/
-void macStopInterceptWindowTitle()
-{
-    currentWindow = 0;
-    qt_cocoa_change_back_implementation(
-            [NSWindow class],
-            @selector(setTitle:),
-            @selector(qt_fakeSetTitle:));
-}
-
-/*
-    Doesn't really belong in here.
-*/
-NSButton *macCreateButton(const char *text, NSView *superview)
-{
-    static const NSRect buttonFrameRect = { { 0.0, 0.0 }, { 0.0, 0.0 } };
-
-    NSButton *button = [[NSButton alloc] initWithFrame:buttonFrameRect];
-    [button setButtonType:NSMomentaryLightButton];
-    [button setBezelStyle:NSRoundedBezelStyle];
-    [button setTitle:(NSString*)(CFStringRef)QCFString(QDialogButtonBox::tr(text)
-                                                       .remove(QLatin1Char('&')))];
-    [[button cell] setFont:[NSFont systemFontOfSize:
-            [NSFont systemFontSizeForControlSize:NSRegularControlSize]]];
-    [superview addSubview:button];
-    return button;
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/dialogs/qpagesetupdialog_mac.mm b/src/gui/dialogs/qpagesetupdialog_mac.mm
deleted file mode 100644 (file)
index 69ccf6e..0000000
+++ /dev/null
@@ -1,315 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qpagesetupdialog.h"
-
-#include <qhash.h>
-#include <qapplication_p.h>
-#include <qprintengine_mac_p.h>
-#include <qabstractpagesetupdialog_p.h>
-
-#ifndef QT_NO_PRINTDIALOG
-
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate);
-
-@interface QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate) : NSObject {
-    QMacPrintEnginePrivate *pe;
-}
-- (id)initWithMacPrintEngine:(QMacPrintEnginePrivate *)printEngine;
-- (void)pageLayoutDidEnd:(NSPageLayout *)pageLayout
-        returnCode:(int)returnCode contextInfo:(void *)contextInfo;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate)
-- (id)initWithMacPrintEngine:(QMacPrintEnginePrivate *)printEngine
-{
-    self = [super init];
-    if (self) {
-        pe = printEngine;
-    }
-    return self;
-
-}
-- (void)pageLayoutDidEnd:(NSPageLayout *)pageLayout
-        returnCode:(int)returnCode contextInfo:(void *)contextInfo
-{
-    Q_UNUSED(pageLayout);
-    QPageSetupDialog *dialog = static_cast<QPageSetupDialog *>(contextInfo);
-    if (returnCode == NSOKButton) {
-        PMRect paperRect;
-        PMGetUnadjustedPaperRect(pe->format, &paperRect);
-        pe->customSize = QSizeF(paperRect.right - paperRect.left,
-                                paperRect.bottom - paperRect.top);
-    }
-    dialog->done((returnCode == NSOKButton) ? QDialog::Accepted : QDialog::Rejected);
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-extern void macStartInterceptWindowTitle(QWidget *window);
-extern void macStopInterceptWindowTitle();
-
-class QPageSetupDialogPrivate : public QAbstractPageSetupDialogPrivate
-{
-    Q_DECLARE_PUBLIC(QPageSetupDialog)
-
-public:
-    QPageSetupDialogPrivate() : ep(0)
-#ifndef QT_MAC_USE_COCOA
-    ,upp(0)
-#else
-    ,pageLayout(0)
-#endif
-    {}
-
-    ~QPageSetupDialogPrivate() {
-#ifndef QT_MAC_USE_COCOA
-        if (upp) {
-            DisposePMSheetDoneUPP(upp);
-            upp = 0;
-        }
-        QHash<PMPrintSession, QPageSetupDialogPrivate *>::iterator it = sheetCallbackMap.begin();
-        while (it != sheetCallbackMap.end()) {
-            if (it.value() == this) {
-                it = sheetCallbackMap.erase(it);
-            } else {
-                ++it;
-            }
-        }
-#endif
-    }
-
-#ifndef QT_MAC_USE_COCOA
-    void openCarbonPageLayout(Qt::WindowModality modality);
-    void closeCarbonPageLayout();
-    static void pageSetupDialogSheetDoneCallback(PMPrintSession printSession, WindowRef /*documentWindow*/, Boolean accepted) {
-        QPageSetupDialogPrivate *priv = sheetCallbackMap.value(printSession);
-        if (!priv) {
-            qWarning("%s:%d: QPageSetupDialog::exec: Could not retrieve data structure, "
-                     "you most likely now have an infinite modal loop", __FILE__, __LINE__);
-            return;
-        }
-        priv->q_func()->done(accepted ? QDialog::Accepted : QDialog::Rejected);
-    }
-#else
-    void openCocoaPageLayout(Qt::WindowModality modality);
-    void closeCocoaPageLayout();
-#endif
-
-    QMacPrintEnginePrivate *ep;
-#ifndef QT_MAC_USE_COCOA
-    PMSheetDoneUPP upp;
-    static QHash<PMPrintSession, QPageSetupDialogPrivate*> sheetCallbackMap;
-#else
-    NSPageLayout *pageLayout;
-#endif
-};
-
-#ifndef QT_MAC_USE_COCOA
-QHash<PMPrintSession, QPageSetupDialogPrivate*> QPageSetupDialogPrivate::sheetCallbackMap;
-void QPageSetupDialogPrivate::openCarbonPageLayout(Qt::WindowModality modality)
-{
-    Q_Q(QPageSetupDialog);
-    // If someone is reusing a QPrinter object, the end released all our old
-    // information. In this case, we must reinitialize.
-    if (ep->session == 0)
-        ep->initialize();
-
-    sheetCallbackMap.insert(ep->session, this);
-    if (modality == Qt::ApplicationModal) {
-       QWidget modal_widg(0, Qt::Window);
-        modal_widg.setObjectName(QLatin1String(__FILE__ "__modal_dlg"));
-        modal_widg.createWinId();
-       QApplicationPrivate::enterModal(&modal_widg);
-        QApplicationPrivate::native_modal_dialog_active = true;
-        Boolean accepted;
-        PMSessionPageSetupDialog(ep->session, ep->format, &accepted);
-       QApplicationPrivate::leaveModal(&modal_widg);
-        QApplicationPrivate::native_modal_dialog_active = false;
-        pageSetupDialogSheetDoneCallback(ep->session, 0, accepted);
-    } else {
-        // Window Modal means that we use a sheet at the moment, there's no other way to do it correctly.
-        if (!upp)
-            upp = NewPMSheetDoneUPP(QPageSetupDialogPrivate::pageSetupDialogSheetDoneCallback);
-        PMSessionUseSheets(ep->session, qt_mac_window_for(q->parentWidget()), upp);
-        Boolean unused;
-        PMSessionPageSetupDialog(ep->session, ep->format, &unused);
-    }
-}
-
-void QPageSetupDialogPrivate::closeCarbonPageLayout()
-{
-    // if the margins have changed, we have to use the margins from the new
-    // PMFormat object
-    if (q_func()->result() == QDialog::Accepted) {
-        PMPaper paper;
-        PMPaperMargins margins;
-        PMGetPageFormatPaper(ep->format, &paper);
-        PMPaperGetMargins(paper, &margins);
-        ep->leftMargin = margins.left;
-        ep->topMargin = margins.top;
-        ep->rightMargin = margins.right;
-        ep->bottomMargin = margins.bottom;
-
-       PMRect paperRect;
-       PMGetUnadjustedPaperRect(ep->format, &paperRect);
-       ep->customSize = QSizeF(paperRect.right - paperRect.left,
-                               paperRect.bottom - paperRect.top);
-    }
-    sheetCallbackMap.remove(ep->session);
-}
-#else
-void QPageSetupDialogPrivate::openCocoaPageLayout(Qt::WindowModality modality)
-{
-    Q_Q(QPageSetupDialog);
-
-    // If someone is reusing a QPrinter object, the end released all our old
-    // information. In this case, we must reinitialize.
-    if (ep->session == 0)
-        ep->initialize();
-
-    macStartInterceptWindowTitle(q);
-    pageLayout = [NSPageLayout pageLayout];
-    // Keep a copy to this since we plan on using it for a bit.
-    [pageLayout retain];
-    QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate) *delegate = [[QT_MANGLE_NAMESPACE(QCocoaPageLayoutDelegate) alloc] initWithMacPrintEngine:ep];
-
-    if (modality == Qt::ApplicationModal) {
-        int rval = [pageLayout runModalWithPrintInfo:ep->printInfo];
-        [delegate pageLayoutDidEnd:pageLayout returnCode:rval contextInfo:q];
-    } else {
-        Q_ASSERT(q->parentWidget());
-        [pageLayout beginSheetWithPrintInfo:ep->printInfo
-                             modalForWindow:qt_mac_window_for(q->parentWidget())
-                                   delegate:delegate
-                             didEndSelector:@selector(pageLayoutDidEnd:returnCode:contextInfo:)
-                                contextInfo:q];
-    }
-
-    macStopInterceptWindowTitle();
-}
-
-void QPageSetupDialogPrivate::closeCocoaPageLayout()
-{
-    // NSPageLayout can change the session behind our back and then our
-    // d->ep->session object will become a dangling pointer. Update it
-    // based on the "current" session
-    ep->session = static_cast<PMPrintSession>([ep->printInfo PMPrintSession]);
-
-    [pageLayout release];
-    pageLayout = 0;
-}
-#endif
-
-QPageSetupDialog::QPageSetupDialog(QPrinter *printer, QWidget *parent)
-    : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), printer, parent)
-{
-    Q_D(QPageSetupDialog);
-    d->ep = static_cast<QMacPrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPageSetupDialog::QPageSetupDialog(QWidget *parent)
-    : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), 0, parent)
-{
-    Q_D(QPageSetupDialog);
-    d->ep = static_cast<QMacPrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-void QPageSetupDialog::setVisible(bool visible)
-{
-    Q_D(QPageSetupDialog);
-
-    if (d->printer->outputFormat() != QPrinter::NativeFormat)
-        return;
-
-#ifndef QT_MAC_USE_COCOA
-    bool isCurrentlyVisible = d->sheetCallbackMap.contains(d->ep->session);
-#else
-    bool isCurrentlyVisible = (d->pageLayout != 0);
-#endif
-    if (!visible == !isCurrentlyVisible)
-        return;
-
-    if (visible) {
-#ifndef QT_MAC_USE_COCOA
-        d->openCarbonPageLayout(parentWidget() ? Qt::WindowModal
-                                               : Qt::ApplicationModal);
-#else
-        d->openCocoaPageLayout(parentWidget() ? Qt::WindowModal
-                                              : Qt::ApplicationModal);
-#endif
-        return;
-    } else {
-#ifndef QT_MAC_USE_COCOA
-        d->closeCarbonPageLayout();
-#else
-        if (d->pageLayout) {
-            d->closeCocoaPageLayout();
-            return;
-        }
-#endif
-    }
-}
-
-int QPageSetupDialog::exec()
-{
-    Q_D(QPageSetupDialog);
-
-    if (d->printer->outputFormat() != QPrinter::NativeFormat)
-        return Rejected;
-
-#ifndef QT_MAC_USE_COCOA
-    d->openCarbonPageLayout(Qt::ApplicationModal);
-    d->closeCarbonPageLayout();
-#else
-    QMacCocoaAutoReleasePool pool;
-    d->openCocoaPageLayout(Qt::ApplicationModal);
-    d->closeCocoaPageLayout();
-#endif
-    return result();
-}
-
-QT_END_NAMESPACE
-
-#endif /* QT_NO_PRINTDIALOG */
diff --git a/src/gui/dialogs/qpagesetupdialog_win.cpp b/src/gui/dialogs/qpagesetupdialog_win.cpp
deleted file mode 100644 (file)
index 619661e..0000000
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qpagesetupdialog.h"
-
-#ifndef QT_NO_PRINTDIALOG
-#include <qapplication.h>
-
-#include <qprintengine_win_p.h>
-#include <qabstractpagesetupdialog_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QPageSetupDialogPrivate : public QAbstractPageSetupDialogPrivate
-{
-};
-
-QPageSetupDialog::QPageSetupDialog(QPrinter *printer, QWidget *parent)
-    : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), printer, parent)
-{
-}
-
-QPageSetupDialog::QPageSetupDialog(QWidget *parent)
-    : QAbstractPageSetupDialog(*(new QPageSetupDialogPrivate), 0, parent)
-{
-}
-
-int QPageSetupDialog::exec()
-{
-    Q_D(QPageSetupDialog);
-
-    if (d->printer->outputFormat() != QPrinter::NativeFormat)
-        return Rejected;
-
-    QWin32PrintEngine *engine = static_cast<QWin32PrintEngine*>(d->printer->paintEngine());
-    QWin32PrintEnginePrivate *ep = static_cast<QWin32PrintEnginePrivate *>(engine->d_ptr.data());
-
-    PAGESETUPDLG psd;
-    memset(&psd, 0, sizeof(PAGESETUPDLG));
-    psd.lStructSize = sizeof(PAGESETUPDLG);
-
-    // we need a temp DEVMODE struct if we don't have a global DEVMODE
-    HGLOBAL hDevMode = 0;
-    int devModeSize = 0;
-    if (!ep->globalDevMode) {
-        devModeSize = sizeof(DEVMODE) + ep->devMode->dmDriverExtra;
-        hDevMode = GlobalAlloc(GHND, devModeSize);
-        if (hDevMode) {
-            void *dest = GlobalLock(hDevMode);
-            memcpy(dest, ep->devMode, devModeSize);
-            GlobalUnlock(hDevMode);
-        }
-        psd.hDevMode = hDevMode;
-    } else {
-        psd.hDevMode = ep->devMode;
-    }
-
-    HGLOBAL *tempDevNames = ep->createDevNames();
-    psd.hDevNames = tempDevNames;
-
-    QWidget *parent = parentWidget();
-    parent = parent ? parent->window() : QApplication::activeWindow();
-    Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created));
-    psd.hwndOwner = parent ? parent->winId() : 0;
-
-    psd.Flags = PSD_MARGINS;
-    double multiplier = 1;
-    switch (QLocale::system().measurementSystem()) {
-    case QLocale::MetricSystem:
-        psd.Flags |= PSD_INHUNDREDTHSOFMILLIMETERS;
-        multiplier = 1;
-        break;
-    case QLocale::ImperialSystem:
-        psd.Flags |= PSD_INTHOUSANDTHSOFINCHES;
-        multiplier = 25.4/10;
-        break;
-    }
-
-    QRect marginRect = ep->getPageMargins();
-    psd.rtMargin.left   = marginRect.left()   / multiplier;
-    psd.rtMargin.top    = marginRect.top()    / multiplier;
-    psd.rtMargin.right  = marginRect.width()  / multiplier;;
-    psd.rtMargin.bottom = marginRect.height() / multiplier;;
-
-    bool result = PageSetupDlg(&psd);
-    if (result) {
-        ep->readDevnames(psd.hDevNames);
-        ep->readDevmode(psd.hDevMode);
-
-        QRect theseMargins = QRect(psd.rtMargin.left   * multiplier,
-                                   psd.rtMargin.top    * multiplier,
-                                   psd.rtMargin.right  * multiplier,
-                                   psd.rtMargin.bottom * multiplier);
-
-        if (theseMargins != marginRect) {
-            ep->setPageMargins(psd.rtMargin.left   * multiplier,
-                               psd.rtMargin.top    * multiplier,
-                               psd.rtMargin.right  * multiplier,
-                               psd.rtMargin.bottom * multiplier);
-        }
-
-        ep->updateCustomPaperSize();
-
-        // copy from our temp DEVMODE struct
-        if (!ep->globalDevMode && hDevMode) {
-            void *src = GlobalLock(hDevMode);
-            memcpy(ep->devMode, src, devModeSize);
-            GlobalUnlock(hDevMode);
-        }
-    }
-
-    if (!ep->globalDevMode && hDevMode)
-        GlobalFree(hDevMode);
-    GlobalFree(tempDevNames);
-    done(result);
-    return result;
-}
-
-void QPageSetupDialog::setVisible(bool visible)
-{
-    if (!visible)
-        return;
-    exec();
-}
-
-QT_END_NAMESPACE
-#endif
diff --git a/src/gui/dialogs/qprintdialog_mac.mm b/src/gui/dialogs/qprintdialog_mac.mm
deleted file mode 100644 (file)
index d4482a3..0000000
+++ /dev/null
@@ -1,426 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QT_NO_PRINTDIALOG
-
-#include <qt_mac_p.h>
-
-#include <qhash.h>
-#include <qprintdialog.h>
-#include <qapplication_p.h>
-#include <qabstractprintdialog_p.h>
-#include <qprintengine_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QPrintDialogPrivate : public QAbstractPrintDialogPrivate
-{
-    Q_DECLARE_PUBLIC(QPrintDialog)
-
-public:
-    QPrintDialogPrivate() : ep(0), printPanel(0)
-#ifndef QT_MAC_USE_COCOA
-       ,upp(0)
-#endif
-       {}
-#ifndef QT_MAC_USE_COCOA
-    ~QPrintDialogPrivate() {
-        if (upp) {
-            DisposePMSheetDoneUPP(upp);
-            upp = 0;
-        }
-        QHash<PMPrintSession, QPrintDialogPrivate *>::iterator it = sheetCallbackMap.begin();
-        while (it != sheetCallbackMap.end()) {
-            if (it.value() == this) {
-                it = sheetCallbackMap.erase(it);
-            } else {
-                ++it;
-            }
-        }
-    }
-#endif
-
-#ifndef QT_MAC_USE_COCOA
-    void openCarbonPrintPanel(Qt::WindowModality modality);
-    void closeCarbonPrintPanel();
-    static void printDialogSheetDoneCallback(PMPrintSession printSession, WindowRef /*documentWindow*/, Boolean accepted) {
-        QPrintDialogPrivate *priv = sheetCallbackMap.value(printSession);
-        if (!priv) {
-            qWarning("%s:%d: QPrintDialog::exec: Could not retrieve data structure, "
-                     "you most likely now have an infinite loop", __FILE__, __LINE__);
-            return;
-        }
-        priv->q_func()->done(accepted ? QDialog::Accepted : QDialog::Rejected);
-        priv->closeCarbonPrintPanel();
-    }
-#else
-    void openCocoaPrintPanel(Qt::WindowModality modality);
-    void closeCocoaPrintPanel();
-#endif
-    void initBeforeRun();
-
-    inline QPrintDialog *printDialog() { return q_func(); }
-
-    // stubs for the private signals
-    inline void _q_collapseOrExpandDialog() {}
-    inline void _q_chbPrintLastFirstToggled(bool) {}
-#ifndef QT_NO_MESSAGEBOX
-    inline void _q_checkFields() {}
-#endif
-
-    QMacPrintEnginePrivate *ep;
-    NSPrintPanel *printPanel;
-#ifndef QT_MAC_USE_COCOA
-    PMSheetDoneUPP upp;
-    static QHash<PMPrintSession, QPrintDialogPrivate *> sheetCallbackMap;
-#endif
-};
-
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-
-@class QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate);
-
-@interface QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate) : NSObject {
-}
-- (void)printPanelDidEnd:(NSPrintPanel *)printPanel
-        returnCode:(int)returnCode contextInfo:(void *)contextInfo;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate)
-- (void)printPanelDidEnd:(NSPrintPanel *)printPanel
-        returnCode:(int)returnCode contextInfo:(void *)contextInfo
-{
-    Q_UNUSED(printPanel);
-
-    QPrintDialogPrivate *d = static_cast<QPrintDialogPrivate *>(contextInfo);
-    QPrintDialog *dialog = d->printDialog();
-
-    if (returnCode == NSOKButton) {
-        UInt32 frompage, topage;
-        PMGetFirstPage(d->ep->settings, &frompage);
-        PMGetLastPage(d->ep->settings, &topage);
-        topage = qMin(UInt32(INT_MAX), topage);
-        dialog->setFromTo(frompage, topage);
-
-        // OK, I need to map these values back let's see
-        // If from is 1 and to is INT_MAX, then print it all
-        // (Apologies to the folks with more than INT_MAX pages)
-        if (dialog->fromPage() == 1 && dialog->toPage() == INT_MAX) {
-            dialog->setPrintRange(QPrintDialog::AllPages);
-            dialog->setFromTo(0, 0);
-        } else {
-            dialog->setPrintRange(QPrintDialog::PageRange); // In a way a lie, but it shouldn't hurt.
-            // Carbon hands us back a very large number here even for ALL, set it to max
-            // in that case to follow the behavior of the other print dialogs.
-            if (dialog->maxPage() < dialog->toPage())
-                dialog->setFromTo(dialog->fromPage(), dialog->maxPage());
-        }
-        // Keep us in sync with file output
-        PMDestinationType dest;
-
-        // If the user selected print to file, the session has been
-        // changed behind our back and our d->ep->session object is a
-        // dangling pointer. Update it based on the "current" session
-        d->ep->session = static_cast<PMPrintSession>([d->ep->printInfo PMPrintSession]);
-
-        PMSessionGetDestinationType(d->ep->session, d->ep->settings, &dest);
-        if (dest == kPMDestinationFile) {
-            QCFType<CFURLRef> file;
-            PMSessionCopyDestinationLocation(d->ep->session, d->ep->settings, &file);
-            UInt8 localFile[2048];  // Assuming there's a POSIX file system here.
-            CFURLGetFileSystemRepresentation(file, true, localFile, sizeof(localFile));
-            d->ep->outputFilename
-                = QString::fromUtf8(reinterpret_cast<const char *>(localFile));
-        } else {
-            // Keep output format.
-            QPrinter::OutputFormat format;
-            format = d->printer->outputFormat();
-            d->printer->setOutputFileName(QString());
-            d->printer->setOutputFormat(format);
-        }
-    }
-
-    dialog->done((returnCode == NSOKButton) ? QDialog::Accepted : QDialog::Rejected);
-}
-@end
-
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern void macStartInterceptWindowTitle(QWidget *window);
-extern void macStopInterceptWindowTitle();
-
-
-void QPrintDialogPrivate::initBeforeRun()
-{
-    Q_Q(QPrintDialog);
-    // If someone is reusing a QPrinter object, the end released all our old
-    // information. In this case, we must reinitialize.
-    if (ep->session == 0)
-        ep->initialize();
-
-
-    // It seems the only way that PM lets you use all is if the minimum
-    // for the page range is 1. This _kind of_ makes sense if you think about
-    // it. However, calling PMSetFirstPage() or PMSetLastPage() always enforces
-    // the range.
-    PMSetPageRange(ep->settings, q->minPage(), q->maxPage());
-    if (q->printRange() == QAbstractPrintDialog::PageRange) {
-        PMSetFirstPage(ep->settings, q->fromPage(), false);
-        PMSetLastPage(ep->settings, q->toPage(), false);
-    }
-}
-
-#ifndef QT_MAC_USE_COCOA
-QHash<PMPrintSession, QPrintDialogPrivate *> QPrintDialogPrivate::sheetCallbackMap;
-void QPrintDialogPrivate::openCarbonPrintPanel(Qt::WindowModality modality)
-{
-    Q_Q(QPrintDialog);
-    initBeforeRun();
-    sheetCallbackMap.insert(ep->session, this);
-    if (modality == Qt::ApplicationModal) {
-        QWidget modal_widg(0, Qt::Window);
-        modal_widg.setObjectName(QLatin1String(__FILE__ "__modal_dlg"));
-        modal_widg.createWinId();
-        QApplicationPrivate::enterModal(&modal_widg);
-        QApplicationPrivate::native_modal_dialog_active = true;
-        Boolean acceptStatus;
-        PMSessionPrintDialog(ep->session, ep->settings, ep->format, &acceptStatus);
-        QApplicationPrivate::leaveModal(&modal_widg);
-        QApplicationPrivate::native_modal_dialog_active = false;
-        printDialogSheetDoneCallback(ep->session, 0, acceptStatus);
-    } else {
-        // Window Modal means that we use a sheet at the moment, there's no other way to do it correctly.
-        if (!upp)
-            upp = NewPMSheetDoneUPP(QPrintDialogPrivate::printDialogSheetDoneCallback);
-        PMSessionUseSheets(ep->session, qt_mac_window_for(q->parentWidget()), upp);
-        QApplicationPrivate::native_modal_dialog_active = true;
-        Boolean unused;
-        PMSessionPrintDialog(ep->session, ep->settings, ep->format, &unused);
-    }
-}
-
-void QPrintDialogPrivate::closeCarbonPrintPanel()
-{
-    Q_Q(QPrintDialog);
-    QApplicationPrivate::native_modal_dialog_active = false;
-    if (q->result() == QDialog::Accepted) {
-        UInt32 frompage, topage;
-        PMGetFirstPage(ep->settings, &frompage);
-        PMGetLastPage(ep->settings, &topage);
-        topage = qMin(UInt32(INT_MAX), topage);
-        q->setFromTo(frompage, topage);
-
-        // OK, I need to map these values back let's see
-        // If from is 1 and to is INT_MAX, then print it all
-        // (Apologies to the folks with more than INT_MAX pages)
-        // ...that's a joke.
-        if (q->fromPage() == 1 && q->toPage() == INT_MAX) {
-            q->setPrintRange(QAbstractPrintDialog::AllPages);
-            q->setFromTo(0,0);
-        } else {
-            q->setPrintRange(QAbstractPrintDialog::PageRange); // In a way a lie, but it shouldn't hurt.
-            // Carbon hands us back a very large number here even for ALL, set it to max
-            // in that case to follow the behavior of the other print dialogs.
-            if (q->maxPage() < q->toPage())
-                q->setFromTo(q->fromPage(), q->maxPage());
-        }
-        // Keep us in sync with file output
-        PMDestinationType dest;
-        PMSessionGetDestinationType(ep->session, ep->settings, &dest);
-        if (dest == kPMDestinationFile) {
-            QCFType<CFURLRef> file;
-            PMSessionCopyDestinationLocation(ep->session, ep->settings, &file);
-            UInt8 localFile[2048];  // Assuming there's a POSIX file system here.
-            CFURLGetFileSystemRepresentation(file, true, localFile, sizeof(localFile));
-            ep->outputFilename = QString::fromUtf8(reinterpret_cast<const char *>(localFile));
-        } else {
-            ep->outputFilename = QString();
-        }
-    }
-    sheetCallbackMap.remove(ep->session);
-}
-#else
-void QPrintDialogPrivate::openCocoaPrintPanel(Qt::WindowModality modality)
-{
-    Q_Q(QPrintDialog);
-
-    initBeforeRun();
-
-    QPrintDialog::PrintDialogOptions qtOptions = q->options();
-    NSPrintPanelOptions macOptions = NSPrintPanelShowsCopies;
-    if (qtOptions & QPrintDialog::PrintPageRange)
-        macOptions |= NSPrintPanelShowsPageRange;
-    if (qtOptions & QPrintDialog::PrintShowPageSize)
-        macOptions |= NSPrintPanelShowsPaperSize | NSPrintPanelShowsPageSetupAccessory
-                      | NSPrintPanelShowsOrientation;
-
-    macStartInterceptWindowTitle(q);
-    printPanel = [NSPrintPanel printPanel];
-    QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate) *delegate = [[QT_MANGLE_NAMESPACE(QCocoaPrintPanelDelegate) alloc] init];
-
-    // Call processEvents in case the event dispatcher has been interrupted, and needs to do
-    // cleanup of modal sessions. Do this before showing the native dialog, otherwise it will
-    // close down during the cleanup (QTBUG-17913):
-    qApp->processEvents(QEventLoop::ExcludeUserInputEvents, QEventLoop::ExcludeSocketNotifiers);
-
-    [printPanel setOptions:macOptions];
-
-    if (modality == Qt::ApplicationModal || !q->parentWidget()) {
-        if (modality == Qt::NonModal)
-            qWarning("QPrintDialog is required to be modal on OS X");
-        int rval = [printPanel runModalWithPrintInfo:ep->printInfo];
-        [delegate printPanelDidEnd:printPanel returnCode:rval contextInfo:this];
-    } else {
-        Q_ASSERT(q->parentWidget());
-        NSWindow *windowRef = qt_mac_window_for(q->parentWidget());
-        [printPanel beginSheetWithPrintInfo:ep->printInfo
-                             modalForWindow:windowRef
-                                   delegate:delegate
-                             didEndSelector:@selector(printPanelDidEnd:returnCode:contextInfo:)
-                                contextInfo:this];
-    }
-
-    macStopInterceptWindowTitle();
-}
-
-void QPrintDialogPrivate::closeCocoaPrintPanel()
-{
-    // ###
-}
-#endif
-
-static bool warnIfNotNative(QPrinter *printer)
-{
-    if (printer->outputFormat() != QPrinter::NativeFormat) {
-        qWarning("QPrintDialog: Cannot be used on non-native printers");
-        return false;
-    }
-    return true;
-}
-
-
-QPrintDialog::QPrintDialog(QPrinter *printer, QWidget *parent)
-    : QAbstractPrintDialog(*(new QPrintDialogPrivate), printer, parent)
-{
-    Q_D(QPrintDialog);
-    if (!warnIfNotNative(d->printer))
-        return;
-    d->ep = static_cast<QMacPrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPrintDialog::QPrintDialog(QWidget *parent)
-    : QAbstractPrintDialog(*(new QPrintDialogPrivate), 0, parent)
-{
-    Q_D(QPrintDialog);
-    if (!warnIfNotNative(d->printer))
-        return;
-    d->ep = static_cast<QMacPrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPrintDialog::~QPrintDialog()
-{
-}
-
-int QPrintDialog::exec()
-{
-    Q_D(QPrintDialog);
-    if (!warnIfNotNative(d->printer))
-        return QDialog::Rejected;
-
-#ifndef QT_MAC_USE_COCOA
-    d->openCarbonPrintPanel(Qt::ApplicationModal);
-#else
-    QMacCocoaAutoReleasePool pool;
-
-    d->openCocoaPrintPanel(Qt::ApplicationModal);
-    d->closeCocoaPrintPanel();
-#endif
-    return result();
-}
-
-/*!
-    \reimp
-*/
-void QPrintDialog::setVisible(bool visible)
-{
-    Q_D(QPrintDialog);
-
-    bool isCurrentlyVisible = (d->printPanel != 0);
-
-    if (!visible == !isCurrentlyVisible)
-        return;
-
-    if (d->printer->outputFormat() != QPrinter::NativeFormat)
-        return;
-
-    if (visible) {
-#ifndef QT_MAC_USE_COCOA
-        d->openCarbonPrintPanel(parentWidget() ? Qt::WindowModal
-                                               : Qt::ApplicationModal);
-#else
-        d->openCocoaPrintPanel(parentWidget() ? Qt::WindowModal
-                                              : Qt::ApplicationModal);
-#endif
-        return;
-    } else {
-        if (d->printPanel) {
-#ifndef QT_MAC_USE_COCOA
-            d->closeCarbonPrintPanel();
-#else
-            d->closeCocoaPrintPanel();
-#endif
-            return;
-        }
-    }
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qprintdialog.h"
-#include "qrc_qprintdialog.cpp"
-
-#endif // QT_NO_PRINTDIALOG
diff --git a/src/gui/dialogs/qprintdialog_win.cpp b/src/gui/dialogs/qprintdialog_win.cpp
deleted file mode 100644 (file)
index 4fdf45a..0000000
+++ /dev/null
@@ -1,318 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QT_NO_PRINTDIALOG
-
-#include "qprintdialog.h"
-
-#include <qwidget.h>
-#include <qapplication.h>
-#include <qmessagebox.h>
-#include <qapplication_p.h>
-
-#include <qabstractprintdialog_p.h>
-#include <qprintengine_win_p.h>
-#include <qprinter_p.h>
-
-#if !defined(PD_NOCURRENTPAGE)
-#define PD_NOCURRENTPAGE    0x00800000
-#define PD_RESULT_PRINT        1
-#define PD_RESULT_APPLY        2
-#define START_PAGE_GENERAL  0XFFFFFFFF
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern void qt_win_eatMouseMove();
-
-class QPrintDialogPrivate : public QAbstractPrintDialogPrivate
-{
-    Q_DECLARE_PUBLIC(QPrintDialog)
-public:
-    QPrintDialogPrivate()
-        : ep(0)
-    {
-    }
-
-    int openWindowsPrintDialogModally();
-
-    // stubs for the private signals
-    inline void _q_collapseOrExpandDialog() {}
-    inline void _q_chbPrintLastFirstToggled(bool) {}
-#ifndef QT_NO_MESSAGEBOX
-    inline void _q_checkFields() {}
-#endif
-
-    QWin32PrintEnginePrivate *ep;
-};
-
-static void qt_win_setup_PRINTDLGEX(PRINTDLGEX *pd, QWidget *parent,
-                                    QPrintDialog *pdlg,
-                                    QPrintDialogPrivate *d, HGLOBAL *tempDevNames)
-{
-    DEVMODE *devMode = d->ep->devMode;
-
-    if (devMode) {
-        int size = sizeof(DEVMODE) + devMode->dmDriverExtra;
-        pd->hDevMode = GlobalAlloc(GHND, size);
-        {
-            void *dest = GlobalLock(pd->hDevMode);
-            memcpy(dest, devMode, size);
-            GlobalUnlock(pd->hDevMode);
-        }
-    } else {
-        pd->hDevMode = NULL;
-    }
-    pd->hDevNames  = tempDevNames;
-
-    pd->Flags = PD_RETURNDC;
-    pd->Flags |= PD_USEDEVMODECOPIESANDCOLLATE;
-
-    if (!pdlg->isOptionEnabled(QPrintDialog::PrintSelection))
-        pd->Flags |= PD_NOSELECTION;
-    if (pdlg->isOptionEnabled(QPrintDialog::PrintPageRange)) {
-        pd->nMinPage = pdlg->minPage();
-        pd->nMaxPage = pdlg->maxPage();
-    }
-
-    if(!pdlg->isOptionEnabled(QPrintDialog::PrintToFile))
-        pd->Flags |= PD_DISABLEPRINTTOFILE;
-
-    if (pdlg->isOptionEnabled(QPrintDialog::PrintSelection) && pdlg->printRange() == QPrintDialog::Selection)
-        pd->Flags |= PD_SELECTION;
-    else if (pdlg->isOptionEnabled(QPrintDialog::PrintPageRange) && pdlg->printRange() == QPrintDialog::PageRange)
-        pd->Flags |= PD_PAGENUMS;
-    else if (pdlg->isOptionEnabled(QPrintDialog::PrintCurrentPage) && pdlg->printRange() == QPrintDialog::CurrentPage)
-        pd->Flags |= PD_CURRENTPAGE;
-    else
-        pd->Flags |= PD_ALLPAGES;
-
-    // As stated by MSDN, to enable collate option when minpage==maxpage==0
-    // set the PD_NOPAGENUMS flag
-    if (pd->nMinPage==0 && pd->nMaxPage==0)
-        pd->Flags |= PD_NOPAGENUMS;
-
-    // Disable Current Page option if not required as default is Enabled
-    if (!pdlg->isOptionEnabled(QPrintDialog::PrintCurrentPage))
-        pd->Flags |= PD_NOCURRENTPAGE;
-
-    // Default to showing the General tab first
-    pd->nStartPage = START_PAGE_GENERAL;
-
-    // We don't support more than one page range in the QPrinter API yet.
-    pd->nPageRanges = 1;
-    pd->nMaxPageRanges = 1;
-
-    if (d->ep->printToFile)
-        pd->Flags |= PD_PRINTTOFILE;
-    Q_ASSERT(parent);
-    pd->hwndOwner = parent->window()->winId();
-    pd->lpPageRanges[0].nFromPage = qMax(pdlg->fromPage(), pdlg->minPage());
-    pd->lpPageRanges[0].nToPage   = (pdlg->toPage() > 0) ? qMin(pdlg->toPage(), pdlg->maxPage()) : 1;
-    pd->nCopies = d->ep->num_copies;
-}
-
-static void qt_win_read_back_PRINTDLGEX(PRINTDLGEX *pd, QPrintDialog *pdlg, QPrintDialogPrivate *d)
-{
-    if (pd->Flags & PD_SELECTION) {
-        pdlg->setPrintRange(QPrintDialog::Selection);
-        pdlg->setFromTo(0, 0);
-    } else if (pd->Flags & PD_PAGENUMS) {
-        pdlg->setPrintRange(QPrintDialog::PageRange);
-        pdlg->setFromTo(pd->lpPageRanges[0].nFromPage, pd->lpPageRanges[0].nToPage);
-    } else if (pd->Flags & PD_CURRENTPAGE) {
-        pdlg->setPrintRange(QPrintDialog::CurrentPage);
-        pdlg->setFromTo(0, 0);
-    } else { // PD_ALLPAGES
-        pdlg->setPrintRange(QPrintDialog::AllPages);
-        pdlg->setFromTo(0, 0);
-    }
-
-    d->ep->printToFile = (pd->Flags & PD_PRINTTOFILE) != 0;
-
-    d->ep->readDevnames(pd->hDevNames);
-    d->ep->readDevmode(pd->hDevMode);
-    d->ep->updateCustomPaperSize();
-
-    if (d->ep->printToFile && d->ep->fileName.isEmpty())
-        d->ep->fileName = d->ep->port;
-    else if (!d->ep->printToFile && d->ep->fileName == QLatin1String("FILE:"))
-        d->ep->fileName.clear();
-}
-
-static bool warnIfNotNative(QPrinter *printer)
-{
-    if (printer->outputFormat() != QPrinter::NativeFormat) {
-        qWarning("QPrintDialog: Cannot be used on non-native printers");
-        return false;
-    }
-    return true;
-}
-
-QPrintDialog::QPrintDialog(QPrinter *printer, QWidget *parent)
-    : QAbstractPrintDialog( *(new QPrintDialogPrivate), printer, parent)
-{
-    Q_D(QPrintDialog);
-    if (!warnIfNotNative(d->printer))
-        return;
-    d->ep = static_cast<QWin32PrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPrintDialog::QPrintDialog(QWidget *parent)
-    : QAbstractPrintDialog( *(new QPrintDialogPrivate), 0, parent)
-{
-    Q_D(QPrintDialog);
-    if (!warnIfNotNative(d->printer))
-        return;
-    d->ep = static_cast<QWin32PrintEngine *>(d->printer->paintEngine())->d_func();
-}
-
-QPrintDialog::~QPrintDialog()
-{
-}
-
-int QPrintDialog::exec()
-{
-    if (!warnIfNotNative(printer()))
-        return 0;
-
-    Q_D(QPrintDialog);
-    return d->openWindowsPrintDialogModally();
-}
-
-int QPrintDialogPrivate::openWindowsPrintDialogModally()
-{
-    Q_Q(QPrintDialog);
-    QWidget *parent = q->parentWidget();
-    if (parent)
-        parent = parent->window();
-    else
-        parent = QApplication::activeWindow();
-
-    // If there is no window, fall back to the print dialog itself
-    if (parent == 0)
-        parent = q;
-
-    QWidget modal_widget;
-    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
-    modal_widget.setParent(parent, Qt::Window);
-    QApplicationPrivate::enterModal(&modal_widget);
-
-    HGLOBAL *tempDevNames = ep->createDevNames();
-
-    bool done;
-    bool result;
-    bool doPrinting;
-
-    PRINTPAGERANGE pageRange;
-    PRINTDLGEX pd;
-    memset(&pd, 0, sizeof(PRINTDLGEX));
-    pd.lStructSize = sizeof(PRINTDLGEX);
-    pd.lpPageRanges = &pageRange;
-    qt_win_setup_PRINTDLGEX(&pd, parent, q, this, tempDevNames);
-
-    do {
-        done = true;
-        doPrinting = false;
-        result = (PrintDlgEx(&pd) == S_OK);
-        if (result && (pd.dwResultAction == PD_RESULT_PRINT
-                       || pd.dwResultAction == PD_RESULT_APPLY))
-        {
-            doPrinting = (pd.dwResultAction == PD_RESULT_PRINT);
-            if ((pd.Flags & PD_PAGENUMS)
-                && (pd.lpPageRanges[0].nFromPage > pd.lpPageRanges[0].nToPage))
-            {
-                pd.lpPageRanges[0].nFromPage = 1;
-                pd.lpPageRanges[0].nToPage = 1;
-                done = false;
-            }
-            if (pd.hDC == 0)
-                result = false;
-        }
-
-        if (!done) {
-            QMessageBox::warning(0, QPrintDialog::tr("Print"),
-                                 QPrintDialog::tr("The 'From' value cannot be greater than the 'To' value."));
-        }
-    } while (!done);
-
-    QApplicationPrivate::leaveModal(&modal_widget);
-
-    qt_win_eatMouseMove();
-
-    // write values back...
-    if (result && (pd.dwResultAction == PD_RESULT_PRINT
-                   || pd.dwResultAction == PD_RESULT_APPLY))
-    {
-        qt_win_read_back_PRINTDLGEX(&pd, q, this);
-        // update printer validity
-        printer->d_func()->validPrinter = !ep->name.isEmpty();
-    }
-
-    // Cleanup...
-    GlobalFree(tempDevNames);
-
-    q->done(result && doPrinting);
-
-    return result && doPrinting;
-}
-
-void QPrintDialog::setVisible(bool visible)
-{
-    Q_D(QPrintDialog);
-
-    // its always modal, so we cannot hide a native print dialog
-    if (!visible)
-        return;
-
-    if (!warnIfNotNative(d->printer))
-        return;
-
-    (void)d->openWindowsPrintDialogModally();
-    return;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qprintdialog.h"
-#include "qrc_qprintdialog.cpp"
-
-#endif // QT_NO_PRINTDIALOG
diff --git a/src/gui/dialogs/qwizard_win.cpp b/src/gui/dialogs/qwizard_win.cpp
deleted file mode 100644 (file)
index c57ec08..0000000
+++ /dev/null
@@ -1,832 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QT_NO_WIZARD
-#ifndef QT_NO_STYLE_WINDOWSVISTA
-
-#include "qwizard_win_p.h"
-#include <qsystemlibrary_p.h>
-#include "qwizard.h"
-#include "qpaintengine.h"
-#include "qapplication.h"
-#include <QtCore/QEvent>
-#include <QtGui/QDesktopWidget>
-
-// Note, these tests are duplicates in qwindowsxpstyle_p.h.
-#ifdef Q_CC_GNU
-#  include <w32api.h>
-#  if (__W32API_MAJOR_VERSION >= 3 || (__W32API_MAJOR_VERSION == 2 && __W32API_MINOR_VERSION >= 5))
-#    ifdef _WIN32_WINNT
-#      undef _WIN32_WINNT
-#    endif
-#    define _WIN32_WINNT 0x0501
-#    include <commctrl.h>
-#  endif
-#endif
-
-#include <uxtheme.h>
-
-QT_BEGIN_NAMESPACE
-
-//DWM related
-typedef struct  {       //MARGINS       
-    int cxLeftWidth;    // width of left border that retains its size
-    int cxRightWidth;   // width of right border that retains its size
-    int cyTopHeight;    // height of top border that retains its size
-    int cyBottomHeight; // height of bottom border that retains its size
-} WIZ_MARGINS;
-typedef struct {        //DTTOPTS
-    DWORD dwSize;
-    DWORD dwFlags;
-    COLORREF crText;
-    COLORREF crBorder;
-    COLORREF crShadow;
-    int eTextShadowType;
-    POINT ptShadowOffset;
-    int iBorderSize;
-    int iFontPropId;
-    int iColorPropId;
-    int iStateId;
-    BOOL fApplyOverlay;
-    int iGlowSize;
-} WIZ_DTTOPTS;
-
-typedef struct {
-    DWORD dwFlags;
-    DWORD dwMask;
-} WIZ_WTA_OPTIONS;
-
-#define WIZ_WM_THEMECHANGED                 0x031A
-#define WIZ_WM_DWMCOMPOSITIONCHANGED        0x031E
-
-enum WIZ_WINDOWTHEMEATTRIBUTETYPE {
-    WIZ_WTA_NONCLIENT = 1
-};
-
-#define WIZ_WTNCA_NODRAWCAPTION 0x00000001
-#define WIZ_WTNCA_NODRAWICON    0x00000002
-
-#define WIZ_DT_CENTER                   0x00000001 //DT_CENTER
-#define WIZ_DT_VCENTER                  0x00000004
-#define WIZ_DT_SINGLELINE               0x00000020
-#define WIZ_DT_NOPREFIX                 0x00000800
-
-enum WIZ_NAVIGATIONPARTS {          //NAVIGATIONPARTS
-       WIZ_NAV_BACKBUTTON = 1,
-       WIZ_NAV_FORWARDBUTTON = 2,
-       WIZ_NAV_MENUBUTTON = 3,
-};
-
-enum WIZ_NAV_BACKBUTTONSTATES {     //NAV_BACKBUTTONSTATES
-       WIZ_NAV_BB_NORMAL = 1,
-       WIZ_NAV_BB_HOT = 2,
-       WIZ_NAV_BB_PRESSED = 3,
-       WIZ_NAV_BB_DISABLED = 4,
-};
-
-#define WIZ_TMT_CAPTIONFONT (801)           //TMT_CAPTIONFONT
-#define WIZ_DTT_COMPOSITED  (1UL << 13)     //DTT_COMPOSITED
-#define WIZ_DTT_GLOWSIZE    (1UL << 11)     //DTT_GLOWSIZE
-
-#define WIZ_WM_NCMOUSELEAVE 674             //WM_NCMOUSELEAVE
-
-#define WIZ_WP_CAPTION             1 //WP_CAPTION
-#define WIZ_CS_ACTIVE              1 //CS_ACTIVE
-#define WIZ_TMT_FILLCOLORHINT   3821 //TMT_FILLCOLORHINT
-#define WIZ_TMT_BORDERCOLORHINT 3822 //TMT_BORDERCOLORHINT
-
-typedef BOOL (WINAPI *PtrDwmDefWindowProc)(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *plResult);
-typedef HRESULT (WINAPI *PtrDwmIsCompositionEnabled)(BOOL* pfEnabled);
-typedef HRESULT (WINAPI *PtrDwmExtendFrameIntoClientArea)(HWND hWnd, const WIZ_MARGINS* pMarInset);
-typedef HRESULT (WINAPI *PtrSetWindowThemeAttribute)(HWND hwnd, enum WIZ_WINDOWTHEMEATTRIBUTETYPE eAttribute, PVOID pvAttribute, DWORD cbAttribute);
-
-static PtrDwmDefWindowProc pDwmDefWindowProc = 0;
-static PtrDwmIsCompositionEnabled pDwmIsCompositionEnabled = 0;
-static PtrDwmExtendFrameIntoClientArea pDwmExtendFrameIntoClientArea = 0;
-static PtrSetWindowThemeAttribute pSetWindowThemeAttribute = 0;
-
-//Theme related
-typedef bool (WINAPI *PtrIsAppThemed)();
-typedef bool (WINAPI *PtrIsThemeActive)();
-typedef HANDLE (WINAPI *PtrOpenThemeData)(HWND hwnd, LPCWSTR pszClassList);
-typedef HRESULT (WINAPI *PtrCloseThemeData)(HANDLE hTheme);
-typedef HRESULT (WINAPI *PtrGetThemeSysFont)(HANDLE hTheme, int iFontId, LOGFONTW *plf);
-typedef HRESULT (WINAPI *PtrDrawThemeTextEx)(HANDLE hTheme, HDC hdc, int iPartId, int iStateId, LPCWSTR pszText, int cchText, DWORD dwTextFlags, LPRECT pRect, const WIZ_DTTOPTS *pOptions);
-typedef HRESULT (WINAPI *PtrDrawThemeBackground)(HANDLE hTheme, HDC hdc, int iPartId, int iStateId, const RECT *pRect, OPTIONAL const RECT *pClipRect);
-typedef HRESULT (WINAPI *PtrGetThemePartSize)(HANDLE hTheme, HDC hdc, int iPartId, int iStateId, OPTIONAL RECT *prc, enum THEMESIZE eSize, OUT SIZE *psz);
-typedef HRESULT (WINAPI *PtrGetThemeColor)(HANDLE hTheme, int iPartId, int iStateId, int iPropId, OUT COLORREF *pColor);
-
-static PtrIsAppThemed pIsAppThemed = 0;
-static PtrIsThemeActive pIsThemeActive = 0;
-static PtrOpenThemeData pOpenThemeData = 0;
-static PtrCloseThemeData pCloseThemeData = 0;
-static PtrGetThemeSysFont pGetThemeSysFont = 0;
-static PtrDrawThemeTextEx pDrawThemeTextEx = 0;
-static PtrDrawThemeBackground pDrawThemeBackground = 0;
-static PtrGetThemePartSize pGetThemePartSize = 0;
-static PtrGetThemeColor pGetThemeColor = 0;
-
-int QVistaHelper::instanceCount = 0;
-bool QVistaHelper::is_vista = false;
-QVistaHelper::VistaState QVistaHelper::cachedVistaState = QVistaHelper::Dirty;
-
-/******************************************************************************
-** QVistaBackButton
-*/
-
-QVistaBackButton::QVistaBackButton(QWidget *widget)
-    : QAbstractButton(widget)
-{
-    setFocusPolicy(Qt::NoFocus);
-}
-
-QSize QVistaBackButton::sizeHint() const
-{
-    ensurePolished();
-    int size = int(QStyleHelper::dpiScaled(32));
-    int width = size, height = size;
-/*
-    HANDLE theme = pOpenThemeData(0, L"Navigation");
-    SIZE size;
-    if (pGetThemePartSize(theme, 0, WIZ_NAV_BACKBUTTON, WIZ_NAV_BB_NORMAL, 0, TS_TRUE, &size) == S_OK) {
-        width = size.cx;
-        height = size.cy;
-    }
-*/
-    return QSize(width, height);
-}
-
-void QVistaBackButton::enterEvent(QEvent *event)
-{
-    if (isEnabled())
-        update();
-    QAbstractButton::enterEvent(event);
-}
-
-void QVistaBackButton::leaveEvent(QEvent *event)
-{
-    if (isEnabled())
-        update();
-    QAbstractButton::leaveEvent(event);
-}
-
-void QVistaBackButton::paintEvent(QPaintEvent *)
-{
-    QPainter p(this);
-    QRect r = rect();
-    HANDLE theme = pOpenThemeData(0, L"Navigation");
-    //RECT rect;
-    RECT clipRect;
-    int xoffset = QWidget::mapToParent(r.topLeft()).x() - 1;
-    int yoffset = QWidget::mapToParent(r.topLeft()).y() - 1;
-
-    clipRect.top = r.top() + yoffset;
-    clipRect.bottom = r.bottom() + yoffset;
-    clipRect.left = r.left() + xoffset;
-    clipRect.right = r.right()  + xoffset;
-
-    int state = WIZ_NAV_BB_NORMAL;
-    if (!isEnabled())
-        state = WIZ_NAV_BB_DISABLED;
-    else if (isDown())
-        state = WIZ_NAV_BB_PRESSED;
-    else if (underMouse())
-        state = WIZ_NAV_BB_HOT;
-
-    WIZ_NAVIGATIONPARTS buttonType = (layoutDirection() == Qt::LeftToRight
-                                      ? WIZ_NAV_BACKBUTTON
-                                      : WIZ_NAV_FORWARDBUTTON);
-
-   pDrawThemeBackground(theme, p.paintEngine()->getDC(), buttonType, state, &clipRect, &clipRect);
-}
-
-/******************************************************************************
-** QVistaHelper
-*/
-
-QVistaHelper::QVistaHelper(QWizard *wizard)
-    : QObject(wizard)
-    , pressed(false)
-    , wizard(wizard)
-    , backButton_(0)
-{
-    is_vista = QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && resolveSymbols();
-    if (instanceCount++ == 0)
-        cachedVistaState = Dirty;
-    if (is_vista)
-        backButton_ = new QVistaBackButton(wizard);
-
-    // Handle diff between Windows 7 and Vista
-    iconSpacing = QStyleHelper::dpiScaled(7);
-    textSpacing = QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7 ?
-                  iconSpacing : QStyleHelper::dpiScaled(20);
-}
-
-QVistaHelper::~QVistaHelper()
-{
-    --instanceCount;
-}
-
-bool QVistaHelper::isCompositionEnabled()
-{
-    bool value = is_vista;
-    if (is_vista) {
-        HRESULT hr;
-        BOOL bEnabled;
-
-        hr = pDwmIsCompositionEnabled(&bEnabled);
-        value = (SUCCEEDED(hr) && bEnabled);
-    }
-    return value;
-}
-
-bool QVistaHelper::isThemeActive()
-{
-    return is_vista && pIsThemeActive();
-}
-
-QVistaHelper::VistaState QVistaHelper::vistaState()
-{
-    if (instanceCount == 0 || cachedVistaState == Dirty)
-        cachedVistaState =
-            isCompositionEnabled() ? VistaAero : isThemeActive() ? VistaBasic : Classic;
-    return cachedVistaState;
-}
-
-void QVistaHelper::disconnectBackButton()
-{
-    if (backButton_) // Leave QStyleSheetStyle's connections on destroyed() intact.
-        backButton_->disconnect(SIGNAL(clicked()));
-}
-
-QColor QVistaHelper::basicWindowFrameColor()
-{
-    DWORD rgb;
-    HANDLE hTheme = pOpenThemeData(QApplication::desktop()->winId(), L"WINDOW");
-    pGetThemeColor(
-        hTheme, WIZ_WP_CAPTION, WIZ_CS_ACTIVE,
-        wizard->isActiveWindow() ? WIZ_TMT_FILLCOLORHINT : WIZ_TMT_BORDERCOLORHINT,
-        &rgb);
-    BYTE r = GetRValue(rgb);
-    BYTE g = GetGValue(rgb);
-    BYTE b = GetBValue(rgb);
-    return QColor(r, g, b);
-}
-
-bool QVistaHelper::setDWMTitleBar(TitleBarChangeType type)
-{
-    bool value = false;
-    if (vistaState() == VistaAero) {
-        WIZ_MARGINS mar = {0};
-        if (type == NormalTitleBar)
-            mar.cyTopHeight = 0;
-        else
-            mar.cyTopHeight = titleBarSize() + topOffset();
-        HRESULT hr = pDwmExtendFrameIntoClientArea(wizard->winId(), &mar);
-        value = SUCCEEDED(hr);
-    }
-    return value;
-}
-
-void QVistaHelper::drawTitleBar(QPainter *painter)
-{
-    HDC hdc = painter->paintEngine()->getDC();
-
-    if (vistaState() == VistaAero)
-        drawBlackRect(QRect(0, 0, wizard->width(),
-                            titleBarSize() + topOffset()), hdc);
-    Q_ASSERT(backButton_);
-    const int btnTop = backButton_->mapToParent(QPoint()).y();
-    const int btnHeight = backButton_->size().height();
-    const int verticalCenter = (btnTop + btnHeight / 2) - 1;
-
-    const QString text = wizard->window()->windowTitle();
-    const QFont font = QApplication::font("QWorkspaceTitleBar");
-    const QFontMetrics fontMetrics(font);
-    const QRect brect = fontMetrics.boundingRect(text);
-    int textHeight = brect.height();
-    int textWidth = brect.width();
-    int glowOffset = 0;
-
-    if (vistaState() == VistaAero) {
-        textHeight += 2 * glowSize();
-        textWidth += 2 * glowSize();
-        glowOffset = glowSize();
-    }
-
-    const int titleLeft = (wizard->layoutDirection() == Qt::LeftToRight
-                           ? titleOffset() - glowOffset
-                           : wizard->width() - titleOffset() - textWidth + glowOffset);
-
-    drawTitleText(
-        painter, text,
-        QRect(titleLeft, verticalCenter - textHeight / 2, textWidth, textHeight),
-        hdc);
-
-    if (!wizard->windowIcon().isNull()) {
-        const int iconLeft = (wizard->layoutDirection() == Qt::LeftToRight
-                              ? leftMargin()
-                              : wizard->width() - leftMargin() - iconSize());
-
-        QRect rect(iconLeft, verticalCenter - iconSize() / 2, iconSize(), iconSize());
-        HICON hIcon = wizard->windowIcon().pixmap(iconSize()).toWinHICON();
-        DrawIconEx(hdc, rect.left(), rect.top(), hIcon, 0, 0, 0, NULL, DI_NORMAL | DI_COMPAT);
-        DestroyIcon(hIcon);
-    }
-}
-
-void QVistaHelper::setTitleBarIconAndCaptionVisible(bool visible)
-{
-    if (is_vista) {
-        WIZ_WTA_OPTIONS opt;
-        opt.dwFlags = WIZ_WTNCA_NODRAWICON | WIZ_WTNCA_NODRAWCAPTION;
-        if (visible)
-            opt.dwMask = 0;
-        else
-            opt.dwMask = WIZ_WTNCA_NODRAWICON | WIZ_WTNCA_NODRAWCAPTION;
-        pSetWindowThemeAttribute(wizard->winId(), WIZ_WTA_NONCLIENT, &opt, sizeof(WIZ_WTA_OPTIONS));
-    }
-}
-
-bool QVistaHelper::winEvent(MSG* msg, long* result)
-{
-    switch (msg->message) {
-    case WM_NCHITTEST: {
-        LRESULT lResult;
-        // Perform hit testing using DWM
-        if (pDwmDefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam, &lResult)) {
-            // DWM returned a hit, no further processing necessary
-            *result = lResult;
-        } else {
-            // DWM didn't return a hit, process using DefWindowProc
-            lResult = DefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam);
-            // If DefWindowProc returns a window caption button, just return HTCLIENT (client area).
-            // This avoid unnecessary hits to Windows NT style caption buttons which aren't visible but are
-            // located just under the Aero style window close button.
-            if (lResult == HTCLOSE || lResult == HTMAXBUTTON || lResult == HTMINBUTTON || lResult == HTHELP)
-                *result = HTCLIENT;
-            else
-                *result = lResult;
-        }
-        break;
-    }
-    case WM_NCCALCSIZE:
-        if (vistaState() == VistaAero) {
-            NCCALCSIZE_PARAMS* lpncsp = (NCCALCSIZE_PARAMS*)msg->lParam;
-            *result = DefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam);
-            lpncsp->rgrc[0].top -= titleBarSize();
-        } else {
-            return false;
-        }
-        break;
-    default:
-        LRESULT lResult;
-        // Pass to DWM to handle
-        if (pDwmDefWindowProc(msg->hwnd, msg->message, msg->wParam, msg->lParam, &lResult))
-            *result = lResult;
-        // If the message wasn't handled by DWM, continue processing it as normal
-        else
-            return false;
-    }
-
-    return true;
-}
-
-void QVistaHelper::setMouseCursor(QPoint pos)
-{
-#ifndef QT_NO_CURSOR
-    if (rtTop.contains(pos))
-        wizard->setCursor(Qt::SizeVerCursor);
-    else
-        wizard->setCursor(Qt::ArrowCursor);
-#endif
-}
-
-void QVistaHelper::mouseEvent(QEvent *event)
-{
-    switch (event->type()) {
-    case QEvent::MouseMove:
-        mouseMoveEvent(static_cast<QMouseEvent *>(event));
-        break;
-    case QEvent::MouseButtonPress:
-        mousePressEvent(static_cast<QMouseEvent *>(event));
-        break;
-    case QEvent::MouseButtonRelease:
-        mouseReleaseEvent(static_cast<QMouseEvent *>(event));
-        break;
-    default:
-        break;
-    }
-}
-
-// The following hack ensures that the titlebar is updated correctly
-// when the wizard style changes to and from AeroStyle. Specifically,
-// this function causes a Windows message of type WM_NCCALCSIZE to
-// be triggered.
-void QVistaHelper::setWindowPosHack()
-{
-    const int x = wizard->geometry().x(); // ignored by SWP_NOMOVE
-    const int y = wizard->geometry().y(); // ignored by SWP_NOMOVE
-    const int w = wizard->width();
-    const int h = wizard->height();
-    SetWindowPos(wizard->winId(), 0, x, y, w, h, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
-}
-
-// The following hack allows any QWidget subclass to access
-// QWidgetPrivate::topData() without being declared as a
-// friend by QWidget.
-class QHackWidget : public QWidget
-{
-public:
-    Q_DECLARE_PRIVATE(QWidget)
-    QTLWExtra* topData() { return d_func()->topData(); }
-};
-
-void QVistaHelper::collapseTopFrameStrut()
-{
-    QTLWExtra *top = ((QHackWidget *)wizard)->d_func()->topData();
-    int x1, y1, x2, y2;
-    top->frameStrut.getCoords(&x1, &y1, &x2, &y2);
-    top->frameStrut.setCoords(x1, 0, x2, y2);
-}
-
-bool QVistaHelper::handleWinEvent(MSG *message, long *result)
-{
-    if (message->message == WIZ_WM_THEMECHANGED || message->message == WIZ_WM_DWMCOMPOSITIONCHANGED)
-        cachedVistaState = Dirty;
-
-    bool status = false;
-    if (wizard->wizardStyle() == QWizard::AeroStyle && vistaState() == VistaAero) {
-        status = winEvent(message, result);
-        if (message->message == WM_NCCALCSIZE) {
-            if (status)
-                collapseTopFrameStrut();
-        } else if (message->message == WM_NCPAINT) {
-            wizard->update();
-        }
-    }
-    return status;
-}
-
-void QVistaHelper::resizeEvent(QResizeEvent * event)
-{
-    Q_UNUSED(event);
-    rtTop = QRect (0, 0, wizard->width(), frameSize());
-    int height = captionSize() + topOffset();
-    if (vistaState() == VistaBasic)
-        height -= titleBarSize();
-    rtTitle = QRect (0, frameSize(), wizard->width(), height);
-}
-
-void QVistaHelper::paintEvent(QPaintEvent *event)
-{
-    Q_UNUSED(event);
-    QPainter painter(wizard);
-    drawTitleBar(&painter);
-}
-
-void QVistaHelper::mouseMoveEvent(QMouseEvent *event)
-{
-    if (wizard->windowState() & Qt::WindowMaximized) {
-        event->ignore();
-        return;
-    }
-
-    QRect rect = wizard->geometry();
-    if (pressed) {
-        switch (change) {
-        case resizeTop:
-            {
-                const int dy = event->pos().y() - pressedPos.y();
-                if ((dy > 0 && rect.height() > wizard->minimumHeight())
-                    || (dy < 0 && rect.height() < wizard->maximumHeight()))
-                    rect.setTop(rect.top() + dy);
-            }
-            break;
-        case movePosition: {
-            QPoint newPos = event->pos() - pressedPos;
-            rect.moveLeft(rect.left() + newPos.x());
-            rect.moveTop(rect.top() + newPos.y());
-            break; }
-        default:
-            break;
-        }
-        wizard->setGeometry(rect);
-
-    } else if (vistaState() == VistaAero) {
-        setMouseCursor(event->pos());
-    }
-    event->ignore();
-}
-
-void QVistaHelper::mousePressEvent(QMouseEvent *event)
-{
-    change = noChange;
-
-    if (event->button() != Qt::LeftButton || wizard->windowState() & Qt::WindowMaximized) {
-        event->ignore();
-        return;
-    }
-
-    if (rtTitle.contains(event->pos())) {
-        change = movePosition;
-    } else if (rtTop.contains(event->pos()))
-        change = (vistaState() == VistaAero) ? resizeTop : movePosition;
-
-    if (change != noChange) {
-        if (vistaState() == VistaAero)
-            setMouseCursor(event->pos());
-        pressed = true;
-        pressedPos = event->pos();
-    } else {
-        event->ignore();
-    }
-}
-
-void QVistaHelper::mouseReleaseEvent(QMouseEvent *event)
-{
-    change = noChange;
-    if (pressed) {
-        pressed = false;
-        wizard->releaseMouse();
-        if (vistaState() == VistaAero)
-            setMouseCursor(event->pos());
-    }
-    event->ignore();
-}
-
-bool QVistaHelper::eventFilter(QObject *obj, QEvent *event)
-{
-    if (obj != wizard)
-        return QObject::eventFilter(obj, event);
-
-    if (event->type() == QEvent::MouseMove) {
-        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
-        long result;
-        MSG msg;
-        msg.message = WM_NCHITTEST;
-        msg.wParam  = 0;
-        msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
-        msg.hwnd = wizard->winId();
-        winEvent(&msg, &result);
-        msg.wParam = result;
-        msg.message = WM_NCMOUSEMOVE;
-        winEvent(&msg, &result);
-     } else if (event->type() == QEvent::MouseButtonPress) {
-        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
-
-        if (mouseEvent->button() == Qt::LeftButton) {
-            long result;
-            MSG msg;
-            msg.message = WM_NCHITTEST;
-            msg.wParam  = 0;
-            msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
-            msg.hwnd = wizard->winId();
-            winEvent(&msg, &result);
-            msg.wParam = result;
-            msg.message = WM_NCLBUTTONDOWN;
-            winEvent(&msg, &result);
-        }
-     } else if (event->type() == QEvent::MouseButtonRelease) {
-        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
-
-        if (mouseEvent->button() == Qt::LeftButton) {
-            long result;
-            MSG msg;
-            msg.message = WM_NCHITTEST;
-            msg.wParam  = 0;
-            msg.lParam = MAKELPARAM(mouseEvent->globalX(), mouseEvent->globalY());
-            msg.hwnd = wizard->winId();
-            winEvent(&msg, &result);
-            msg.wParam = result;
-            msg.message = WM_NCLBUTTONUP;
-            winEvent(&msg, &result);
-        }
-     }
-
-     return false;
-}
-
-HFONT QVistaHelper::getCaptionFont(HANDLE hTheme)
-{
-    LOGFONT lf = {0};
-
-    if (!hTheme)
-        pGetThemeSysFont(hTheme, WIZ_TMT_CAPTIONFONT, &lf);
-    else
-    {
-        NONCLIENTMETRICS ncm = {sizeof(NONCLIENTMETRICS)};
-        SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NONCLIENTMETRICS), &ncm, false);
-        lf = ncm.lfMessageFont;
-    }
-    return CreateFontIndirect(&lf);
-}
-
-bool QVistaHelper::drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc)
-{
-    bool value = false;
-    if (vistaState() == VistaAero) {
-        HANDLE hTheme = pOpenThemeData(QApplication::desktop()->winId(), L"WINDOW");
-        if (!hTheme) return false;
-        // Set up a memory DC and bitmap that we'll draw into
-        HDC dcMem;
-        HBITMAP bmp;
-        BITMAPINFO dib = {{0}};
-        dcMem = CreateCompatibleDC(hdc);
-
-        dib.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
-        dib.bmiHeader.biWidth = rect.width();
-        dib.bmiHeader.biHeight = -rect.height();
-        dib.bmiHeader.biPlanes = 1;
-        dib.bmiHeader.biBitCount = 32;
-        dib.bmiHeader.biCompression = BI_RGB;
-        bmp = CreateDIBSection(hdc, &dib, DIB_RGB_COLORS, NULL, NULL, 0);
-
-        // Set up the DC
-        HFONT hCaptionFont = getCaptionFont(hTheme);
-        HBITMAP hOldBmp = (HBITMAP)SelectObject(dcMem, (HGDIOBJ) bmp);
-        HFONT hOldFont = (HFONT)SelectObject(dcMem, (HGDIOBJ) hCaptionFont);
-        // Draw the text!
-        WIZ_DTTOPTS dto = { sizeof(WIZ_DTTOPTS) };
-        const UINT uFormat = WIZ_DT_SINGLELINE|WIZ_DT_CENTER|WIZ_DT_VCENTER|WIZ_DT_NOPREFIX;
-        RECT rctext ={0,0, rect.width(), rect.height()};
-
-        dto.dwFlags = WIZ_DTT_COMPOSITED|WIZ_DTT_GLOWSIZE;
-        dto.iGlowSize = glowSize();
-        pDrawThemeTextEx(hTheme, dcMem, 0, 0, (LPCWSTR)text.utf16(), -1, uFormat, &rctext, &dto );
-        BitBlt(hdc, rect.left(), rect.top(), rect.width(), rect.height(), dcMem, 0, 0, SRCCOPY);
-        SelectObject(dcMem, (HGDIOBJ) hOldBmp);
-        SelectObject(dcMem, (HGDIOBJ) hOldFont);
-        DeleteObject(bmp);
-        DeleteObject(hCaptionFont);
-        DeleteDC(dcMem);
-        //ReleaseDC(hwnd, hdc);
-    } else if (vistaState() == VistaBasic) {
-        painter->drawText(rect, text);
-    }
-    return value;
-}
-
-bool QVistaHelper::drawBlackRect(const QRect &rect, HDC hdc)
-{
-    bool value = false;
-    if (vistaState() == VistaAero) {
-        // Set up a memory DC and bitmap that we'll draw into
-        HDC dcMem;
-        HBITMAP bmp;
-        BITMAPINFO dib = {{0}};
-        dcMem = CreateCompatibleDC(hdc);
-
-        dib.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
-        dib.bmiHeader.biWidth = rect.width();
-        dib.bmiHeader.biHeight = -rect.height();
-        dib.bmiHeader.biPlanes = 1;
-        dib.bmiHeader.biBitCount = 32;
-        dib.bmiHeader.biCompression = BI_RGB;
-        bmp = CreateDIBSection(hdc, &dib, DIB_RGB_COLORS, NULL, NULL, 0);
-        HBITMAP hOldBmp = (HBITMAP)SelectObject(dcMem, (HGDIOBJ) bmp);
-
-        BitBlt(hdc, rect.left(), rect.top(), rect.width(), rect.height(), dcMem, 0, 0, SRCCOPY);
-        SelectObject(dcMem, (HGDIOBJ) hOldBmp);
-
-        DeleteObject(bmp);
-        DeleteDC(dcMem);
-    }
-    return value;
-}
-
-#if !defined(_MSC_VER) || _MSC_VER < 1700
-static inline int getWindowBottomMargin()
-{
-    return GetSystemMetrics(SM_CYSIZEFRAME);
-}
-#else // !_MSC_VER || _MSC_VER < 1700
-// QTBUG-36192, GetSystemMetrics(SM_CYSIZEFRAME) returns bogus values
-// for MSVC2012 which leads to the custom margin having no effect since
-// that only works when removing the entire margin.
-static inline int getWindowBottomMargin()
-{
-    RECT rect = {0, 0, 0, 0};
-    AdjustWindowRectEx(&rect, WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_THICKFRAME | WS_DLGFRAME, FALSE, 0);
-    return qAbs(rect.bottom);
-}
-#endif // _MSC_VER >= 1700
-
-int QVistaHelper::frameSize()
-{
-    return getWindowBottomMargin();
-}
-
-int QVistaHelper::captionSize()
-{
-    return GetSystemMetrics(SM_CYCAPTION);
-}
-
-bool QVistaHelper::resolveSymbols()
-{
-    static bool tried = false;
-    if (!tried) {
-        QSystemLibrary dwmLib(L"dwmapi");
-        pDwmIsCompositionEnabled =
-            (PtrDwmIsCompositionEnabled)dwmLib.resolve("DwmIsCompositionEnabled");
-        if (pDwmIsCompositionEnabled) {
-            pDwmDefWindowProc = (PtrDwmDefWindowProc)dwmLib.resolve("DwmDefWindowProc");
-            pDwmExtendFrameIntoClientArea =
-                (PtrDwmExtendFrameIntoClientArea)dwmLib.resolve("DwmExtendFrameIntoClientArea");
-        }
-        QSystemLibrary themeLib(L"uxtheme");
-        pIsAppThemed = (PtrIsAppThemed)themeLib.resolve("IsAppThemed");
-        if (pIsAppThemed) {
-            pDrawThemeBackground = (PtrDrawThemeBackground)themeLib.resolve("DrawThemeBackground");
-            pGetThemePartSize = (PtrGetThemePartSize)themeLib.resolve("GetThemePartSize");
-            pGetThemeColor = (PtrGetThemeColor)themeLib.resolve("GetThemeColor");
-            pIsThemeActive = (PtrIsThemeActive)themeLib.resolve("IsThemeActive");
-            pOpenThemeData = (PtrOpenThemeData)themeLib.resolve("OpenThemeData");
-            pCloseThemeData = (PtrCloseThemeData)themeLib.resolve("CloseThemeData");
-            pGetThemeSysFont = (PtrGetThemeSysFont)themeLib.resolve("GetThemeSysFont");
-            pDrawThemeTextEx = (PtrDrawThemeTextEx)themeLib.resolve("DrawThemeTextEx");
-            pSetWindowThemeAttribute = (PtrSetWindowThemeAttribute)themeLib.resolve("SetWindowThemeAttribute");
-        }
-        tried = true;
-    }
-
-    return (
-        pDwmIsCompositionEnabled != 0
-        && pDwmDefWindowProc != 0
-        && pDwmExtendFrameIntoClientArea != 0
-        && pIsAppThemed != 0
-        && pDrawThemeBackground != 0
-        && pGetThemePartSize != 0
-        && pGetThemeColor != 0
-        && pIsThemeActive != 0
-        && pOpenThemeData != 0
-        && pCloseThemeData != 0
-        && pGetThemeSysFont != 0
-        && pDrawThemeTextEx != 0
-        && pSetWindowThemeAttribute != 0
-        );
-}
-
-int QVistaHelper::titleOffset()
-{
-    int iconOffset = wizard ->windowIcon().isNull() ? 0 : iconSize() + textSpacing;
-    return leftMargin() + iconOffset;
-}
-
-int QVistaHelper::topOffset()
-{
-    if (vistaState() != VistaAero)
-        return titleBarSize() + 3;
-    static const int aeroOffset =
-        QSysInfo::WindowsVersion == QSysInfo::WV_WINDOWS7 ?
-        QStyleHelper::dpiScaled(4) : QStyleHelper::dpiScaled(13);
-    return aeroOffset + titleBarSize();
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWSVISTA
-
-#endif // QT_NO_WIZARD
diff --git a/src/gui/dialogs/qwizard_win_p.h b/src/gui/dialogs/qwizard_win_p.h
deleted file mode 100644 (file)
index 856d020..0000000
+++ /dev/null
@@ -1,157 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWIZARD_WIN_P_H
-#define QWIZARD_WIN_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.
-//
-
-#ifndef QT_NO_WIZARD
-#ifndef QT_NO_STYLE_WINDOWSVISTA
-
-#include <qt_windows.h>
-#include <qobject.h>
-#include <qwidget.h>
-#include <qabstractbutton.h>
-#include <QtGui/qwidget_p.h>
-#include <QtGui/qstylehelper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-class QVistaBackButton : public QAbstractButton
-{
-public:
-    QVistaBackButton(QWidget *widget);
-
-    QSize sizeHint() const;
-    inline QSize minimumSizeHint() const
-    { return sizeHint(); }
-
-    void enterEvent(QEvent *event);
-    void leaveEvent(QEvent *event);
-    void paintEvent(QPaintEvent *event);
-};
-
-class QWizard;
-
-class QVistaHelper : public QObject
-{
-public:
-    QVistaHelper(QWizard *wizard);
-    ~QVistaHelper();
-    enum TitleBarChangeType { NormalTitleBar, ExtendedTitleBar };
-    bool setDWMTitleBar(TitleBarChangeType type);
-    void setTitleBarIconAndCaptionVisible(bool visible);
-    void mouseEvent(QEvent *event);
-    bool handleWinEvent(MSG *message, long *result);
-    void resizeEvent(QResizeEvent *event);
-    void paintEvent(QPaintEvent *event);
-    QVistaBackButton *backButton() const { return backButton_; }
-    void disconnectBackButton();
-    void hideBackButton() { if (backButton_) backButton_->hide(); }
-    void setWindowPosHack();
-    QColor basicWindowFrameColor();
-    enum VistaState { VistaAero, VistaBasic, Classic, Dirty };
-    static VistaState vistaState();
-    static int titleBarSize() { return frameSize() + captionSize(); }
-    static int topPadding() { // padding under text
-        return int(QStyleHelper::dpiScaled(
-                QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS7 ? 4 : 6));
-    }
-    static int topOffset();
-
-private:
-    static HFONT getCaptionFont(HANDLE hTheme);
-    bool drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc);
-    static bool drawBlackRect(const QRect &rect, HDC hdc);
-
-    static int frameSize();
-    static int captionSize();
-
-    static int backButtonSize() { return int(QStyleHelper::dpiScaled(30)); }
-    static int iconSize() { return 16; } // Standard Aero
-    static int glowSize() { return 10; }
-    int leftMargin() { return backButton_->isVisible() ? backButtonSize() + iconSpacing : 0; }
-
-    int titleOffset();
-    bool resolveSymbols();
-    void drawTitleBar(QPainter *painter);
-    void setMouseCursor(QPoint pos);
-    void collapseTopFrameStrut();
-    bool winEvent(MSG *message, long *result);
-    void mouseMoveEvent(QMouseEvent *event);
-    void mousePressEvent(QMouseEvent *event);
-    void mouseReleaseEvent(QMouseEvent *event);
-    bool eventFilter(QObject *obj, QEvent *event);
-
-    static int instanceCount;
-    static bool is_vista;
-    static VistaState cachedVistaState;
-    static bool isCompositionEnabled();
-    static bool isThemeActive();
-    enum Changes { resizeTop, movePosition, noChange } change;
-    QPoint pressedPos;
-    bool pressed;
-    QRect rtTop;
-    QRect rtTitle;
-    QWizard *wizard;
-    QVistaBackButton *backButton_;
-
-    int titleBarOffset;  // Extra spacing above the text
-    int iconSpacing;    // Space between button and icon
-    int textSpacing;    // Space between icon and text
-};
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_STYLE_WINDOWSVISTA
-#endif // QT_NO_WIZARD
-#endif // QWIZARD_WIN_P_H
diff --git a/src/gui/egl/qegl_wince.cpp b/src/gui/egl/qegl_wince.cpp
deleted file mode 100644 (file)
index 0d9502d..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtGui/qpaintdevice.h>
-#include <QtGui/qpixmap.h>
-#include <QtGui/qwidget.h>
-
-#include "qegl_p.h"
-#include "qeglcontext_p.h"
-
-#include <windows.h>
-
-
-QT_BEGIN_NAMESPACE
-
-EGLNativeDisplayType QEgl::nativeDisplay()
-{
-    HDC myDc = GetDC(0);
-    if (!myDc) {
-        qWarning("QEglContext::nativeDisplay(): WinCE display is not open");
-        return EGLNativeDisplayType(EGL_DEFAULT_DISPLAY);
-    }
-    return EGLNativeDisplayType(myDc);
-}
-
-EGLNativeWindowType QEgl::nativeWindow(QWidget* widget)
-{
-    return (EGLNativeWindowType)(widget->winId());
-}
-
-EGLNativePixmapType QEgl::nativePixmap(QPixmap*)
-{
-    qWarning("QEgl: EGL pixmap surfaces not supported on WinCE");
-    return (EGLNativePixmapType)0;
-}
-
-// Set pixel format and other properties based on a paint device.
-void QEglProperties::setPaintDeviceFormat(QPaintDevice *dev)
-{
-    int devType = dev->devType();
-    if (devType == QInternal::Image)
-        setPixelFormat(static_cast<QImage *>(dev)->format());
-    else
-        setPixelFormat(QImage::Format_RGB16); // XXX
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/image/qpixmap_win.cpp b/src/gui/image/qpixmap_win.cpp
deleted file mode 100644 (file)
index ca144b8..0000000
+++ /dev/null
@@ -1,477 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qpixmap.h"
-#include "qpixmap_raster_p.h"
-
-#include "qbitmap.h"
-#include "qimage.h"
-#include "qwidget.h"
-#include "qpainter.h"
-#include "qdatastream.h"
-#include "qbuffer.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qfile.h"
-#include "qfileinfo.h"
-#include "qdatetime.h"
-#include "qpixmapcache.h"
-#include "qimagereader.h"
-#include "qimagewriter.h"
-#include "qdebug.h"
-#include "qt_windows.h"
-
-#if defined(Q_WS_WINCE)
-#include <winbase.h>
-#include "qguifunctions_wince.h"
-extern bool qt_wince_is_high_dpi();
-extern bool qt_wince_is_pocket_pc();
-#endif
-
-#ifndef CAPTUREBLT
-#define CAPTUREBLT ((DWORD)0x40000000)
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QPixmap QPixmap::grabWindow(WId winId, int x, int y, int w, int h )
-{
-    RECT r;
-    GetClientRect(winId, &r);
-
-    if (w < 0) w = r.right - r.left;
-    if (h < 0) h = r.bottom - r.top;
-
-#ifdef Q_WS_WINCE_WM
-    if (qt_wince_is_pocket_pc()) {
-        QWidget *widget = QWidget::find(winId);
-        if (qobject_cast<QDesktopWidget *>(widget)) {
-            RECT rect = {0,0,0,0};
-            AdjustWindowRectEx(&rect, WS_BORDER | WS_CAPTION, FALSE, 0);
-            int magicNumber = qt_wince_is_high_dpi() ? 4 : 2;
-            y += rect.top - magicNumber;
-        }
-    }
-#endif
-
-    // Create and setup bitmap
-    HDC display_dc = GetDC(0);
-    HDC bitmap_dc = CreateCompatibleDC(display_dc);
-    HBITMAP bitmap = CreateCompatibleBitmap(display_dc, w, h);
-    HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap);
-
-    // copy data
-    HDC window_dc = GetDC(winId);
-    BitBlt(bitmap_dc, 0, 0, w, h, window_dc, x, y, SRCCOPY
-#ifndef Q_WS_WINCE
-                                    | CAPTUREBLT
-#endif
-            );
-
-    // clean up all but bitmap
-    ReleaseDC(winId, window_dc);
-    SelectObject(bitmap_dc, null_bitmap);
-    DeleteDC(bitmap_dc);
-
-    QPixmap pixmap = QPixmap::fromWinHBITMAP(bitmap);
-
-    DeleteObject(bitmap);
-    ReleaseDC(0, display_dc);
-
-    return pixmap;
-}
-
-HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const
-{
-    if (isNull())
-        return 0;
-
-    HBITMAP bitmap = 0;
-    if (data->classId() == QPixmapData::RasterClass) {
-        QRasterPixmapData* d = static_cast<QRasterPixmapData*>(data.data());
-        int w = d->image.width();
-        int h = d->image.height();
-
-        HDC display_dc = GetDC(0);
-
-        // Define the header
-        BITMAPINFO bmi;
-        memset(&bmi, 0, sizeof(bmi));
-        bmi.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
-        bmi.bmiHeader.biWidth       = w;
-        bmi.bmiHeader.biHeight      = -h;
-        bmi.bmiHeader.biPlanes      = 1;
-        bmi.bmiHeader.biBitCount    = 32;
-        bmi.bmiHeader.biCompression = BI_RGB;
-        bmi.bmiHeader.biSizeImage   = w * h * 4;
-
-        // Create the pixmap
-        uchar *pixels = 0;
-        bitmap = CreateDIBSection(display_dc, &bmi, DIB_RGB_COLORS, (void **) &pixels, 0, 0);
-        ReleaseDC(0, display_dc);
-        if (!bitmap) {
-            qErrnoWarning("QPixmap::toWinHBITMAP(), failed to create dibsection");
-            return 0;
-        }
-        if (!pixels) {
-            qErrnoWarning("QPixmap::toWinHBITMAP(), did not allocate pixel data");
-            return 0;
-        }
-
-        // Copy over the data
-        QImage::Format imageFormat = QImage::Format_ARGB32;
-        if (format == NoAlpha)
-            imageFormat = QImage::Format_RGB32;
-        else if (format == PremultipliedAlpha)
-            imageFormat = QImage::Format_ARGB32_Premultiplied;
-        const QImage image = d->image.convertToFormat(imageFormat);
-        int bytes_per_line = w * 4;
-        for (int y=0; y<h; ++y)
-            memcpy(pixels + y * bytes_per_line, image.scanLine(y), bytes_per_line);
-
-    } else {
-        QPixmapData *data = new QRasterPixmapData(depth() == 1 ?
-                                                  QPixmapData::BitmapType : QPixmapData::PixmapType);
-        data->fromImage(toImage(), Qt::AutoColor);
-        return QPixmap(data).toWinHBITMAP(format);
-    }
-    return bitmap;
-}
-
-QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format)
-{
-    // Verify size
-    BITMAP bitmap_info;
-    memset(&bitmap_info, 0, sizeof(BITMAP));
-
-    int res = GetObject(bitmap, sizeof(BITMAP), &bitmap_info);
-    if (!res) {
-        qErrnoWarning("QPixmap::fromWinHBITMAP(), failed to get bitmap info");
-        return QPixmap();
-    }
-    int w = bitmap_info.bmWidth;
-    int h = bitmap_info.bmHeight;
-
-    BITMAPINFO bmi;
-    memset(&bmi, 0, sizeof(bmi));
-    bmi.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
-    bmi.bmiHeader.biWidth       = w;
-    bmi.bmiHeader.biHeight      = -h;
-    bmi.bmiHeader.biPlanes      = 1;
-    bmi.bmiHeader.biBitCount    = 32;
-    bmi.bmiHeader.biCompression = BI_RGB;
-    bmi.bmiHeader.biSizeImage   = w * h * 4;
-
-    QImage result;
-    // Get bitmap bits
-    uchar *data = (uchar *) malloc(bmi.bmiHeader.biSizeImage);
-
-    HDC display_dc = GetDC(0);
-    if (GetDIBits(display_dc, bitmap, 0, h, data, &bmi, DIB_RGB_COLORS)) {
-
-        QImage::Format imageFormat = QImage::Format_ARGB32_Premultiplied;
-        uint mask = 0;
-        if (format == NoAlpha) {
-            imageFormat = QImage::Format_RGB32;
-            mask = 0xff000000;
-        }
-
-        // Create image and copy data into image.
-        QImage image(w, h, imageFormat);
-        if (!image.isNull()) { // failed to alloc?
-            int bytes_per_line = w * sizeof(QRgb);
-            for (int y=0; y<h; ++y) {
-                QRgb *dest = (QRgb *) image.scanLine(y);
-                const QRgb *src = (const QRgb *) (data + y * bytes_per_line);
-                for (int x=0; x<w; ++x) {
-                    const uint pixel = src[x];
-                    if ((pixel & 0xff000000) == 0 && (pixel & 0x00ffffff) != 0)
-                        dest[x] = pixel | 0xff000000;
-                    else
-                        dest[x] = pixel | mask;
-                }
-            }
-        }
-        result = image;
-    } else {
-        qWarning("QPixmap::fromWinHBITMAP(), failed to get bitmap bits");
-    }
-    ReleaseDC(0, display_dc);
-    free(data);
-    return fromImage(result);
-}
-
-HBITMAP qt_createIconMask(const QBitmap &bitmap)
-{
-    QImage bm = bitmap.toImage().convertToFormat(QImage::Format_Mono);
-    int w = bm.width();
-    int h = bm.height();
-    int bpl = ((w+15)/16)*2;                        // bpl, 16 bit alignment
-    uchar *bits = new uchar[bpl*h];
-    bm.invertPixels();
-    for (int y=0; y<h; y++)
-        memcpy(bits+y*bpl, bm.scanLine(y), bpl);
-    HBITMAP hbm = CreateBitmap(w, h, 1, 1, bits);
-    delete [] bits;
-    return hbm;
-}
-
-HICON QPixmap::toWinHICON() const
-{
-    QBitmap maskBitmap = mask();
-    if (maskBitmap.isNull()) {
-        maskBitmap= QBitmap(size());
-        maskBitmap.fill(Qt::color1);
-    }
-
-    ICONINFO ii;
-    ii.fIcon    = true;
-    ii.hbmMask  = qt_createIconMask(maskBitmap);
-    ii.hbmColor = toWinHBITMAP(QPixmap::Alpha);
-    ii.xHotspot = 0;
-    ii.yHotspot = 0;
-
-    HICON hIcon = CreateIconIndirect(&ii);
-
-    DeleteObject(ii.hbmColor);
-    DeleteObject(ii.hbmMask);
-
-    return hIcon;
-}
-
-#ifdef Q_WS_WIN
-#ifndef Q_WS_WINCE
-
-static QImage qt_fromWinHBITMAP(HDC hdc, HBITMAP bitmap, int w, int h)
-{
-    BITMAPINFO bmi;
-    memset(&bmi, 0, sizeof(bmi));
-    bmi.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
-    bmi.bmiHeader.biWidth       = w;
-    bmi.bmiHeader.biHeight      = -h;
-    bmi.bmiHeader.biPlanes      = 1;
-    bmi.bmiHeader.biBitCount    = 32;
-    bmi.bmiHeader.biCompression = BI_RGB;
-    bmi.bmiHeader.biSizeImage   = w * h * 4;
-
-    QImage image(w, h, QImage::Format_ARGB32_Premultiplied);
-    if (image.isNull())
-        return image;
-
-    // Get bitmap bits
-    uchar *data = (uchar *) malloc(bmi.bmiHeader.biSizeImage);
-
-    if (GetDIBits(hdc, bitmap, 0, h, data, &bmi, DIB_RGB_COLORS)) {
-        // Create image and copy data into image.
-        for (int y=0; y<h; ++y) {
-            void *dest = (void *) image.scanLine(y);
-            void *src = data + y * image.bytesPerLine();
-            memcpy(dest, src, image.bytesPerLine());
-        }
-    } else {
-        qWarning("qt_fromWinHBITMAP(), failed to get bitmap bits");
-    }
-    free(data);
-
-    return image;
-}
-
-QPixmap QPixmap::fromWinHICON(HICON icon)
-{
-    bool foundAlpha = false;
-    HDC screenDevice = GetDC(0);
-    HDC hdc = CreateCompatibleDC(screenDevice);
-    ReleaseDC(0, screenDevice);
-
-    ICONINFO iconinfo;
-    bool result = GetIconInfo(icon, &iconinfo); //x and y Hotspot describes the icon center
-    if (!result)
-        qWarning("QPixmap::fromWinHICON(), failed to GetIconInfo()");
-
-    int w = iconinfo.xHotspot * 2;
-    int h = iconinfo.yHotspot * 2;
-
-    BITMAPINFOHEADER bitmapInfo;
-    bitmapInfo.biSize        = sizeof(BITMAPINFOHEADER);
-    bitmapInfo.biWidth       = w;
-    bitmapInfo.biHeight      = h;
-    bitmapInfo.biPlanes      = 1;
-    bitmapInfo.biBitCount    = 32;
-    bitmapInfo.biCompression = BI_RGB;
-    bitmapInfo.biSizeImage   = 0;
-    bitmapInfo.biXPelsPerMeter = 0;
-    bitmapInfo.biYPelsPerMeter = 0;
-    bitmapInfo.biClrUsed       = 0;
-    bitmapInfo.biClrImportant  = 0;
-    DWORD* bits;
-
-    HBITMAP winBitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bitmapInfo, DIB_RGB_COLORS, (VOID**)&bits, NULL, 0);
-    HGDIOBJ oldhdc = (HBITMAP)SelectObject(hdc, winBitmap);
-    DrawIconEx( hdc, 0, 0, icon, iconinfo.xHotspot * 2, iconinfo.yHotspot * 2, 0, 0, DI_NORMAL);
-    QImage image = qt_fromWinHBITMAP(hdc, winBitmap, w, h);
-
-    for (int y = 0 ; y < h && !foundAlpha ; y++) {
-        QRgb *scanLine= reinterpret_cast<QRgb *>(image.scanLine(y));
-        for (int x = 0; x < w ; x++) {
-            if (qAlpha(scanLine[x]) != 0) {
-                foundAlpha = true;
-                break;
-            }
-        }
-    }
-    if (!foundAlpha) {
-        //If no alpha was found, we use the mask to set alpha values
-        DrawIconEx( hdc, 0, 0, icon, w, h, 0, 0, DI_MASK);
-        QImage mask = qt_fromWinHBITMAP(hdc, winBitmap, w, h);
-
-        for (int y = 0 ; y < h ; y++){
-            QRgb *scanlineImage = reinterpret_cast<QRgb *>(image.scanLine(y));
-            QRgb *scanlineMask = mask.isNull() ? 0 : reinterpret_cast<QRgb *>(mask.scanLine(y));
-            for (int x = 0; x < w ; x++){
-                if (scanlineMask && qRed(scanlineMask[x]) != 0)
-                    scanlineImage[x] = 0; //mask out this pixel
-                else
-                    scanlineImage[x] |= 0xff000000; // set the alpha channel to 255
-            }
-        }
-    }
-    //dispose resources created by iconinfo call
-    DeleteObject(iconinfo.hbmMask);
-    DeleteObject(iconinfo.hbmColor);
-
-    SelectObject(hdc, oldhdc); //restore state
-    DeleteObject(winBitmap);
-    DeleteDC(hdc);
-    return QPixmap::fromImage(image);
-}
-#else //ifndef Q_WS_WINCE
-QPixmap QPixmap::fromWinHICON(HICON icon)
-{
-    HDC screenDevice = GetDC(0);
-    HDC hdc = CreateCompatibleDC(screenDevice);
-    ReleaseDC(0, screenDevice);
-
-    ICONINFO iconinfo;
-    bool result = GetIconInfo(icon, &iconinfo);
-    if (!result)
-        qWarning("QPixmap::fromWinHICON(), failed to GetIconInfo()");
-
-    int w = 0;
-    int h = 0;
-    if (!iconinfo.xHotspot || !iconinfo.yHotspot) {
-        // We could not retrieve the icon size via GetIconInfo,
-        // so we try again using the icon bitmap.
-        BITMAP bm;
-        int result = GetObject(iconinfo.hbmColor, sizeof(BITMAP), &bm);
-        if (!result) result = GetObject(iconinfo.hbmMask, sizeof(BITMAP), &bm);
-        if (!result) {
-            qWarning("QPixmap::fromWinHICON(), failed to retrieve icon size");
-            return QPixmap();
-        }
-        w = bm.bmWidth;
-        h = bm.bmHeight;
-    } else {
-        // x and y Hotspot describes the icon center
-        w = iconinfo.xHotspot * 2;
-        h = iconinfo.yHotspot * 2;
-    }
-    const DWORD dwImageSize = w * h * 4;
-
-    BITMAPINFO bmi;
-    memset(&bmi, 0, sizeof(bmi));
-    bmi.bmiHeader.biSize        = sizeof(BITMAPINFO);
-    bmi.bmiHeader.biWidth       = w;
-    bmi.bmiHeader.biHeight      = -h;
-    bmi.bmiHeader.biPlanes      = 1;
-    bmi.bmiHeader.biBitCount    = 32;
-    bmi.bmiHeader.biCompression = BI_RGB;
-    bmi.bmiHeader.biSizeImage   = dwImageSize;
-
-    uchar* bits;
-
-    HBITMAP winBitmap = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, (void**) &bits, 0, 0);
-    if (winBitmap )
-        memset(bits, 0xff, dwImageSize);
-    if (!winBitmap) {
-        qWarning("QPixmap::fromWinHICON(), failed to CreateDIBSection()");
-        return QPixmap();
-    }
-
-    HGDIOBJ oldhdc = (HBITMAP)SelectObject(hdc, winBitmap);
-    if (!DrawIconEx( hdc, 0, 0, icon, w, h, 0, 0, DI_NORMAL))
-        qWarning("QPixmap::fromWinHICON(), failed to DrawIcon()");
-
-    uint mask = 0xff000000;
-    // Create image and copy data into image.
-    QImage image(w, h, QImage::Format_ARGB32);
-
-    if (!image.isNull()) { // failed to alloc?
-        int bytes_per_line = w * sizeof(QRgb);
-        for (int y=0; y < h; ++y) {
-            QRgb *dest = (QRgb *) image.scanLine(y);
-            const QRgb *src = (const QRgb *) (bits + y * bytes_per_line);
-            for (int x=0; x < w; ++x) {
-                dest[x] = src[x];
-            }
-        }
-    }
-    if (!DrawIconEx( hdc, 0, 0, icon, w, h, 0, 0, DI_MASK))
-        qWarning("QPixmap::fromWinHICON(), failed to DrawIcon()");
-    if (!image.isNull()) { // failed to alloc?
-        int bytes_per_line = w * sizeof(QRgb);
-        for (int y=0; y < h; ++y) {
-            QRgb *dest = (QRgb *) image.scanLine(y);
-            const QRgb *src = (const QRgb *) (bits + y * bytes_per_line);
-            for (int x=0; x < w; ++x) {
-                if (!src[x])
-                    dest[x] = dest[x] | mask;
-            }
-        }
-    }
-    SelectObject(hdc, oldhdc); //restore state
-    DeleteObject(winBitmap);
-    DeleteDC(hdc);
-    return QPixmap::fromImage(image);
-}
-#endif //ifndef Q_WS_WINCE
-#endif //ifdef Q_WS_WIN
-
-QT_END_NAMESPACE
diff --git a/src/gui/inputmethod/qmacinputcontext_mac.cpp b/src/gui/inputmethod/qmacinputcontext_mac.cpp
deleted file mode 100644 (file)
index ef7fbc2..0000000
+++ /dev/null
@@ -1,387 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include <qconfig.h>
-#include <qglobal.h>
-#ifndef QT_NO_IM
-#include <qvarlengtharray.h>
-#include <qwidget.h>
-#include <qmacinputcontext_p.h>
-#include "qtextformat.h"
-#include <qdebug.h>
-#include <qapplication_p.h>
-#include <qkeymapper_p.h>
-#include <qthread_p.h>
-
-QT_BEGIN_NAMESPACE
-
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
-#  define typeRefCon typeSInt32
-#  define typeByteCount typeSInt32
-#endif
-
-QMacInputContext::QMacInputContext(QObject *parent)
-    : QInputContext(parent), composing(false), recursionGuard(false), textDocument(0),
-      keydownEvent(0), lastFocusWid(0)
-{
-//    createTextDocument();
-}
-
-QMacInputContext::~QMacInputContext()
-{
-#ifndef QT_MAC_USE_COCOA
-    if(textDocument)
-        DeleteTSMDocument(textDocument);
-#endif
-}
-
-void
-QMacInputContext::createTextDocument()
-{
-#ifndef QT_MAC_USE_COCOA
-    if(!textDocument) {
-        InterfaceTypeList itl = { kUnicodeDocument };
-        NewTSMDocument(1, itl, &textDocument, SRefCon(this));
-    }
-#endif
-}
-
-
-QString QMacInputContext::language()
-{
-    return QString();
-}
-
-
-void QMacInputContext::mouseHandler(int pos, QMouseEvent *e)
-{
-#ifndef QT_MAC_USE_COCOA
-    if(e->type() != QEvent::MouseButtonPress)
-        return;
-
-    if (!composing)
-        return;
-    if (pos < 0 || pos > currentText.length())
-        reset();
-    // ##### handle mouse position
-#else
-    Q_UNUSED(pos);
-    Q_UNUSED(e);
-#endif
-}
-
-#if !defined QT_MAC_USE_COCOA
-
-static QTextFormat qt_mac_compose_format()
-{
-    QTextCharFormat ret;
-    ret.setFontUnderline(true);
-    return ret;
-}
-
-void QMacInputContext::reset()
-{
-    if (recursionGuard)
-        return;
-    if (!currentText.isEmpty()){
-        QInputMethodEvent e;
-        e.setCommitString(currentText);
-        qt_sendSpontaneousEvent(focusWidget(), &e);
-        currentText = QString();
-    }
-    recursionGuard = true;
-    createTextDocument();
-    composing = false;
-    ActivateTSMDocument(textDocument);
-    FixTSMDocument(textDocument);
-    recursionGuard = false;
-}
-
-bool QMacInputContext::isComposing() const
-{
-    return composing;
-}
-#endif
-
-void QMacInputContext::setFocusWidget(QWidget *w)
-{
-    if (!w)
-        lastFocusWid = focusWidget();
-    createTextDocument();
-#ifndef QT_MAC_USE_COCOA
-    if(w)
-        ActivateTSMDocument(textDocument);
-    else
-        DeactivateTSMDocument(textDocument);
-#endif
-    QInputContext::setFocusWidget(w);
-}
-
-
-#ifndef QT_MAC_USE_COCOA
-static EventTypeSpec input_events[] = {
-    { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent },
-    { kEventClassTextInput, kEventTextInputOffsetToPos },
-    { kEventClassTextInput, kEventTextInputUpdateActiveInputArea }
-};
-static EventHandlerUPP input_proc_handlerUPP = 0;
-static EventHandlerRef input_proc_handler = 0;
-#endif
-
-void
-QMacInputContext::initialize()
-{
-#ifndef QT_MAC_USE_COCOA
-    if(!input_proc_handler) {
-        input_proc_handlerUPP = NewEventHandlerUPP(QMacInputContext::globalEventProcessor);
-        InstallEventHandler(GetApplicationEventTarget(), input_proc_handlerUPP,
-                            GetEventTypeCount(input_events), input_events,
-                            0, &input_proc_handler);
-    }
-#endif
-}
-
-void
-QMacInputContext::cleanup()
-{
-#ifndef QT_MAC_USE_COCOA
-    if(input_proc_handler) {
-        RemoveEventHandler(input_proc_handler);
-        input_proc_handler = 0;
-    }
-    if(input_proc_handlerUPP) {
-        DisposeEventHandlerUPP(input_proc_handlerUPP);
-        input_proc_handlerUPP = 0;
-    }
-#endif
-}
-
-void QMacInputContext::setLastKeydownEvent(EventRef event)
-{
-    EventRef tmpEvent = keydownEvent;
-    keydownEvent = event;
-    if (keydownEvent)
-        RetainEvent(keydownEvent);
-    if (tmpEvent)
-        ReleaseEvent(tmpEvent);
-}
-
-OSStatus
-QMacInputContext::globalEventProcessor(EventHandlerCallRef, EventRef event, void *)
-{
-#ifndef QT_MAC_USE_COCOA
-    QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);
-
-    SRefCon refcon = 0;
-    GetEventParameter(event, kEventParamTextInputSendRefCon, typeRefCon, 0,
-                      sizeof(refcon), 0, &refcon);
-    QMacInputContext *context = reinterpret_cast<QMacInputContext*>(refcon);
-
-    bool handled_event=true;
-    UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
-    switch(eclass) {
-    case kEventClassTextInput: {
-        handled_event = false;
-        QWidget *widget = QApplicationPrivate::focus_widget;
-        bool canCompose = widget && (!context || widget->inputContext() == context)
-                && !(widget->inputMethodHints() & Qt::ImhDigitsOnly
-                || widget->inputMethodHints() & Qt::ImhFormattedNumbersOnly
-                || widget->inputMethodHints() & Qt::ImhHiddenText);
-        if(!canCompose) {
-            handled_event = false;
-        } else if(ekind == kEventTextInputOffsetToPos) {
-            if(!widget->testAttribute(Qt::WA_InputMethodEnabled)) {
-                handled_event = false;
-                break;
-            }
-
-            QRect mr(widget->inputMethodQuery(Qt::ImMicroFocus).toRect());
-            QPoint mp(widget->mapToGlobal(QPoint(mr.topLeft())));
-            Point pt;
-            pt.h = mp.x();
-            pt.v = mp.y() + mr.height();
-            SetEventParameter(event, kEventParamTextInputReplyPoint, typeQDPoint,
-                              sizeof(pt), &pt);
-            handled_event = true;
-        } else if(ekind == kEventTextInputUpdateActiveInputArea) {
-            if(!widget->testAttribute(Qt::WA_InputMethodEnabled)) {
-                handled_event = false;
-                break;
-            }
-
-            if (context->recursionGuard)
-                break;
-
-            ByteCount unilen = 0;
-            GetEventParameter(event, kEventParamTextInputSendText, typeUnicodeText,
-                              0, 0, &unilen, 0);
-            UniChar *unicode = (UniChar*)NewPtr(unilen);
-            GetEventParameter(event, kEventParamTextInputSendText, typeUnicodeText,
-                              0, unilen, 0, unicode);
-            QString text((QChar*)unicode, unilen / sizeof(UniChar));
-            DisposePtr((char*)unicode);
-
-            ByteCount fixed_length = 0;
-            GetEventParameter(event, kEventParamTextInputSendFixLen, typeByteCount, 0,
-                              sizeof(fixed_length), 0, &fixed_length);
-            if(fixed_length == ULONG_MAX || fixed_length == unilen) {
-                QInputMethodEvent e;
-                e.setCommitString(text);
-                context->currentText = QString();
-                qt_sendSpontaneousEvent(context->focusWidget(), &e);
-                handled_event = true;
-                context->reset();
-            } else {
-                ByteCount rngSize = 0;
-                OSStatus err = GetEventParameter(event, kEventParamTextInputSendHiliteRng, typeTextRangeArray, 0,
-                                                 0, &rngSize, 0);
-                QVarLengthArray<TextRangeArray> highlight(rngSize);
-                if (noErr == err) {
-                    err = GetEventParameter(event, kEventParamTextInputSendHiliteRng, typeTextRangeArray, 0,
-                                            rngSize, &rngSize, highlight.data());
-                }
-                context->composing = true;
-                if(fixed_length > 0) {
-                    const int qFixedLength = fixed_length / sizeof(UniChar);
-                    QList<QInputMethodEvent::Attribute> attrs;
-                    attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
-                                                          qFixedLength, text.length()-qFixedLength,
-                                                          qt_mac_compose_format());
-                    QInputMethodEvent e(text, attrs);
-                    context->currentText = text;
-                    e.setCommitString(text.left(qFixedLength), 0, qFixedLength);
-                    qt_sendSpontaneousEvent(widget, &e);
-                    handled_event = true;
-                } else {
-                    /* Apple's enums that they have removed from Tiger :(
-                    enum {
-                        kCaretPosition = 1,
-                        kRawText = 2,
-                        kSelectedRawText = 3,
-                        kConvertedText = 4,
-                        kSelectedConvertedText = 5,
-                        kBlockFillText = 6,
-                        kOutlineText = 7,
-                        kSelectedText = 8
-                    };
-                    */
-#ifndef kConvertedText
-#define kConvertedText 4
-#endif
-#ifndef kCaretPosition
-#define kCaretPosition 1
-#endif
-                    QList<QInputMethodEvent::Attribute> attrs;
-                    if (!highlight.isEmpty()) {
-                        TextRangeArray *data = highlight.data();
-                        for (int i = 0; i < data->fNumOfRanges; ++i) {
-                            int start = data->fRange[i].fStart / sizeof(UniChar);
-                            int len = (data->fRange[i].fEnd - data->fRange[i].fStart) / sizeof(UniChar);
-                            if (data->fRange[i].fHiliteStyle == kCaretPosition) {
-                                attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, start, 0, QVariant());
-                                continue;
-                            }
-                            QTextCharFormat format;
-                            format.setFontUnderline(true);
-                            if (data->fRange[i].fHiliteStyle == kConvertedText)
-                                format.setUnderlineColor(Qt::gray);
-                            else
-                                format.setUnderlineColor(Qt::black);
-                            attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, start, len, format);
-                        }
-                    } else {
-                        attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
-                                0, text.length(), qt_mac_compose_format());
-                    }
-                    context->currentText = text;
-                    QInputMethodEvent e(text, attrs);
-                    qt_sendSpontaneousEvent(widget, &e);
-                    handled_event = true;
-                }
-            }
-#if 0
-            if(!context->composing)
-                handled_event = false;
-#endif
-
-            extern bool qt_mac_eat_unicode_key; //qapplication_mac.cpp
-            qt_mac_eat_unicode_key = handled_event;
-        } else if(ekind == kEventTextInputUnicodeForKeyEvent) {
-            EventRef key_ev = 0;
-            GetEventParameter(event, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0,
-                              sizeof(key_ev), 0, &key_ev);
-            QString text;
-            ByteCount unilen = 0;
-            if(GetEventParameter(key_ev, kEventParamKeyUnicodes, typeUnicodeText, 0, 0, &unilen, 0) == noErr) {
-                UniChar *unicode = (UniChar*)NewPtr(unilen);
-                GetEventParameter(key_ev, kEventParamKeyUnicodes, typeUnicodeText, 0, unilen, 0, unicode);
-                text = QString((QChar*)unicode, unilen / sizeof(UniChar));
-                DisposePtr((char*)unicode);
-            }
-            unsigned char chr = 0;
-            GetEventParameter(key_ev, kEventParamKeyMacCharCodes, typeChar, 0, sizeof(chr), 0, &chr);
-            if(!chr || chr >= 128 || (text.length() > 0 && (text.length() > 1 || text.at(0) != QLatin1Char(chr))))
-                handled_event = !widget->testAttribute(Qt::WA_InputMethodEnabled);
-            QMacInputContext *context = qobject_cast<QMacInputContext*>(qApp->inputContext());
-            if (context && context->lastKeydownEvent()) {
-                qt_keymapper_private()->translateKeyEvent(widget, 0, context->lastKeydownEvent(),
-                                                          0, false);
-                context->setLastKeydownEvent(0);
-            }
-        }
-        break; }
-    default:
-        break;
-    }
-    if(!handled_event) //let the event go through
-        return eventNotHandledErr;
-#else
-    Q_UNUSED(event);
-#endif
-    return noErr; //we eat the event
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qmacinputcontext_p.h"
-
-#endif // QT_NO_IM
diff --git a/src/gui/inputmethod/qwininputcontext_win.cpp b/src/gui/inputmethod/qwininputcontext_win.cpp
deleted file mode 100644 (file)
index a00e7e4..0000000
+++ /dev/null
@@ -1,852 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwininputcontext_p.h"
-#include "qinputcontext_p.h"
-#ifndef QT_NO_IM
-
-#include "qfont.h"
-#include "qwidget.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qtextformat.h"
-#include "qtextboundaryfinder.h"
-
-//#define Q_IME_DEBUG
-
-#ifdef Q_IME_DEBUG
-#include "qdebug.h"
-#endif
-
-#if defined(Q_WS_WINCE)
-extern void qt_wince_show_SIP(bool show);   // defined in qguifunctions_wince.cpp
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-
-
-DEFINE_GUID(IID_IActiveIMMApp,
-0x08c0e040, 0x62d1, 0x11d1, 0x93, 0x26, 0x0, 0x60, 0xb0, 0x67, 0xb8, 0x6e);
-
-
-
-DEFINE_GUID(CLSID_CActiveIMM,
-0x4955DD33, 0xB159, 0x11d0, 0x8F, 0xCF, 0x0, 0xAA, 0x00, 0x6B, 0xCC, 0x59);
-
-
-
-DEFINE_GUID(IID_IActiveIMMMessagePumpOwner,
-0xb5cf2cfa, 0x8aeb, 0x11d1, 0x93, 0x64, 0x0, 0x60, 0xb0, 0x67, 0xb8, 0x6e);
-
-
-
-interface IEnumRegisterWordW;
-interface IEnumInputContext;
-
-
-bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-
-
-#define IFMETHOD HRESULT STDMETHODCALLTYPE
-
-interface IActiveIMMApp : public IUnknown
-{
-public:
-    virtual IFMETHOD AssociateContext(HWND hWnd, HIMC hIME, HIMC __RPC_FAR *phPrev) = 0;
-    virtual IFMETHOD dummy_ConfigureIMEA() = 0;
-    virtual IFMETHOD ConfigureIMEW(HKL hKL, HWND hWnd, DWORD dwMode, REGISTERWORDW __RPC_FAR *pData) = 0;
-    virtual IFMETHOD CreateContext(HIMC __RPC_FAR *phIMC) = 0;
-    virtual IFMETHOD DestroyContext(HIMC hIME) = 0;
-    virtual IFMETHOD dummy_EnumRegisterWordA() = 0;
-    virtual IFMETHOD EnumRegisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szRegister, LPVOID pData,
-        IEnumRegisterWordW __RPC_FAR *__RPC_FAR *pEnum) = 0;
-    virtual IFMETHOD dummy_EscapeA() = 0;
-    virtual IFMETHOD EscapeW(HKL hKL, HIMC hIMC, UINT uEscape, LPVOID pData, LRESULT __RPC_FAR *plResult) = 0;
-    virtual IFMETHOD dummy_GetCandidateListA() = 0;
-    virtual IFMETHOD GetCandidateListW(HIMC hIMC, DWORD dwIndex, UINT uBufLen, CANDIDATELIST __RPC_FAR *pCandList,
-        UINT __RPC_FAR *puCopied) = 0;
-    virtual IFMETHOD dummy_GetCandidateListCountA() = 0;
-    virtual IFMETHOD GetCandidateListCountW(HIMC hIMC, DWORD __RPC_FAR *pdwListSize, DWORD __RPC_FAR *pdwBufLen) = 0;
-    virtual IFMETHOD GetCandidateWindow(HIMC hIMC, DWORD dwIndex, CANDIDATEFORM __RPC_FAR *pCandidate) = 0;
-    virtual IFMETHOD dummy_GetCompositionFontA() = 0;
-    virtual IFMETHOD GetCompositionFontW(HIMC hIMC, LOGFONTW __RPC_FAR *plf) = 0;
-    virtual IFMETHOD dummy_GetCompositionStringA() = 0;
-    virtual IFMETHOD GetCompositionStringW(HIMC hIMC, DWORD dwIndex, DWORD dwBufLen, LONG __RPC_FAR *plCopied, LPVOID pBuf) = 0;
-    virtual IFMETHOD GetCompositionWindow(HIMC hIMC, COMPOSITIONFORM __RPC_FAR *pCompForm) = 0;
-    virtual IFMETHOD GetContext(HWND hWnd, HIMC __RPC_FAR *phIMC) = 0;
-    virtual IFMETHOD dummy_GetConversionListA() = 0;
-    virtual IFMETHOD GetConversionListW(HKL hKL, HIMC hIMC, LPWSTR pSrc, UINT uBufLen, UINT uFlag,
-        CANDIDATELIST __RPC_FAR *pDst, UINT __RPC_FAR *puCopied) = 0;
-    virtual IFMETHOD GetConversionStatus(HIMC hIMC, DWORD __RPC_FAR *pfdwConversion, DWORD __RPC_FAR *pfdwSentence) = 0;
-    virtual IFMETHOD GetDefaultIMEWnd(HWND hWnd, HWND __RPC_FAR *phDefWnd) = 0;
-    virtual IFMETHOD dummy_GetDescriptionA() = 0;
-    virtual IFMETHOD GetDescriptionW(HKL hKL, UINT uBufLen, LPWSTR szDescription, UINT __RPC_FAR *puCopied) = 0;
-    virtual IFMETHOD dummy_GetGuideLineA() = 0;
-    virtual IFMETHOD GetGuideLineW(HIMC hIMC, DWORD dwIndex, DWORD dwBufLen, LPWSTR pBuf, DWORD __RPC_FAR *pdwResult) = 0;
-    virtual IFMETHOD dummy_GetIMEFileNameA() = 0;
-    virtual IFMETHOD GetIMEFileNameW(HKL hKL, UINT uBufLen, LPWSTR szFileName, UINT __RPC_FAR *puCopied) = 0;
-    virtual IFMETHOD GetOpenStatus(HIMC hIMC) = 0;
-    virtual IFMETHOD GetProperty(HKL hKL, DWORD fdwIndex, DWORD __RPC_FAR *pdwProperty) = 0;
-    virtual IFMETHOD dummy_GetRegisterWordStyleA() = 0;
-    virtual IFMETHOD GetRegisterWordStyleW(HKL hKL, UINT nItem, STYLEBUFW __RPC_FAR *pStyleBuf, UINT __RPC_FAR *puCopied) = 0;
-    virtual IFMETHOD GetStatusWindowPos(HIMC hIMC, POINT __RPC_FAR *pptPos) = 0;
-    virtual IFMETHOD GetVirtualKey(HWND hWnd, UINT __RPC_FAR *puVirtualKey) = 0;
-    virtual IFMETHOD dummy_InstallIMEA() = 0;
-    virtual IFMETHOD InstallIMEW(LPWSTR szIMEFileName, LPWSTR szLayoutText, HKL __RPC_FAR *phKL) = 0;
-    virtual IFMETHOD IsIME(HKL hKL) = 0;
-    virtual IFMETHOD dummy_IsUIMessageA() = 0;
-    virtual IFMETHOD IsUIMessageW(HWND hWndIME, UINT msg, WPARAM wParam, LPARAM lParam) = 0;
-    virtual IFMETHOD NotifyIME(HIMC hIMC, DWORD dwAction, DWORD dwIndex, DWORD dwValue) = 0;
-    virtual IFMETHOD dummy_RegisterWordA() = 0;
-    virtual IFMETHOD RegisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szRegister) = 0;
-    virtual IFMETHOD ReleaseContext(HWND hWnd, HIMC hIMC) = 0;
-    virtual IFMETHOD SetCandidateWindow(HIMC hIMC, CANDIDATEFORM __RPC_FAR *pCandidate) = 0;
-    virtual IFMETHOD SetCompositionFontA(HIMC hIMC, LOGFONTA __RPC_FAR *plf) = 0;
-    virtual IFMETHOD SetCompositionFontW(HIMC hIMC, LOGFONTW __RPC_FAR *plf) = 0;
-    virtual IFMETHOD dummy_SetCompositionStringA() = 0;
-    virtual IFMETHOD SetCompositionStringW(HIMC hIMC, DWORD dwIndex, LPVOID pComp, DWORD dwCompLen,
-        LPVOID pRead, DWORD dwReadLen) = 0;
-    virtual IFMETHOD SetCompositionWindow(HIMC hIMC, COMPOSITIONFORM __RPC_FAR *pCompForm) = 0;
-    virtual IFMETHOD SetConversionStatus(HIMC hIMC, DWORD fdwConversion, DWORD fdwSentence) = 0;
-    virtual IFMETHOD SetOpenStatus(HIMC hIMC, BOOL fOpen) = 0;
-    virtual IFMETHOD SetStatusWindowPos(HIMC hIMC, POINT __RPC_FAR *pptPos) = 0;
-    virtual IFMETHOD SimulateHotKey(HWND hWnd, DWORD dwHotKeyID) = 0;
-    virtual IFMETHOD dummy_UnregisterWordA() = 0;
-    virtual IFMETHOD UnregisterWordW(HKL hKL, LPWSTR szReading, DWORD dwStyle, LPWSTR szUnregister) = 0;
-    virtual IFMETHOD Activate(BOOL fRestoreLayout) = 0;
-    virtual IFMETHOD Deactivate(void) = 0;
-    virtual IFMETHOD OnDefWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam, LRESULT __RPC_FAR *plResult) = 0;
-    virtual IFMETHOD FilterClientWindows(ATOM __RPC_FAR *aaClassList, UINT uSize) = 0;
-    virtual IFMETHOD dummy_GetCodePageA() = 0;
-    virtual IFMETHOD GetLangId(HKL hKL, LANGID __RPC_FAR *plid) = 0;
-    virtual IFMETHOD AssociateContextEx(HWND hWnd, HIMC hIMC, DWORD dwFlags) = 0;
-    virtual IFMETHOD DisableIME(DWORD idThread) = 0;
-    virtual IFMETHOD dummy_GetImeMenuItemsA() = 0;
-    virtual IFMETHOD GetImeMenuItemsW(HIMC hIMC, DWORD dwFlags, DWORD dwType, /*IMEMENUITEMINFOW*/ void __RPC_FAR *pImeParentMenu,
-        /*IMEMENUITEMINFOW*/ void __RPC_FAR *pImeMenu, DWORD dwSize, DWORD __RPC_FAR *pdwResult) = 0;
-    virtual IFMETHOD EnumInputContext(DWORD idThread, IEnumInputContext __RPC_FAR *__RPC_FAR *ppEnum) = 0;
-};
-
-interface IActiveIMMMessagePumpOwner : public IUnknown
-{
-public:
-    virtual IFMETHOD Start(void) = 0;
-    virtual IFMETHOD End(void) = 0;
-    virtual IFMETHOD OnTranslateMessage(const MSG __RPC_FAR *pMsg) = 0;
-    virtual IFMETHOD Pause(DWORD __RPC_FAR *pdwCookie) = 0;
-    virtual IFMETHOD Resume(DWORD dwCookie) = 0;
-};
-
-
-static IActiveIMMApp *aimm = 0;
-static IActiveIMMMessagePumpOwner *aimmpump = 0;
-static QString *imeComposition = 0;
-static int        imePosition    = -1;
-extern bool qt_use_rtl_extensions;
-static bool haveCaret = false;
-
-#ifndef LGRPID_INSTALLED
-#define LGRPID_INSTALLED          0x00000001  // installed language group ids
-#define LGRPID_SUPPORTED          0x00000002  // supported language group ids
-#endif
-
-#ifndef LGRPID_ARABIC
-#define LGRPID_WESTERN_EUROPE        0x0001   // Western Europe & U.S.
-#define LGRPID_CENTRAL_EUROPE        0x0002   // Central Europe
-#define LGRPID_BALTIC                0x0003   // Baltic
-#define LGRPID_GREEK                 0x0004   // Greek
-#define LGRPID_CYRILLIC              0x0005   // Cyrillic
-#define LGRPID_TURKISH               0x0006   // Turkish
-#define LGRPID_JAPANESE              0x0007   // Japanese
-#define LGRPID_KOREAN                0x0008   // Korean
-#define LGRPID_TRADITIONAL_CHINESE   0x0009   // Traditional Chinese
-#define LGRPID_SIMPLIFIED_CHINESE    0x000a   // Simplified Chinese
-#define LGRPID_THAI                  0x000b   // Thai
-#define LGRPID_HEBREW                0x000c   // Hebrew
-#define LGRPID_ARABIC                0x000d   // Arabic
-#define LGRPID_VIETNAMESE            0x000e   // Vietnamese
-#define LGRPID_INDIC                 0x000f   // Indic
-#define LGRPID_GEORGIAN              0x0010   // Georgian
-#define LGRPID_ARMENIAN              0x0011   // Armenian
-#endif
-
-static DWORD WM_MSIME_MOUSE = 0;
-
-QWinInputContext::QWinInputContext(QObject *parent)
-    : QInputContext(parent), recursionGuard(false)
-{
-#ifndef Q_WS_WINCE
-    QSysInfo::WinVersion ver = QSysInfo::windowsVersion();
-    if (ver & QSysInfo::WV_NT_based  && ver >= QSysInfo::WV_VISTA) {
-        // Since the IsValidLanguageGroup/IsValidLocale functions always return true on 
-        // Vista, check the Keyboard Layouts for enabling RTL. 
-        UINT nLayouts = GetKeyboardLayoutList(0, 0);
-        if (nLayouts) {
-            HKL *lpList = new HKL[nLayouts];
-            GetKeyboardLayoutList(nLayouts, lpList);
-            for (int i = 0; i<(int)nLayouts; i++) {
-                WORD plangid = PRIMARYLANGID((quintptr)lpList[i]);
-                if (plangid == LANG_ARABIC 
-                    || plangid ==  LANG_HEBREW
-                    || plangid ==  LANG_FARSI
-#ifdef LANG_SYRIAC
-                    || plangid ==  LANG_SYRIAC
-#endif
-                    ) {
-                        qt_use_rtl_extensions = true;
-                        break;
-                }
-            }
-            delete []lpList;
-        }
-    } else {
-        // figure out whether a RTL language is installed
-        qt_use_rtl_extensions = IsValidLanguageGroup(LGRPID_ARABIC, LGRPID_INSTALLED)
-                                || IsValidLanguageGroup(LGRPID_HEBREW, LGRPID_INSTALLED)
-                                || IsValidLocale(MAKELCID(MAKELANGID(LANG_ARABIC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED)
-                                || IsValidLocale(MAKELCID(MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED)
-#ifdef LANG_SYRIAC
-                                || IsValidLocale(MAKELCID(MAKELANGID(LANG_SYRIAC, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED)
-#endif
-                                || IsValidLocale(MAKELCID(MAKELANGID(LANG_FARSI, SUBLANG_DEFAULT), SORT_DEFAULT), LCID_INSTALLED);
-    }
-#else
-    qt_use_rtl_extensions = false;
-#endif
-
-    WM_MSIME_MOUSE = RegisterWindowMessage(L"MSIMEMouseOperation");
-}
-
-QWinInputContext::~QWinInputContext()
-{
-    // release active input method if we have one
-    if (aimm) {
-        aimmpump->End();
-        aimmpump->Release();
-        aimm->Deactivate();
-        aimm->Release();
-        aimm = 0;
-        aimmpump = 0;
-    }
-    delete imeComposition;
-    imeComposition = 0;
-}
-
-static HWND getDefaultIMEWnd(HWND wnd)
-{
-    HWND ime_wnd;
-    if(aimm)
-        aimm->GetDefaultIMEWnd(wnd, &ime_wnd);
-    else
-        ime_wnd = ImmGetDefaultIMEWnd(wnd);
-    return ime_wnd;
-}
-
-static HIMC getContext(HWND wnd)
-{
-    HIMC imc;
-    if (aimm)
-        aimm->GetContext(wnd, &imc);
-    else
-        imc = ImmGetContext(wnd);
-
-    return imc;
-}
-
-static void releaseContext(HWND wnd, HIMC imc)
-{
-    if (aimm)
-        aimm->ReleaseContext(wnd, imc);
-    else
-        ImmReleaseContext(wnd, imc);
-}
-
-static void notifyIME(HIMC imc, DWORD dwAction, DWORD dwIndex, DWORD dwValue)
-{
-    if (!imc)
-        return;
-    if (aimm)
-        aimm->NotifyIME(imc, dwAction, dwIndex, dwValue);
-    else
-        ImmNotifyIME(imc, dwAction, dwIndex, dwValue);
-}
-
-static LONG getCompositionString(HIMC himc, DWORD dwIndex, LPVOID lpbuf, DWORD dBufLen)
-{
-    LONG len = 0;
-    if (aimm)
-        aimm->GetCompositionStringW(himc, dwIndex, dBufLen, &len, lpbuf);
-    else
-        len = ImmGetCompositionString(himc, dwIndex, lpbuf, dBufLen);
-    return len;
-}
-
-static int getCursorPosition(HIMC himc)
-{
-    return getCompositionString(himc, GCS_CURSORPOS, 0, 0);
-}
-
-static QString getString(HIMC himc, DWORD dwindex, int *selStart = 0, int *selLength = 0)
-{
-    const int bufferSize = 256;
-    wchar_t buffer[bufferSize];
-    int len = getCompositionString(himc, dwindex, buffer, bufferSize * sizeof(wchar_t));
-
-    if (selStart) {
-        char attrbuffer[bufferSize];
-        int attrlen = getCompositionString(himc, GCS_COMPATTR, attrbuffer, bufferSize);
-        *selStart = attrlen+1;
-        *selLength = -1;
-        for (int i = 0; i < attrlen; i++) {
-            if (attrbuffer[i] & ATTR_TARGET_CONVERTED) {
-                *selStart = qMin(*selStart, i);
-                *selLength = qMax(*selLength, i);
-            }
-        }
-        *selLength = qMax(0, *selLength - *selStart + 1);
-    }
-
-    if (len <= 0)
-        return QString();
-
-    return QString((QChar*)buffer, len / sizeof(QChar));
-}
-
-void QWinInputContext::TranslateMessage(const MSG *msg)
-{
-    if (!aimmpump || aimmpump->OnTranslateMessage(msg) != S_OK)
-        ::TranslateMessage(msg);
-}
-
-LRESULT QWinInputContext::DefWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
-{
-    LRESULT retval;
-    if (!aimm || aimm->OnDefWindowProc(hwnd, msg, wParam, lParam, &retval) != S_OK)
-    {
-        retval = ::DefWindowProc(hwnd, msg, wParam, lParam);
-    }
-    return retval;
-}
-
-
-void QWinInputContext::update()
-{
-    QWidget *w = focusWidget();
-    if(!w)
-        return;
-
-    Q_ASSERT(w->testAttribute(Qt::WA_WState_Created));
-    HIMC imc = getContext(w->effectiveWinId());
-
-    if (!imc)
-        return;
-
-    QFont f = qvariant_cast<QFont>(w->inputMethodQuery(Qt::ImFont));
-    HFONT hf;
-    hf = f.handle();
-
-    LOGFONT lf;
-    if (GetObject(hf, sizeof(lf), &lf)) {
-        if (aimm)
-            aimm->SetCompositionFontW(imc, &lf);
-        else
-            ImmSetCompositionFont(imc, &lf);
-    }
-
-    QRect r = w->inputMethodQuery(Qt::ImMicroFocus).toRect();
-
-    // The ime window positions are based on the WinId with active focus.
-    QWidget *imeWnd = QWidget::find(::GetFocus());
-    if (imeWnd && !aimm) {
-        QPoint pt (r.topLeft());
-        pt = w->mapToGlobal(pt);
-        pt = imeWnd->mapFromGlobal(pt);
-        r.moveTo(pt);
-    }
-
-    COMPOSITIONFORM cf;
-    // ### need X-like inputStyle config settings
-    cf.dwStyle = CFS_FORCE_POSITION;
-    cf.ptCurrentPos.x = r.x();
-    cf.ptCurrentPos.y = r.y();
-
-    CANDIDATEFORM candf;
-    candf.dwIndex = 0;
-    candf.dwStyle = CFS_EXCLUDE;
-    candf.ptCurrentPos.x = r.x();
-    candf.ptCurrentPos.y = r.y() + r.height();
-    candf.rcArea.left = r.x();
-    candf.rcArea.top = r.y();
-    candf.rcArea.right = r.x() + r.width();
-    candf.rcArea.bottom = r.y() + r.height();
-
-    if(haveCaret)
-        SetCaretPos(r.x(), r.y());
-
-    if (aimm) {
-        aimm->SetCompositionWindow(imc, &cf);
-        aimm->SetCandidateWindow(imc, &candf);
-    } else {
-        ImmSetCompositionWindow(imc, &cf);
-        ImmSetCandidateWindow(imc, &candf);
-    }
-
-    releaseContext(w->effectiveWinId(), imc);
-}
-
-
-bool QWinInputContext::endComposition()
-{
-    QWidget *fw = focusWidget();
-#ifdef Q_IME_DEBUG
-    qDebug() << "endComposition! fw=" <<  fw;
-#endif
-    bool result = true;
-    if(imePosition == -1 || recursionGuard)
-        return result;
-
-    // Googles Pinyin Input Method likes to call endComposition again
-    // when we call notifyIME with CPS_CANCEL, so protect ourselves
-    // against that.
-    recursionGuard = true;
-
-    if (fw) {
-        Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
-        HIMC imc = getContext(fw->effectiveWinId());
-        notifyIME(imc, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
-        releaseContext(fw->effectiveWinId(), imc);
-        if(haveCaret) {
-            DestroyCaret();
-            haveCaret = false;
-        }
-    }
-
-    if (!fw)
-        fw = QApplication::focusWidget();
-
-    if (fw) {
-        QInputMethodEvent e;
-        result = qt_sendSpontaneousEvent(fw, &e);
-    }
-
-    if (imeComposition)
-        imeComposition->clear();
-    imePosition = -1;
-
-    recursionGuard = false;
-
-    return result;
-}
-
-void QWinInputContext::reset()
-{
-    QWidget *fw = focusWidget();
-
-#ifdef Q_IME_DEBUG
-    qDebug() << "sending accept to focus widget" <<  fw;
-#endif
-
-    if (fw && imePosition != -1) {
-        QInputMethodEvent e;
-        if (imeComposition)
-            e.setCommitString(*imeComposition);
-         imePosition = -1;
-         qt_sendSpontaneousEvent(fw, &e);
-    }
-
-    if (imeComposition)
-        imeComposition->clear();
-    imePosition = -1;
-
-    if (fw) {
-        Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
-        HIMC imc = getContext(fw->effectiveWinId());
-        notifyIME(imc, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
-        releaseContext(fw->effectiveWinId(), imc);
-    }
-
-}
-
-
-bool QWinInputContext::startComposition()
-{
-#ifdef Q_IME_DEBUG
-    qDebug("startComposition");
-#endif
-
-    if (!imeComposition)
-        imeComposition = new QString();
-
-    QWidget *fw = focusWidget();
-    if (fw) {
-        Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
-        imePosition = 0;
-        haveCaret = CreateCaret(fw->effectiveWinId(), 0, 1, 1);
-        HideCaret(fw->effectiveWinId());
-        update();
-    }
-    return fw != 0;
-}
-
-enum StandardFormat {
-    PreeditFormat,
-    SelectionFormat
-};
-
-bool QWinInputContext::composition(LPARAM lParam)
-{
-#ifdef Q_IME_DEBUG
-    QString str;
-    if (lParam & GCS_RESULTSTR)
-        str += QLatin1String("RESULTSTR ");
-    if (lParam & GCS_COMPSTR)
-        str += QLatin1String("COMPSTR ");
-    if (lParam & GCS_COMPATTR)
-        str += QLatin1String("COMPATTR ");
-    if (lParam & GCS_CURSORPOS)
-        str += QLatin1String("CURSORPOS ");
-    if (lParam & GCS_COMPCLAUSE)
-        str += QLatin1String("COMPCLAUSE ");
-    if (lParam & CS_INSERTCHAR)
-       str += QLatin1String("INSERTCHAR ");
-    if (lParam & CS_NOMOVECARET)
-       str += QLatin1String("NOMOVECARET ");
-    qDebug("composition, lParam=(%x) %s imePosition=%d", lParam, qPrintable(str), imePosition);
-#endif
-
-    bool result = true;
-
-    if(!lParam)
-        // bogus event
-        return true;
-
-    QWidget *fw = QApplication::focusWidget();
-    if (fw) {
-        Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
-        HIMC imc = getContext(fw->effectiveWinId());
-        QInputMethodEvent e;
-        if (lParam & (GCS_COMPSTR | GCS_COMPATTR | GCS_CURSORPOS)) {
-            if (imePosition == -1)
-                // need to send a start event
-                startComposition();
-
-            // some intermediate composition result
-            int selStart, selLength;
-            *imeComposition = getString(imc, GCS_COMPSTR, &selStart, &selLength);
-            imePosition = getCursorPosition(imc);
-            if (lParam & CS_INSERTCHAR  && lParam & CS_NOMOVECARET) {
-                // make korean work correctly. Hope this is correct for all IMEs
-                selStart = 0;
-                selLength = imeComposition->length();
-            }
-           if(selLength == 0)
-                selStart = 0;
-
-           QList<QInputMethodEvent::Attribute> attrs;
-           if (selStart > 0)
-               attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, 0, selStart,
-                                            standardFormat(PreeditFormat));
-           if (selLength)
-               attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selStart, selLength,
-                                            standardFormat(SelectionFormat));
-           if (selStart + selLength < imeComposition->length())
-               attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, selStart + selLength,
-                                            imeComposition->length() - selStart - selLength,
-                                            standardFormat(PreeditFormat));
-           if(imePosition >= 0)
-               attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, imePosition, selLength ? 0 : 1, QVariant());
-
-           e = QInputMethodEvent(*imeComposition, attrs);
-        }
-        if (lParam & GCS_RESULTSTR) {
-            if(imePosition == -1)
-                startComposition();
-            // a fixed result, return the converted string
-            *imeComposition = getString(imc, GCS_RESULTSTR);
-            imePosition = -1;
-            e.setCommitString(*imeComposition);
-            imeComposition->clear();
-        }
-        result = qt_sendSpontaneousEvent(fw, &e);
-        update();
-        releaseContext(fw->effectiveWinId(), imc);
-    }
-#ifdef Q_IME_DEBUG
-    qDebug("imecomposition: cursor pos at %d, str=%x", imePosition, str[0].unicode());
-#endif
-    return result;
-}
-
-static HIMC defaultContext = 0;
-
-// checks whether widget is a popup
-inline bool isPopup(QWidget *w)
-{
-    if (w && (w->windowFlags() & Qt::Popup) == Qt::Popup)
-        return true;
-    else 
-        return false;
-}
-// checks whether widget is in a popup
-inline bool isInPopup(QWidget *w)
-{
-    if (w && (isPopup(w) ||  isPopup(w->window())))
-        return true;
-    else 
-        return false;
-}
-
-// find the parent widget, which is a non popup toplevel
-// this is valid only if the widget is/in a popup
-inline QWidget *findParentforPopup(QWidget *w)
-{
-    QWidget *e = QWidget::find(w->effectiveWinId());
-    // check if this or its parent is a popup
-    while (isInPopup(e)) {
-        e = e->window()->parentWidget();
-        if (!e) 
-            break;
-        e = QWidget::find(e->effectiveWinId());
-    }
-    if (e)
-        return e->window();
-    else
-        return 0;
-}
-
-// enables or disables the ime 
-inline void enableIme(QWidget *w,  bool value) 
-{
-    if (value) {
-        // enable ime
-        if (defaultContext)
-            ImmAssociateContext(w->effectiveWinId(), defaultContext);
-#ifdef Q_WS_WINCE
-        if (qApp->autoSipEnabled())
-            qt_wince_show_SIP(true);
-#endif
-    } else {
-        // disable ime
-        HIMC oldimc = ImmAssociateContext(w->effectiveWinId(), 0);
-        if (!defaultContext)
-            defaultContext = oldimc;
-#ifdef Q_WS_WINCE
-        if (qApp->autoSipEnabled())
-            qt_wince_show_SIP(false);
-#endif
-    }
-}
-
-
-void QWinInputContext::updateImeStatus(QWidget *w, bool hasFocus)
-{
-    if (!w)
-        return;
-    // It's always the proxy that carries the hints.
-    QWidget *focusProxyWidget = w->focusProxy();
-    if (!focusProxyWidget)
-        focusProxyWidget = w;
-    bool e = w->testAttribute(Qt::WA_InputMethodEnabled) && w->isEnabled()
-            && !(focusProxyWidget->inputMethodHints() & (Qt::ImhExclusiveInputMask | Qt::ImhHiddenText));
-    bool hasIme = e && hasFocus;
-#ifdef Q_IME_DEBUG
-    qDebug("%s HasFocus = %d hasIme = %d e = %d ", w->metaObject()->className(), hasFocus, hasIme, e);
-#endif
-    if (hasFocus || e) {
-        if (isInPopup(w))
-            QWinInputContext::enablePopupChild(w, hasIme);
-        else
-            QWinInputContext::enable(w, hasIme);
-    }
-}
-
-void QWinInputContext::enablePopupChild(QWidget *w, bool e)
-{
-    if (aimm) {
-        enable(w, e);
-        return;
-    }
-
-    if (!w || !isInPopup(w))
-        return;
-#ifdef Q_IME_DEBUG
-    qDebug() << "enablePopupChild: w=" << w << "enable=" << e;
-#endif
-    QWidget *parent = findParentforPopup(w);
-    if (parent) {
-        // update ime status of the normal toplevel parent of the popup
-        enableIme(parent, e);
-    }
-    QWidget *toplevel = w->window();
-    if (toplevel) {
-        // update ime status of the toplevel popup
-        enableIme(toplevel, e);
-    }
-}
-
-void QWinInputContext::enable(QWidget *w, bool e)
-{
-    if(w) {
-#ifdef Q_IME_DEBUG
-        qDebug() <<"enable: w=" << w << "enable=" << e;
-#endif
-        if (!w->testAttribute(Qt::WA_WState_Created))
-            return;
-        if(aimm) {
-            HIMC oldimc;
-            if (!e) {
-                aimm->AssociateContext(w->effectiveWinId(), 0, &oldimc);
-                if (!defaultContext)
-                    defaultContext = oldimc;
-            } else if (defaultContext) {
-                aimm->AssociateContext(w->effectiveWinId(), defaultContext, &oldimc);
-            }
-        } else {
-            // update ime status on the widget
-            QWidget *p = QWidget::find(w->effectiveWinId());
-            if (p)
-                enableIme(p, e);
-        }
-    }
-}
-
-void QWinInputContext::setFocusWidget(QWidget *w)
-{
-    QWidget *oldFocus = focusWidget();
-    if (oldFocus == w)
-        return;
-    if (w) {
-        QWinInputContext::updateImeStatus(w, true);
-    } else {
-        if (oldFocus)
-            QWinInputContext::updateImeStatus(oldFocus , false);
-    }
-    QInputContext::setFocusWidget(w);
-    update();
-}
-
-bool QWinInputContext::isComposing() const
-{
-    return imeComposition && !imeComposition->isEmpty();
-}
-
-void QWinInputContext::mouseHandler(int pos, QMouseEvent *e)
-{
-    if(e->type() != QEvent::MouseButtonPress)
-        return;
-
-    if (pos < 0 || pos > imeComposition->length())
-        reset();
-
-    // Probably should pass the correct button, but it seems to work fine like this.
-    DWORD button = MK_LBUTTON;
-
-    QWidget *fw = focusWidget();
-    if (fw) {
-        Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created));
-        HIMC himc = getContext(fw->effectiveWinId());
-        HWND ime_wnd = getDefaultIMEWnd(fw->effectiveWinId());
-        SendMessage(ime_wnd, WM_MSIME_MOUSE, MAKELONG(MAKEWORD(button, pos == 0 ? 2 : 1), pos), (LPARAM)himc);
-        releaseContext(fw->effectiveWinId(), himc);
-    }
-    //qDebug("mouseHandler: got value %d pos=%d", ret,pos);
-}
-
-QString QWinInputContext::language()
-{
-    return QString();
-}
-
-int QWinInputContext::reconvertString(RECONVERTSTRING *reconv)
-{
-    QWidget *w = focusWidget();
-    if(!w)
-        return -1;
-
-    Q_ASSERT(w->testAttribute(Qt::WA_WState_Created));
-    QString surroundingText = qvariant_cast<QString>(w->inputMethodQuery(Qt::ImSurroundingText));
-    int memSize = sizeof(RECONVERTSTRING)+(surroundingText.length()+1)*sizeof(ushort);
-    // If memory is not allocated, return the required size.
-    if (!reconv) {
-        if (surroundingText.isEmpty())
-            return -1;
-        else
-            return memSize;
-    }
-    int pos = qvariant_cast<int>(w->inputMethodQuery(Qt::ImCursorPosition));
-    // find the word in the surrounding text.
-    QTextBoundaryFinder bounds(QTextBoundaryFinder::Word, surroundingText);
-    bounds.setPosition(pos);
-    if (bounds.isAtBoundary()) {
-        if (QTextBoundaryFinder::EndWord == bounds.boundaryReasons())
-            bounds.toPreviousBoundary();
-    } else {
-        bounds.toPreviousBoundary();
-    }
-    int startPos = bounds.position();
-    bounds.toNextBoundary();
-    int endPos = bounds.position();
-    // select the text, this will be overwritten by following ime events.
-    QList<QInputMethodEvent::Attribute> attrs;
-    attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Selection, startPos, endPos-startPos, QVariant());
-    QInputMethodEvent e(QString(), attrs);
-    qt_sendSpontaneousEvent(w, &e);
-
-    reconv->dwSize = memSize;
-    reconv->dwVersion = 0;
-
-    reconv->dwStrLen = surroundingText.length();
-    reconv->dwStrOffset = sizeof(RECONVERTSTRING);
-    reconv->dwCompStrLen = endPos-startPos;
-    reconv->dwCompStrOffset = startPos*sizeof(ushort);
-    reconv->dwTargetStrLen = reconv->dwCompStrLen;
-    reconv->dwTargetStrOffset = reconv->dwCompStrOffset;
-    memcpy((char*)(reconv+1), surroundingText.utf16(), surroundingText.length()*sizeof(ushort));
-    return memSize;
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qwininputcontext_p.h"
-
-#endif // QT_NO_IM
diff --git a/src/gui/kernel/qapplication_mac.mm b/src/gui/kernel/qapplication_mac.mm
deleted file mode 100644 (file)
index fa6d3d4..0000000
+++ /dev/null
@@ -1,3140 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#include <Cocoa/Cocoa.h>
-
-#include "qapplication.h"
-#include "qbitarray.h"
-#include "qclipboard.h"
-#include "qcursor.h"
-#include "qdatastream.h"
-#include "qdatetime.h"
-#include "qdesktopwidget.h"
-#include "qdockwidget.h"
-#include "qevent.h"
-#include "qhash.h"
-#include "qlayout.h"
-#include "qmenubar.h"
-#include "qmessagebox.h"
-#include "qmime.h"
-#include "qpixmapcache.h"
-#include "qpointer.h"
-#include "qsessionmanager.h"
-#include "qsettings.h"
-#include "qsocketnotifier.h"
-#include "qstyle.h"
-#include "qstylefactory.h"
-#include "qtextcodec.h"
-#include "qtoolbar.h"
-#include "qvariant.h"
-#include "qwidget.h"
-#include "qcolormap.h"
-#include "qdir.h"
-#include "qdebug.h"
-#include "qtimer.h"
-#include "qurl.h"
-#include "qmacinputcontext_p.h"
-#include "qpaintengine_mac_p.h"
-#include "qcursor_p.h"
-#include "qapplication_p.h"
-#include "qwidget_p.h"
-#include "qkeymapper_p.h"
-#include "qeventdispatcher_mac_p.h"
-#include "qeventdispatcher_unix_p.h"
-#include <qcocoamenuloader_mac_p.h>
-#include <qcocoaapplication_mac_p.h>
-#include <qcocoaapplicationdelegate_mac_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qcocoawindow_mac_p.h>
-#include <qdesktopwidget_mac_p.h>
-#include <qeventdispatcher_mac_p.h>
-#include <qvarlengtharray.h>
-#include <qthread_p.h>
-
-#ifndef QT_NO_ACCESSIBILITY
-#  include "qaccessible.h"
-#endif
-
-#ifndef QT_NO_THREAD
-#  include "qmutex.h"
-#endif
-
-#include <unistd.h>
-#include <string.h>
-#include <sys/time.h>
-#include <sys/select.h>
-
-/*****************************************************************************
-  QApplication debug facilities
- *****************************************************************************/
-//#define DEBUG_EVENTS //like EventDebug but more specific to Qt
-//#define DEBUG_DROPPED_EVENTS
-//#define DEBUG_MOUSE_MAPS
-//#define DEBUG_MODAL_EVENTS
-//#define DEBUG_PLATFORM_SETTINGS
-
-#define QMAC_SPEAK_TO_ME
-#ifdef QMAC_SPEAK_TO_ME
-#include "qregexp.h"
-#endif
-
-#ifndef kThemeBrushAlternatePrimaryHighlightColor
-#define kThemeBrushAlternatePrimaryHighlightColor -5
-#endif
-
-#define kCMDeviceUnregisteredNotification CFSTR("CMDeviceUnregisteredNotification")
-#define kCMDefaultDeviceNotification CFSTR("CMDefaultDeviceNotification")
-#define kCMDeviceProfilesNotification CFSTR("CMDeviceProfilesNotification")
-#define kCMDefaultDeviceProfileNotification CFSTR("CMDefaultDeviceProfileNotification")
-
-QT_BEGIN_NAMESPACE
-
-//for qt_mac.h
-QPaintDevice *qt_mac_safe_pdev = 0;
-QList<QMacWindowChangeEvent*> *QMacWindowChangeEvent::change_events = 0;
-QPointer<QWidget> topLevelAt_cache = 0;
-
-/*****************************************************************************
-  Internal variables and functions
- *****************************************************************************/
-static struct {
-    bool use_qt_time_limit;
-    QPointer<QWidget> last_widget;
-    int last_x, last_y;
-    int last_modifiers, last_button;
-    EventTime last_time;
-} qt_mac_dblclick = { false, 0, -1, -1, 0, 0, -2 };
-
-static bool app_do_modal = false;       // modal mode
-extern QWidgetList *qt_modal_stack;     // stack of modal widgets
-extern bool qt_tab_all_widgets;         // from qapplication.cpp
-bool qt_mac_app_fullscreen = false;
-bool qt_scrollbar_jump_to_pos = false;
-static bool qt_mac_collapse_on_dblclick = true;
-extern int qt_antialiasing_threshold; // from qapplication.cpp
-QWidget * qt_button_down;                // widget got last button-down
-QPointer<QWidget> qt_last_mouse_receiver;
-#ifndef QT_MAC_USE_COCOA
-static bool qt_button_down_in_content; // whether the button_down was in the content area.
-static bool qt_mac_previous_press_in_popup_mode = false;
-static bool qt_mac_no_click_through_mode = false;
-static int tablet_button_state = 0;
-#endif
-#if defined(QT_DEBUG)
-static bool        appNoGrab        = false;        // mouse/keyboard grabbing
-#endif
-#ifndef QT_MAC_USE_COCOA
-static EventHandlerRef app_proc_handler = 0;
-static EventHandlerUPP app_proc_handlerUPP = 0;
-#endif
-static AEEventHandlerUPP app_proc_ae_handlerUPP = NULL;
-static EventHandlerRef tablet_proximity_handler = 0;
-static EventHandlerUPP tablet_proximity_UPP = 0;
-bool QApplicationPrivate::native_modal_dialog_active;
-
-Q_GUI_EXPORT bool qt_applefontsmoothing_enabled;
-
-/*****************************************************************************
-  External functions
- *****************************************************************************/
-extern void qt_mac_beep(); //qsound_mac.mm
-extern Qt::KeyboardModifiers qt_mac_get_modifiers(int keys); //qkeymapper_mac.cpp
-extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
-extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
-extern OSWindowRef qt_mac_window_for(const QWidget*); //qwidget_mac.cpp
-extern QWidget *qt_mac_find_window(OSWindowRef); //qwidget_mac.cpp
-extern void qt_mac_set_cursor(const QCursor *); //qcursor_mac.cpp
-extern bool qt_mac_is_macsheet(const QWidget *); //qwidget_mac.cpp
-extern void qt_mac_command_set_enabled(MenuRef, UInt32, bool); //qmenu_mac.cpp
-extern bool qt_sendSpontaneousEvent(QObject *obj, QEvent *event); // qapplication.cpp
-extern void qt_mac_update_cursor(); // qcursor_mac.mm
-
-// Forward Decls
-void onApplicationWindowChangedActivation( QWidget*widget, bool activated );
-void onApplicationChangedActivation( bool activated );
-
-#ifdef QT_MAC_USE_COCOA
-void qt_mac_loadMenuNib(QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *qtMenuLoader)
-{
-    // Create qt_menu.nib dir in temp.
-    QDir temp = QDir::temp();
-    temp.mkdir("qt_menu.nib");
-    QString nibDir = temp.canonicalPath() + QLatin1String("/") + QLatin1String("qt_menu.nib/");
-    if (!QDir(nibDir).exists()) {
-        qWarning("qt_mac_loadMenuNib: could not create nib directory in temp");
-        return;
-    }
-
-    // Copy nib files from resources to temp.
-    QDir nibResource(":/trolltech/mac/qt_menu.nib/");
-    if (!nibResource.exists()) {
-        qWarning("qt_mac_loadMenuNib: could not load nib from resources");
-        return;
-    }
-    foreach (const QFileInfo &file, nibResource.entryInfoList())
-        QFile::copy(file.absoluteFilePath(), nibDir + QLatin1String("/") + file.fileName());
-
-    // Load and instantiate nib file from temp
-    NSURL *nibUrl = [NSURL fileURLWithPath : const_cast<NSString *>(reinterpret_cast<const NSString *>(QCFString::toCFStringRef(nibDir)))];
-    NSNib *nib = [[NSNib alloc] initWithContentsOfURL : nibUrl];
-    [nib autorelease];
-    if (!nib) {
-        qWarning("qt_mac_loadMenuNib: could not load nib from temp");
-        return;
-    }
-    bool ok = [nib instantiateNibWithOwner : qtMenuLoader topLevelObjects : nil];
-    if (!ok)
-        qWarning("qt_mac_loadMenuNib: could not instantiate nib");
-}
-#endif
-
-static void qt_mac_read_fontsmoothing_settings()
-{
-    qt_applefontsmoothing_enabled = true;
-    int w = 10, h = 10;
-    QImage image(w, h, QImage::Format_RGB32);
-    image.fill(0xffffffff);
-    QPainter p(&image);
-    p.drawText(0, h, "X\\");
-    p.end();
-
-    const int *bits = (const int *) ((const QImage &) image).bits();
-    int bpl = image.bytesPerLine() / 4;
-    for (int y=0; y<w; ++y) {
-        for (int x=0; x<h; ++x) {
-            int r = qRed(bits[x]);
-            int g = qGreen(bits[x]);
-            int b = qBlue(bits[x]);
-            if (r != g || r != b) {
-                qt_applefontsmoothing_enabled = true;
-                return;
-            }
-        }
-        bits += bpl;
-    }
-    qt_applefontsmoothing_enabled = false;
-}
-
-Q_GUI_EXPORT bool qt_mac_execute_apple_script(const char *script, long script_len, AEDesc *ret) {
-    OSStatus err;
-    AEDesc scriptTextDesc;
-    ComponentInstance theComponent = 0;
-    OSAID scriptID = kOSANullScript, resultID = kOSANullScript;
-
-    // set up locals to a known state
-    AECreateDesc(typeNull, 0, 0, &scriptTextDesc);
-    scriptID = kOSANullScript;
-    resultID = kOSANullScript;
-
-    // open the scripting component
-    theComponent = OpenDefaultComponent(kOSAComponentType, typeAppleScript);
-    if (!theComponent) {
-        err = paramErr;
-        goto bail;
-    }
-
-    // put the script text into an aedesc
-    err = AECreateDesc(typeUTF8Text, script, script_len, &scriptTextDesc);
-    if (err != noErr)
-        goto bail;
-
-    // compile the script
-    err = OSACompile(theComponent, &scriptTextDesc, kOSAModeNull, &scriptID);
-    if (err != noErr)
-        goto bail;
-
-    // run the script
-    err = OSAExecute(theComponent, scriptID, kOSANullScript, kOSAModeNull, &resultID);
-
-    // collect the results - if any
-    if (ret) {
-        AECreateDesc(typeNull, 0, 0, ret);
-        if (err == errOSAScriptError)
-            OSAScriptError(theComponent, kOSAErrorMessage, typeChar, ret);
-        else if (err == noErr && resultID != kOSANullScript)
-            OSADisplay(theComponent, resultID, typeChar, kOSAModeNull, ret);
-    }
-bail:
-    AEDisposeDesc(&scriptTextDesc);
-    if (scriptID != kOSANullScript)
-        OSADispose(theComponent, scriptID);
-    if (resultID != kOSANullScript)
-        OSADispose(theComponent, resultID);
-    if (theComponent)
-        CloseComponent(theComponent);
-    return err == noErr;
-}
-
-Q_GUI_EXPORT bool qt_mac_execute_apple_script(const char *script, AEDesc *ret)
-{
-    return qt_mac_execute_apple_script(script, qstrlen(script), ret);
-}
-
-Q_GUI_EXPORT bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret)
-{
-    const QByteArray l = script.toUtf8(); return qt_mac_execute_apple_script(l.constData(), l.size(), ret);
-}
-
-/* Resolution change magic */
-void qt_mac_display_change_callbk(CGDirectDisplayID, CGDisplayChangeSummaryFlags flags, void *)
-{
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-    const bool resized = flags & kCGDisplayDesktopShapeChangedFlag;
-#else
-    Q_UNUSED(flags);
-    const bool resized = true;
-#endif
-    if (resized && qApp) {
-        if (QDesktopWidget *dw = qApp->desktop()) {
-            QResizeEvent *re = new QResizeEvent(dw->size(), dw->size());
-            QApplication::postEvent(dw, re);
-            QCoreGraphicsPaintEngine::cleanUpMacColorSpaces();
-        }
-    }
-}
-
-#ifdef DEBUG_PLATFORM_SETTINGS
-static void qt_mac_debug_palette(const QPalette &pal, const QPalette &pal2, const QString &where)
-{
-    const char *const groups[] = {"Active", "Disabled", "Inactive" };
-    const char *const roles[] = { "WindowText", "Button", "Light", "Midlight", "Dark", "Mid",
-                            "Text", "BrightText", "ButtonText", "Base", "Window", "Shadow",
-                            "Highlight", "HighlightedText", "Link", "LinkVisited" };
-    if (!where.isNull())
-        qDebug("qt-internal: %s", where.toLatin1().constData());
-    for(int grp = 0; grp < QPalette::NColorGroups; grp++) {
-        for(int role = 0; role < QPalette::NColorRoles; role++) {
-            QBrush b = pal.brush((QPalette::ColorGroup)grp, (QPalette::ColorRole)role);
-            QPixmap pm = b.texture();
-            qDebug("  %s::%s %d::%d::%d [%p]%s", groups[grp], roles[role], b.color().red(),
-                   b.color().green(), b.color().blue(), pm.isNull() ? 0 : &pm,
-                   pal2.brush((QPalette::ColorGroup)grp, (QPalette::ColorRole)role) != b ? " (*)" : "");
-        }
-    }
-
-}
-#else
-#define qt_mac_debug_palette(x, y, z)
-#endif
-
-//raise a notification
-#ifndef QT_MAC_USE_COCOA
-static NMRec qt_mac_notification = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
-#endif
-void qt_mac_send_notification()
-{
-#ifndef QT_MAC_USE_COCOA
-    //send it
-    qt_mac_notification.nmMark = 1; //non-zero magic number
-    qt_mac_notification.qType = nmType;
-    NMInstall(&qt_mac_notification);
-#else
-    QMacCocoaAutoReleasePool pool;
-    [[NSApplication sharedApplication] requestUserAttention:NSInformationalRequest];
-#endif
-}
-
-void qt_mac_cancel_notification()
-{
-#ifndef QT_MAC_USE_COCOA
-    NMRemove(&qt_mac_notification);
-#else
-    QMacCocoaAutoReleasePool pool;
-    [[NSApplication sharedApplication] cancelUserAttentionRequest:NSInformationalRequest];
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-//find widget (and part) at a given point
-static short qt_mac_window_at(int x, int y, QWidget **w=0)
-{
-    Point p;
-    p.h = x;
-    p.v = y;
-    OSWindowRef wp;
-    WindowPartCode wpc;
-    OSStatus err = FindWindowOfClass(&p, kAllWindowClasses, &wp, &wpc);
-    if(err != noErr) {
-        if(w)
-            (*w) = 0;
-        return wpc;
-    }
-    if(w) {
-        if(wp) {
-            *w = qt_mac_find_window(wp);
-#if 0
-            if(!*w)
-                qWarning("QApplication: qt_mac_window_at: Couldn't find %d",(int)wp);
-#endif
-        } else {
-            *w = 0;
-        }
-    }
-    return wpc;
-}
-
-#endif
-
-void qt_mac_set_app_icon(const QPixmap &pixmap)
-{
-#ifndef QT_MAC_USE_COCOA
-    if(pixmap.isNull()) {
-        RestoreApplicationDockTileImage();
-    } else {
-        CGImageRef img = (CGImageRef)pixmap.macCGHandle();
-        SetApplicationDockTileImage(img);
-        CGImageRelease(img);
-    }
-#else
-    QMacCocoaAutoReleasePool pool;
-    NSImage *image = NULL;
-    if (pixmap.isNull()) {
-        // Get Application icon from bundle
-        image = [[NSImage imageNamed:@"NSApplicationIcon"] retain]; // released below
-    } else {
-        image = static_cast<NSImage *>(qt_mac_create_nsimage(pixmap));
-    }
-
-    [[NSApplication sharedApplication] setApplicationIconImage:image];
-    [image release];
-#endif
-}
-
-Q_GUI_EXPORT void qt_mac_set_press_and_hold_context(bool b)
-{
-    Q_UNUSED(b);
-    qWarning("qt_mac_set_press_and_hold_context: This functionality is no longer available");
-}
-
-bool qt_nograb()                                // application no-grab option
-{
-#if defined(QT_DEBUG)
-    return appNoGrab;
-#else
-    return false;
-#endif
-}
-
-void qt_mac_update_os_settings()
-{
-    if (!qApp)
-        return;
-    if (!QApplication::startingUp()) {
-        static bool needToPolish = true;
-        if (needToPolish) {
-            QApplication::style()->polish(qApp);
-            needToPolish = false;
-        }
-    }
-    //focus mode
-    /* First worked as of 10.2.3 */
-    QSettings appleSettings(QLatin1String("apple.com"));
-    QVariant appleValue = appleSettings.value(QLatin1String("AppleKeyboardUIMode"), 0);
-    qt_tab_all_widgets = (appleValue.toInt() & 0x2);
-    //paging mode
-    /* First worked as of 10.2.3 */
-    appleValue = appleSettings.value(QLatin1String("AppleScrollerPagingBehavior"), false);
-    qt_scrollbar_jump_to_pos = appleValue.toBool();
-    //collapse
-    /* First worked as of 10.3.3 */
-    appleValue = appleSettings.value(QLatin1String("AppleMiniaturizeOnDoubleClick"), true);
-    qt_mac_collapse_on_dblclick = appleValue.toBool();
-
-    // Anti-aliasing threshold
-    appleValue = appleSettings.value(QLatin1String("AppleAntiAliasingThreshold"));
-    if (appleValue.isValid())
-        qt_antialiasing_threshold = appleValue.toInt();
-
-#ifdef DEBUG_PLATFORM_SETTINGS
-    qDebug("qt_mac_update_os_settings *********************************************************************");
-#endif
-    { // setup the global palette
-        QColor qc;
-        (void) QApplication::style();  // trigger creation of application style and system palettes
-        QPalette pal = *QApplicationPrivate::sys_pal;
-
-        pal.setBrush( QPalette::Active, QPalette::Highlight, qcolorForTheme(kThemeBrushPrimaryHighlightColor) );
-        pal.setBrush( QPalette::Inactive, QPalette::Highlight, qcolorForTheme(kThemeBrushSecondaryHighlightColor) );
-
-        pal.setBrush( QPalette::Disabled, QPalette::Highlight, qcolorForTheme(kThemeBrushSecondaryHighlightColor) );
-        pal.setBrush( QPalette::Active, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonActiveDarkShadow) );
-
-        pal.setBrush( QPalette::Inactive, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonInactiveDarkShadow) );
-        pal.setBrush( QPalette::Disabled, QPalette::Shadow, qcolorForTheme(kThemeBrushButtonInactiveDarkShadow) );
-
-        qc = qcolorForThemeTextColor(kThemeTextColorDialogActive);
-        pal.setColor(QPalette::Active, QPalette::Text, qc);
-        pal.setColor(QPalette::Active, QPalette::WindowText, qc);
-        pal.setColor(QPalette::Active, QPalette::HighlightedText, qc);
-
-        qc = qcolorForThemeTextColor(kThemeTextColorDialogInactive);
-        pal.setColor(QPalette::Inactive, QPalette::Text, qc);
-        pal.setColor(QPalette::Inactive, QPalette::WindowText, qc);
-        pal.setColor(QPalette::Inactive, QPalette::HighlightedText, qc);
-        pal.setColor(QPalette::Disabled, QPalette::Text, qc);
-        pal.setColor(QPalette::Disabled, QPalette::WindowText, qc);
-        pal.setColor(QPalette::Disabled, QPalette::HighlightedText, qc);
-        pal.setBrush(QPalette::ToolTipBase, QColor(255, 255, 199));
-
-        if (!QApplicationPrivate::sys_pal || *QApplicationPrivate::sys_pal != pal) {
-            QApplicationPrivate::setSystemPalette(pal);
-            QApplication::setPalette(pal);
-        }
-#ifdef DEBUG_PLATFORM_SETTINGS
-        qt_mac_debug_palette(pal, QApplication::palette(), "Global Palette");
-#endif
-    }
-
-    QFont fnt = qfontForThemeFont(kThemeApplicationFont);
-#ifdef DEBUG_PLATFORM_SETTINGS
-    qDebug("qt-internal: Font for Application [%s::%d::%d::%d]",
-           fnt.family().toLatin1().constData(), fnt.pointSize(), fnt.bold(), fnt.italic());
-#endif
-    if (!QApplicationPrivate::sys_font || *QApplicationPrivate::sys_font != fnt)
-        QApplicationPrivate::setSystemFont(fnt);
-
-    { //setup the fonts
-        struct FontMap {
-            FontMap(const char *qc, short fk) : qt_class(qc), font_key(fk) { }
-            const char *const qt_class;
-            short font_key;
-        } mac_widget_fonts[] = {
-            FontMap("QPushButton", kThemePushButtonFont),
-            FontMap("QListView", kThemeViewsFont),
-            FontMap("QListBox", kThemeViewsFont),
-            FontMap("QTitleBar", kThemeWindowTitleFont),
-            FontMap("QMenuBar", kThemeMenuTitleFont),
-            FontMap("QMenu", kThemeMenuItemFont),
-            FontMap("QComboMenuItem", kThemeSystemFont),
-            FontMap("QHeaderView", kThemeSmallSystemFont),
-            FontMap("QTipLabel", kThemeSmallSystemFont),
-            FontMap("QLabel", kThemeSystemFont),
-            FontMap("QToolButton", kThemeSmallSystemFont),
-            FontMap("QMenuItem", kThemeMenuItemFont),  // It doesn't exist, but its unique.
-            FontMap("QComboLineEdit", kThemeViewsFont),  // It doesn't exist, but its unique.
-            FontMap("QSmallFont", kThemeSmallSystemFont),  // It doesn't exist, but its unique.
-            FontMap("QMiniFont", kThemeMiniSystemFont),  // It doesn't exist, but its unique.
-            FontMap(0, 0) };
-        for(int i = 0; mac_widget_fonts[i].qt_class; i++) {
-            QFont fnt = qfontForThemeFont(mac_widget_fonts[i].font_key);
-            bool set_font = true;
-            FontHash *hash = qt_app_fonts_hash();
-            if (!hash->isEmpty()) {
-                FontHash::const_iterator it
-                                        = hash->constFind(mac_widget_fonts[i].qt_class);
-                if (it != hash->constEnd())
-                    set_font = (fnt != *it);
-            }
-            if (set_font) {
-                QApplication::setFont(fnt, mac_widget_fonts[i].qt_class);
-#ifdef DEBUG_PLATFORM_SETTINGS
-                qDebug("qt-internal: Font for %s [%s::%d::%d::%d]", mac_widget_fonts[i].qt_class,
-                       fnt.family().toLatin1().constData(), fnt.pointSize(), fnt.bold(), fnt.italic());
-#endif
-            }
-        }
-    }
-    QApplicationPrivate::initializeWidgetPaletteHash();
-#ifdef DEBUG_PLATFORM_SETTINGS
-    qDebug("qt_mac_update_os_settings END !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-#endif
-}
-
-void QApplicationPrivate::initializeWidgetPaletteHash()
-{
-    { //setup the palette
-        struct PaletteMap {
-            inline PaletteMap(const char *qc, ThemeBrush a, ThemeBrush i) :
-                qt_class(qc), active(a), inactive(i) { }
-            const char *const qt_class;
-            ThemeBrush active, inactive;
-        } mac_widget_colors[] = {
-            PaletteMap("QToolButton", kThemeTextColorBevelButtonActive, kThemeTextColorBevelButtonInactive),
-            PaletteMap("QAbstractButton", kThemeTextColorPushButtonActive, kThemeTextColorPushButtonInactive),
-            PaletteMap("QHeaderView", kThemeTextColorPushButtonActive, kThemeTextColorPushButtonInactive),
-            PaletteMap("QComboBox", kThemeTextColorPopupButtonActive, kThemeTextColorPopupButtonInactive),
-            PaletteMap("QAbstractItemView", kThemeTextColorListView, kThemeTextColorDialogInactive),
-            PaletteMap("QMessageBoxLabel", kThemeTextColorAlertActive, kThemeTextColorAlertInactive),
-            PaletteMap("QTabBar", kThemeTextColorTabFrontActive, kThemeTextColorTabFrontInactive),
-            PaletteMap("QLabel", kThemeTextColorPlacardActive, kThemeTextColorPlacardInactive),
-            PaletteMap("QGroupBox", kThemeTextColorPlacardActive, kThemeTextColorPlacardInactive),
-            PaletteMap("QMenu", kThemeTextColorPopupLabelActive, kThemeTextColorPopupLabelInactive),
-            PaletteMap("QTextEdit", 0, 0),
-            PaletteMap("QTextControl", 0, 0),
-            PaletteMap("QLineEdit", 0, 0),
-            PaletteMap(0, 0, 0) };
-        QColor qc;
-        for(int i = 0; mac_widget_colors[i].qt_class; i++) {
-            QPalette pal;
-            if (mac_widget_colors[i].active != 0) {
-                qc = qcolorForThemeTextColor(mac_widget_colors[i].active);
-                pal.setColor(QPalette::Active, QPalette::Text, qc);
-                pal.setColor(QPalette::Active, QPalette::WindowText, qc);
-                pal.setColor(QPalette::Active, QPalette::HighlightedText, qc);
-                qc = qcolorForThemeTextColor(mac_widget_colors[i].inactive);
-                pal.setColor(QPalette::Inactive, QPalette::Text, qc);
-                pal.setColor(QPalette::Disabled, QPalette::Text, qc);
-                pal.setColor(QPalette::Inactive, QPalette::WindowText, qc);
-                pal.setColor(QPalette::Disabled, QPalette::WindowText, qc);
-                pal.setColor(QPalette::Inactive, QPalette::HighlightedText, qc);
-                pal.setColor(QPalette::Disabled, QPalette::HighlightedText, qc);
-            }
-            if (!strcmp(mac_widget_colors[i].qt_class, "QMenu")) {
-                qc = qcolorForThemeTextColor(kThemeTextColorMenuItemActive);
-                pal.setBrush(QPalette::ButtonText, qc);
-                qc = qcolorForThemeTextColor(kThemeTextColorMenuItemSelected);
-                pal.setBrush(QPalette::HighlightedText, qc);
-                qc = qcolorForThemeTextColor(kThemeTextColorMenuItemDisabled);
-                pal.setBrush(QPalette::Disabled, QPalette::Text, qc);
-            } else if (!strcmp(mac_widget_colors[i].qt_class, "QAbstractButton")
-                      || !strcmp(mac_widget_colors[i].qt_class, "QHeaderView")) { //special
-                pal.setColor(QPalette::Disabled, QPalette::ButtonText,
-                             pal.color(QPalette::Disabled, QPalette::Text));
-                pal.setColor(QPalette::Inactive, QPalette::ButtonText,
-                             pal.color(QPalette::Inactive, QPalette::Text));
-                pal.setColor(QPalette::Active, QPalette::ButtonText,
-                             pal.color(QPalette::Active, QPalette::Text));
-            } else if (!strcmp(mac_widget_colors[i].qt_class, "QAbstractItemView")) {
-                pal.setBrush(QPalette::Active, QPalette::Highlight,
-                             qcolorForTheme(kThemeBrushAlternatePrimaryHighlightColor));
-                qc = qcolorForThemeTextColor(kThemeTextColorMenuItemSelected);
-                pal.setBrush(QPalette::Active, QPalette::HighlightedText, qc);
-#if 1
-                pal.setBrush(QPalette::Inactive, QPalette::Text,
-                              pal.brush(QPalette::Active, QPalette::Text));
-                pal.setBrush(QPalette::Inactive, QPalette::HighlightedText,
-                              pal.brush(QPalette::Active, QPalette::Text));
-#endif
-            } else if (!strcmp(mac_widget_colors[i].qt_class, "QTextEdit")
-                       || !strcmp(mac_widget_colors[i].qt_class, "QTextControl")) {
-                pal.setBrush(QPalette::Inactive, QPalette::Text,
-                              pal.brush(QPalette::Active, QPalette::Text));
-                pal.setBrush(QPalette::Inactive, QPalette::HighlightedText,
-                              pal.brush(QPalette::Active, QPalette::Text));
-            } else if (!strcmp(mac_widget_colors[i].qt_class, "QLineEdit")) {
-                pal.setBrush(QPalette::Disabled, QPalette::Base,
-                             pal.brush(QPalette::Active, QPalette::Base));
-            }
-
-            bool set_palette = true;
-            PaletteHash *phash = qt_app_palettes_hash();
-            if (!phash->isEmpty()) {
-                PaletteHash::const_iterator it
-                                    = phash->constFind(mac_widget_colors[i].qt_class);
-                if (it != phash->constEnd())
-                    set_palette = (pal != *it);
-            }
-            if (set_palette) {
-                QApplication::setPalette(pal, mac_widget_colors[i].qt_class);
-#ifdef DEBUG_PLATFORM_SETTINGS
-                qt_mac_debug_palette(pal, QApplication::palette(), QLatin1String("Palette for ") + QString::fromLatin1(mac_widget_colors[i].qt_class));
-#endif
-            }
-        }
-    }
-}
-
-static void qt_mac_event_release(EventRef &event)
-{
-    ReleaseEvent(event);
-    event = 0;
-}
-#ifndef QT_MAC_USE_COCOA
-static void qt_mac_event_release(QWidget *w, EventRef &event)
-{
-    if (event) {
-        QWidget *widget = 0;
-        if (GetEventParameter(event, kEventParamQWidget, typeQWidget, 0, sizeof(widget), 0, &widget) == noErr
-           && w == widget) {
-            if (IsEventInQueue(GetMainEventQueue(), event))
-                RemoveEventFromQueue(GetMainEventQueue(), event);
-            qt_mac_event_release(event);
-        }
-    }
-}
-
-static bool qt_mac_event_remove(EventRef &event)
-{
-    if (event) {
-        if (IsEventInQueue(GetMainEventQueue(), event))
-            RemoveEventFromQueue(GetMainEventQueue(), event);
-        qt_mac_event_release(event);
-        return true;
-    }
-    return false;
-}
-#endif
-
-/* sheets */
-#ifndef QT_MAC_USE_COCOA
-static EventRef request_showsheet_pending = 0;
-#endif
-void qt_event_request_showsheet(QWidget *w)
-{
-    Q_ASSERT(qt_mac_is_macsheet(w));
-#ifdef QT_MAC_USE_COCOA
-    w->repaint();
-    [[NSApplication sharedApplication] beginSheet:qt_mac_window_for(w) modalForWindow:qt_mac_window_for(w->parentWidget())
-        modalDelegate:nil didEndSelector:nil contextInfo:0];
-#else
-    qt_mac_event_remove(request_showsheet_pending);
-    CreateEvent(0, kEventClassQt, kEventQtRequestShowSheet, GetCurrentEventTime(),
-                kEventAttributeUserEvent, &request_showsheet_pending);
-    SetEventParameter(request_showsheet_pending, kEventParamQWidget, typeQWidget, sizeof(w), &w);
-    PostEventToQueue(GetMainEventQueue(), request_showsheet_pending, kEventPriorityStandard);
-#endif
-}
-
-static void qt_post_window_change_event(QWidget *widget)
-{
-    qt_widget_private(widget)->needWindowChange = true;
-    QEvent *glWindowChangeEvent = new QEvent(QEvent::MacGLWindowChange);
-    QApplication::postEvent(widget, glWindowChangeEvent);
-}
-
-/*
-    Posts updates to all child and grandchild OpenGL widgets for the given widget.
-*/
-static void qt_mac_update_child_gl_widgets(QWidget *widget)
-{
-    // Update all OpenGL child widgets for the given widget.
-    QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget)->glWidgets;
-    QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
-    QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();
-
-    for (;it != end; ++it) {
-        qt_post_window_change_event(it->widget);
-    }
-}
-
-/*
-    Sends updates to all child and grandchild gl widgets that have updates pending.
-*/
-void qt_mac_send_posted_gl_updates(QWidget *widget)
-{
-    QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget)->glWidgets;
-    QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
-    QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();
-
-    for (;it != end; ++it) {
-        QWidget *glWidget = it->widget;
-        if (qt_widget_private(glWidget)->needWindowChange) {
-            QEvent glChangeEvent(QEvent::MacGLWindowChange);
-            QApplication::sendEvent(glWidget, &glChangeEvent);
-        }
-    }
-}
-
-/*
-    Posts updates to all OpenGL widgets within the window that the given widget intersects.
-*/
-static void qt_mac_update_intersected_gl_widgets(QWidget *widget)
-{
-#ifndef QT_MAC_USE_COCOA
-    QList<QWidgetPrivate::GlWidgetInfo> &glWidgets = qt_widget_private(widget->window())->glWidgets;
-    if (glWidgets.isEmpty())
-        return;
-
-    // Exit if the window has not been created yet (mapToGlobal/size will force create it)
-    if (widget->testAttribute(Qt::WA_WState_Created) == false || HIViewGetWindow(qt_mac_nativeview_for(widget)) == 0)
-        return;
-
-    const QRect globalWidgetRect = QRect(widget->mapToGlobal(QPoint(0, 0)), widget->size());
-
-    QList<QWidgetPrivate::GlWidgetInfo>::iterator end = glWidgets.end();
-    QList<QWidgetPrivate::GlWidgetInfo>::iterator it = glWidgets.begin();
-
-    for (;it != end; ++it){
-        QWidget *glWidget = it->widget;
-        const QRect globalGlWidgetRect = QRect(glWidget->mapToGlobal(QPoint(0, 0)), glWidget->size());
-        if (globalWidgetRect.intersects(globalGlWidgetRect)) {
-            qt_post_window_change_event(glWidget);
-            it->lastUpdateWidget = widget;
-        } else if (it->lastUpdateWidget == widget) {
-            // Update the gl wigets that the widget intersected the last time around,
-            // and that we are not intersecting now. This prevents paint errors when the
-            // intersecting widget leaves a gl widget.
-            qt_post_window_change_event(glWidget);
-            it->lastUpdateWidget = 0;
-        }
-    }
-#else
-    Q_UNUSED(widget);
-#endif
-}
-
-/*
-    Posts a kEventQtRequestWindowChange event to the main Carbon event queue.
-*/
-static EventRef request_window_change_pending = 0;
-Q_GUI_EXPORT void qt_event_request_window_change()
-{
-    if(request_window_change_pending)
-        return;
-
-    CreateEvent(0, kEventClassQt, kEventQtRequestWindowChange, GetCurrentEventTime(),
-                kEventAttributeUserEvent, &request_window_change_pending);
-    PostEventToQueue(GetMainEventQueue(), request_window_change_pending, kEventPriorityHigh);
-}
-
-/* window changing. This is a hack around Apple's missing functionality, pending the toolbox
-   team fix. --Sam */
-Q_GUI_EXPORT void qt_event_request_window_change(QWidget *widget)
-{
-    if (!widget)
-        return;
-
-    // Post a kEventQtRequestWindowChange event. This event is semi-public,
-    // don't remove this line!
-    qt_event_request_window_change();
-
-    // Post update request on gl widgets unconditionally.
-    if (qt_widget_private(widget)->isGLWidget == true) {
-        qt_post_window_change_event(widget);
-        return;
-    }
-
-    qt_mac_update_child_gl_widgets(widget);
-    qt_mac_update_intersected_gl_widgets(widget);
-}
-
-/* activation */
-static struct {
-    QPointer<QWidget> widget;
-    EventRef event;
-    EventLoopTimerRef timer;
-    EventLoopTimerUPP timerUPP;
-} request_activate_pending = { 0, 0, 0, 0 };
-bool qt_event_remove_activate()
-{
-    if (request_activate_pending.timer) {
-        RemoveEventLoopTimer(request_activate_pending.timer);
-        request_activate_pending.timer = 0;
-    }
-    if (request_activate_pending.event)
-        qt_mac_event_release(request_activate_pending.event);
-    return true;
-}
-
-void qt_event_activate_timer_callbk(EventLoopTimerRef r, void *)
-{
-    EventLoopTimerRef otc = request_activate_pending.timer;
-    qt_event_remove_activate();
-    if (r == otc && !request_activate_pending.widget.isNull()) {
-        const QWidget *tlw = request_activate_pending.widget->window();
-        Qt::WindowType wt = tlw->windowType();
-        if (tlw->isVisible()
-               && ((wt != Qt::Desktop && wt != Qt::Popup && wt != Qt::Tool) || tlw->isModal())) {
-            CreateEvent(0, kEventClassQt, kEventQtRequestActivate, GetCurrentEventTime(),
-                        kEventAttributeUserEvent, &request_activate_pending.event);
-            PostEventToQueue(GetMainEventQueue(), request_activate_pending.event, kEventPriorityHigh);
-        }
-    }
-}
-
-void qt_event_request_activate(QWidget *w)
-{
-    if (w == request_activate_pending.widget)
-        return;
-
-    /* We put these into a timer because due to order of events being sent we need to be sure this
-       comes from inside of the event loop */
-    qt_event_remove_activate();
-    if (!request_activate_pending.timerUPP)
-        request_activate_pending.timerUPP = NewEventLoopTimerUPP(qt_event_activate_timer_callbk);
-    request_activate_pending.widget = w;
-    InstallEventLoopTimer(GetMainEventLoop(), 0, 0, request_activate_pending.timerUPP, 0, &request_activate_pending.timer);
-}
-
-
-/* menubars */
-#ifndef QT_MAC_USE_COCOA
-static EventRef request_menubarupdate_pending = 0;
-#endif
-void qt_event_request_menubarupdate()
-{
-#ifndef QT_MAC_USE_COCOA
-    if (request_menubarupdate_pending) {
-        if (IsEventInQueue(GetMainEventQueue(), request_menubarupdate_pending))
-            return;
-#ifdef DEBUG_DROPPED_EVENTS
-        qDebug("%s:%d Whoa, we dropped an event on the floor!", __FILE__, __LINE__);
-#endif
-    }
-
-    CreateEvent(0, kEventClassQt, kEventQtRequestMenubarUpdate, GetCurrentEventTime(),
-                kEventAttributeUserEvent, &request_menubarupdate_pending);
-    PostEventToQueue(GetMainEventQueue(), request_menubarupdate_pending, kEventPriorityHigh);
-#else
-    // Just call this. The request has the benefit that we don't call this multiple times, but
-    // we can optimize this.
-    QMenuBar::macUpdateMenuBar();
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-//context menu
-static EventRef request_context_pending = 0;
-static void qt_event_request_context(QWidget *w=0, EventRef *where=0)
-{
-    if (!where)
-        where = &request_context_pending;
-    if (*where)
-        return;
-    CreateEvent(0, kEventClassQt, kEventQtRequestContext, GetCurrentEventTime(),
-                kEventAttributeUserEvent, where);
-    if (w)
-        SetEventParameter(*where, kEventParamQWidget, typeQWidget, sizeof(w), &w);
-    PostEventToQueue(GetMainEventQueue(), *where, kEventPriorityStandard);
-}
-#endif
-
-void QApplicationPrivate::createEventDispatcher()
-{
-    Q_Q(QApplication);
-    if (q->type() != QApplication::Tty)
-        eventDispatcher = new QEventDispatcherMac(q);
-    else
-        eventDispatcher = new QEventDispatcherUNIX(q);
-}
-
-/* clipboard */
-void qt_event_send_clipboard_changed()
-{
-#ifndef QT_MAC_USE_COCOA
-    AppleEvent ae;
-    if (AECreateAppleEvent(kEventClassQt, typeAEClipboardChanged, 0, kAutoGenerateReturnID, kAnyTransactionID, &ae) != noErr)
-        qDebug("Can't happen!!");
-    AppleEvent reply;
-    AESend(&ae, &reply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, 0, 0);
-#endif
-}
-
-/* app menu */
-static QMenu *qt_mac_dock_menu = 0;
-Q_GUI_EXPORT void qt_mac_set_dock_menu(QMenu *menu)
-{
-    qt_mac_dock_menu = menu;
-#ifdef QT_MAC_USE_COCOA
-    [[NSApplication sharedApplication] setDockMenu:menu->macMenu()];
-#else
-    SetApplicationDockTileMenu(menu->macMenu());
-#endif
-}
-
-/* events that hold pointers to widgets, must be cleaned up like this */
-void qt_mac_event_release(QWidget *w)
-{
-    if (w) {
-#ifndef QT_MAC_USE_COCOA
-        qt_mac_event_release(w, request_showsheet_pending);
-        qt_mac_event_release(w, request_context_pending);
-#endif
-        if (w == qt_mac_dock_menu) {
-            qt_mac_dock_menu = 0;
-#ifndef QT_MAC_USE_COCOA
-            SetApplicationDockTileMenu(0);
-#else
-            [[NSApplication sharedApplication] setDockMenu:0];
-#endif
-        }
-    }
-}
-
-struct QMacAppleEventTypeSpec {
-    AEEventClass mac_class;
-    AEEventID mac_id;
-} app_apple_events[] = {
-    { kCoreEventClass, kAEQuitApplication },
-    { kCoreEventClass, kAEOpenDocuments },
-    { kInternetEventClass, kAEGetURL },
-};
-
-#ifndef QT_MAC_USE_COCOA
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
-enum
-{
-    kEventMouseScroll                          = 11,
-    kEventParamMouseWheelSmoothVerticalDelta   = 'saxy',
-    kEventParamMouseWheelSmoothHorizontalDelta = 'saxx',
-};
-#endif
-
-/* watched events */
-static EventTypeSpec app_events[] = {
-    { kEventClassQt, kEventQtRequestWindowChange },
-    { kEventClassQt, kEventQtRequestShowSheet },
-    { kEventClassQt, kEventQtRequestContext },
-    { kEventClassQt, kEventQtRequestActivate },
-    { kEventClassQt, kEventQtRequestMenubarUpdate },
-
-    { kEventClassWindow, kEventWindowActivated },
-    { kEventClassWindow, kEventWindowDeactivated },
-
-    { kEventClassMouse, kEventMouseScroll },
-    { kEventClassMouse, kEventMouseWheelMoved },
-    { kEventClassMouse, kEventMouseDown },
-    { kEventClassMouse, kEventMouseUp },
-    { kEventClassMouse, kEventMouseDragged },
-    { kEventClassMouse, kEventMouseMoved },
-
-    { kEventClassTablet, kEventTabletProximity },
-
-    { kEventClassApplication, kEventAppActivated },
-    { kEventClassApplication, kEventAppDeactivated },
-    { kEventClassApplication, kEventAppAvailableWindowBoundsChanged },
-
-    //    { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent },
-    { kEventClassKeyboard, kEventRawKeyModifiersChanged },
-    { kEventClassKeyboard, kEventRawKeyRepeat },
-    { kEventClassKeyboard, kEventRawKeyUp },
-    { kEventClassKeyboard, kEventRawKeyDown },
-
-    { kEventClassCommand, kEventCommandProcess },
-
-    { kEventClassAppleEvent, kEventAppleEvent },
-
-    { kAppearanceEventClass, kAEAppearanceChanged }
-};
-
-void qt_init_app_proc_handler()
-{
-    InstallEventHandler(GetApplicationEventTarget(), app_proc_handlerUPP,
-                        GetEventTypeCount(app_events), app_events, (void *)qApp,
-                        &app_proc_handler);
-}
-#endif // QT_MAC_USE_COCOA
-
-static void qt_init_tablet_proximity_handler()
-{
-    EventTypeSpec      tabletProximityEvent = { kEventClassTablet, kEventTabletProximity };
-    InstallEventHandler(GetEventMonitorTarget(), tablet_proximity_UPP,
-                        1, &tabletProximityEvent, qApp, &tablet_proximity_handler);
-}
-
-static void qt_release_tablet_proximity_handler()
-{
-    RemoveEventHandler(tablet_proximity_handler);
-}
-
-QString QApplicationPrivate::appName() const
-{
-    static QString applName;
-    if (applName.isEmpty()) {
-        applName = QCoreApplicationPrivate::macMenuBarName();
-        ProcessSerialNumber psn;
-        if (applName.isEmpty() && qt_is_gui_used && GetCurrentProcess(&psn) == noErr) {
-            QCFString cfstr;
-            CopyProcessName(&psn, &cfstr);
-            applName = cfstr;
-        }
-    }
-    return applName;
-}
-
-void qt_release_app_proc_handler()
-{
-#ifndef QT_MAC_USE_COCOA
-    if (app_proc_handler) {
-        RemoveEventHandler(app_proc_handler);
-        app_proc_handler = 0;
-    }
-#endif
-}
-
-void qt_color_profile_changed(CFNotificationCenterRef, void *, CFStringRef, const void *,
-                              CFDictionaryRef)
-{
-    QCoreGraphicsPaintEngine::cleanUpMacColorSpaces();
-}
-/* platform specific implementations */
-void qt_init(QApplicationPrivate *priv, int)
-{
-    if (qt_is_gui_used) {
-        CGDisplayRegisterReconfigurationCallback(qt_mac_display_change_callbk, 0);
-        CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter();
-        CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed,
-                                        kCMDeviceUnregisteredNotification, 0,
-                                        CFNotificationSuspensionBehaviorDeliverImmediately);
-        CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed,
-                                        kCMDefaultDeviceNotification, 0,
-                                        CFNotificationSuspensionBehaviorDeliverImmediately);
-        CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed,
-                                        kCMDeviceProfilesNotification, 0,
-                                        CFNotificationSuspensionBehaviorDeliverImmediately);
-        CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed,
-                                        kCMDefaultDeviceProfileNotification, 0,
-                                        CFNotificationSuspensionBehaviorDeliverImmediately);
-        ProcessSerialNumber psn;
-        if (GetCurrentProcess(&psn) == noErr) {
-            // Jambi needs to transform itself since most people aren't "used"
-            // to putting things in bundles, but other people may actually not
-            // want to tranform the process (running as a helper or something)
-            // so don't do that for them. This means checking both LSUIElement
-            // and LSBackgroundOnly. If you set them both... well, you
-            // shouldn't do that.
-
-            bool forceTransform = true;
-            CFTypeRef value = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(),
-                                                                   CFSTR("LSUIElement"));
-            if (value) {
-                CFTypeID valueType = CFGetTypeID(value);
-                // Officially it's supposed to be a string, a boolean makes sense, so we'll check.
-                // A number less so, but OK.
-                if (valueType == CFStringGetTypeID())
-                    forceTransform = !(QCFString::toQString(static_cast<CFStringRef>(value)).toInt());
-                else if (valueType == CFBooleanGetTypeID())
-                    forceTransform = !CFBooleanGetValue(static_cast<CFBooleanRef>(value));
-                else if (valueType == CFNumberGetTypeID()) {
-                    int valueAsInt;
-                    CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberIntType, &valueAsInt);
-                    forceTransform = !valueAsInt;
-                }
-            }
-
-            if (forceTransform) {
-                value = CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(),
-                                                             CFSTR("LSBackgroundOnly"));
-                if (value) {
-                    CFTypeID valueType = CFGetTypeID(value);
-                    if (valueType == CFBooleanGetTypeID())
-                        forceTransform = !CFBooleanGetValue(static_cast<CFBooleanRef>(value));
-                    else if (valueType == CFStringGetTypeID())
-                        forceTransform = !(QCFString::toQString(static_cast<CFStringRef>(value)).toInt());
-                    else if (valueType == CFNumberGetTypeID()) {
-                        int valueAsInt;
-                        CFNumberGetValue(static_cast<CFNumberRef>(value), kCFNumberIntType, &valueAsInt);
-                        forceTransform = !valueAsInt;
-                    }
-                }
-            }
-
-
-            if (forceTransform) {
-                TransformProcessType(&psn, kProcessTransformToForegroundApplication);
-            }
-        }
-    }
-
-    char **argv = priv->argv;
-
-    // Get command line params
-    if (int argc = priv->argc) {
-        int i, j = 1;
-        QString passed_psn;
-        for(i=1; i < argc; i++) {
-            if (argv[i] && *argv[i] != '-') {
-                argv[j++] = argv[i];
-                continue;
-            }
-            QByteArray arg(argv[i]);
-#if defined(QT_DEBUG)
-            if (arg == "-nograb")
-                appNoGrab = !appNoGrab;
-            else
-#endif // QT_DEBUG
-                if (arg.left(5) == "-psn_") {
-                    passed_psn = QString::fromLatin1(arg.mid(6));
-                } else {
-                    argv[j++] = argv[i];
-                }
-        }
-        if (j < priv->argc) {
-            priv->argv[j] = 0;
-            priv->argc = j;
-        }
-
-        //special hack to change working directory (for an app bundle) when running from finder
-        if (!passed_psn.isNull() && QDir::currentPath() == QLatin1String("/")) {
-            QCFType<CFURLRef> bundleURL(CFBundleCopyBundleURL(CFBundleGetMainBundle()));
-            QString qbundlePath = QCFString(CFURLCopyFileSystemPath(bundleURL,
-                                            kCFURLPOSIXPathStyle));
-            if (qbundlePath.endsWith(QLatin1String(".app")))
-                QDir::setCurrent(qbundlePath.section(QLatin1Char('/'), 0, -2));
-        }
-   }
-
-    QMacPasteboardMime::initialize();
-
-    qApp->setObjectName(priv->appName());
-    if (qt_is_gui_used) {
-        QColormap::initialize();
-        QFont::initialize();
-        QCursorData::initialize();
-        QCoreGraphicsPaintEngine::initialize();
-#ifndef QT_NO_ACCESSIBILITY
-        QAccessible::initialize();
-#endif
-#ifndef QT_NO_IM
-        QMacInputContext::initialize();
-        QApplicationPrivate::inputContext = new QMacInputContext;
-#endif
-        if (QApplication::desktopSettingsAware())
-            qt_mac_update_os_settings();
-#ifndef QT_MAC_USE_COCOA
-        if (!app_proc_handler) {
-            app_proc_handlerUPP = NewEventHandlerUPP(QApplicationPrivate::globalEventProcessor);
-            qt_init_app_proc_handler();
-        }
-
-#endif
-        if (!app_proc_ae_handlerUPP && !QApplication::testAttribute(Qt::AA_MacPluginApplication)) {
-            app_proc_ae_handlerUPP = AEEventHandlerUPP(QApplicationPrivate::globalAppleEventProcessor);
-            for(uint i = 0; i < sizeof(app_apple_events) / sizeof(QMacAppleEventTypeSpec); ++i) {
-                // Install apple event handler, but avoid overwriting an already
-                // existing handler (it means a 3rd party application has installed one):
-                SRefCon refCon = 0;
-                AEEventHandlerUPP current_handler = NULL;
-                AEGetEventHandler(app_apple_events[i].mac_class, app_apple_events[i].mac_id, &current_handler, &refCon, false);
-                if (!current_handler)
-                    AEInstallEventHandler(app_apple_events[i].mac_class, app_apple_events[i].mac_id,
-                            app_proc_ae_handlerUPP, SRefCon(qApp), false);
-            }
-        }
-
-        if (QApplicationPrivate::app_style) {
-            QEvent ev(QEvent::Style);
-            qt_sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
-        }
-    }
-    if (QApplication::desktopSettingsAware())
-        QApplicationPrivate::qt_mac_apply_settings();
-
-    // Cocoa application delegate
-#ifdef QT_MAC_USE_COCOA
-    NSApplication *cocoaApp = [QT_MANGLE_NAMESPACE(QNSApplication) sharedApplication];
-    qt_redirectNSApplicationSendEvent();
-
-    QMacCocoaAutoReleasePool pool;
-    id oldDelegate = [cocoaApp delegate];
-    QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *newDelegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
-    Q_ASSERT(newDelegate);
-    [newDelegate setQtPrivate:priv];
-    // Only do things that make sense to do once, otherwise we crash.
-    if (oldDelegate != newDelegate && !QApplication::testAttribute(Qt::AA_MacPluginApplication)) {
-        [newDelegate setReflectionDelegate:oldDelegate];
-        [cocoaApp setDelegate:newDelegate];
-
-        QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *qtMenuLoader = [[QT_MANGLE_NAMESPACE(QCocoaMenuLoader) alloc] init];
-        qt_mac_loadMenuNib(qtMenuLoader);
-
-        [cocoaApp setMenu:[qtMenuLoader menu]];
-        [newDelegate setMenuLoader:qtMenuLoader];
-    }
-#endif
-    // Register for Carbon tablet proximity events on the event monitor target.
-    // This means that we should receive proximity events even when we aren't the active application.
-    if (!tablet_proximity_handler) {
-        tablet_proximity_UPP = NewEventHandlerUPP(QApplicationPrivate::tabletProximityCallback);
-        qt_init_tablet_proximity_handler();
-    }
-   priv->native_modal_dialog_active = false;
-
-   qt_mac_read_fontsmoothing_settings();
-}
-
-void qt_release_apple_event_handler()
-{
-    if(app_proc_ae_handlerUPP) {
-        for(uint i = 0; i < sizeof(app_apple_events) / sizeof(QMacAppleEventTypeSpec); ++i)
-            AERemoveEventHandler(app_apple_events[i].mac_class, app_apple_events[i].mac_id,
-                    app_proc_ae_handlerUPP, true);
-        DisposeAEEventHandlerUPP(app_proc_ae_handlerUPP);
-        app_proc_ae_handlerUPP = 0;
-    }
-}
-
-/*****************************************************************************
-  qt_cleanup() - cleans up when the application is finished
- *****************************************************************************/
-
-void qt_cleanup()
-{
-    CGDisplayRemoveReconfigurationCallback(qt_mac_display_change_callbk, 0);
-    CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter();
-    CFNotificationCenterRemoveObserver(center, qApp, kCMDeviceUnregisteredNotification, 0);
-    CFNotificationCenterRemoveObserver(center, qApp, kCMDefaultDeviceNotification, 0);
-    CFNotificationCenterRemoveObserver(center, qApp, kCMDeviceProfilesNotification, 0);
-    CFNotificationCenterRemoveObserver(center, qApp, kCMDefaultDeviceProfileNotification, 0);
-
-#ifndef QT_MAC_USE_COCOA
-    qt_release_app_proc_handler();
-    if (app_proc_handlerUPP) {
-        DisposeEventHandlerUPP(app_proc_handlerUPP);
-        app_proc_handlerUPP = 0;
-    }
-#endif
-    qt_release_apple_event_handler();
-
-#ifdef QT_MAC_USE_COCOA
-    qt_resetNSApplicationSendEvent();
-#endif
-
-    qt_release_tablet_proximity_handler();
-    if (tablet_proximity_UPP)
-        DisposeEventHandlerUPP(tablet_proximity_UPP);
-
-    QPixmapCache::clear();
-    if (qt_is_gui_used) {
-#ifndef QT_NO_ACCESSIBILITY
-        QAccessible::cleanup();
-#endif
-#ifndef QT_NO_IM
-        QMacInputContext::cleanup();
-#endif
-        QCursorData::cleanup();
-        QFont::cleanup();
-        QColormap::cleanup();
-        if (qt_mac_safe_pdev) {
-            delete qt_mac_safe_pdev;
-            qt_mac_safe_pdev = 0;
-        }
-        extern void qt_mac_unregister_widget(); // qapplication_mac.cpp
-        qt_mac_unregister_widget();
-    }
-}
-
-/*****************************************************************************
-  Platform specific QApplication members
- *****************************************************************************/
-extern QWidget * mac_mouse_grabber;
-extern QWidget * mac_keyboard_grabber;
-
-#ifndef QT_NO_CURSOR
-
-/*****************************************************************************
-  QApplication cursor stack
- *****************************************************************************/
-
-void QApplication::setOverrideCursor(const QCursor &cursor)
-{
-    qApp->d_func()->cursor_list.prepend(cursor);
-
-#ifdef QT_MAC_USE_COCOA
-    qt_mac_update_cursor();
-#else
-    if (qApp && qApp->activeWindow())
-        qt_mac_set_cursor(&qApp->d_func()->cursor_list.first());
-#endif
-}
-
-void QApplication::restoreOverrideCursor()
-{
-    if (qApp->d_func()->cursor_list.isEmpty())
-        return;
-    qApp->d_func()->cursor_list.removeFirst();
-
-#ifdef QT_MAC_USE_COCOA
-    qt_mac_update_cursor();
-#else
-    if (qApp && qApp->activeWindow()) {
-        const QCursor def(Qt::ArrowCursor);
-        qt_mac_set_cursor(qApp->d_func()->cursor_list.isEmpty() ? &def : &qApp->d_func()->cursor_list.first());
-    }
-#endif
-}
-#endif // QT_NO_CURSOR
-
-Qt::KeyboardModifiers QApplication::queryKeyboardModifiers()
-{
-    return qt_mac_get_modifiers(GetCurrentEventKeyModifiers());
-}
-
-QWidget *QApplication::topLevelAt(const QPoint &p)
-{
-#ifndef QT_MAC_USE_COCOA
-    QWidget *widget;
-    qt_mac_window_at(p.x(), p.y(), &widget);
-    return widget;
-#else
-    // Use a cache to avoid iterate through the whole list of windows for all
-    // calls to to topLevelAt. We e.g. do this for each and every mouse
-    // move since we need to find the widget under mouse:
-    if (topLevelAt_cache && topLevelAt_cache->frameGeometry().contains(p))
-        return topLevelAt_cache;
-
-    // INVARIANT: Cache miss. Go through the list if windows instead:
-    QMacCocoaAutoReleasePool pool;
-    NSPoint cocoaPoint = flipPoint(p);
-    NSInteger windowCount;
-    NSCountWindows(&windowCount);
-    if (windowCount <= 0)
-        return 0;  // There's no window to find!
-
-    QVarLengthArray<NSInteger> windowList(windowCount);
-    NSWindowList(windowCount, windowList.data());
-    int firstQtWindowFound = -1;
-    for (int i = 0; i < windowCount; ++i) {
-        NSWindow *window = [[NSApplication sharedApplication] windowWithWindowNumber:windowList[i]];
-        if (window) {
-            QWidget *candidateWindow = [window QT_MANGLE_NAMESPACE(qt_qwidget)];
-            if (candidateWindow && firstQtWindowFound == -1)
-                firstQtWindowFound = i;
-
-            if (NSPointInRect(cocoaPoint, [window frame])) {
-                // Check to see if there's a hole in the window where the mask is.
-                // If there is, we should just continue to see if there is a window below.
-                if (candidateWindow && !candidateWindow->mask().isEmpty()) {
-                    QPoint localPoint = candidateWindow->mapFromGlobal(p);
-                    if (!candidateWindow->mask().contains(localPoint))
-                        continue;
-                    else
-                        return candidateWindow;
-                } else {
-                    if (i == firstQtWindowFound) {
-                        // The cache will only work when the window under mouse is
-                        // top most (that is, not partially obscured by other windows.
-                        // And we only set it if no mask is present to optimize for the common case:
-                        topLevelAt_cache = candidateWindow;
-                    }
-                    return candidateWindow;
-                }
-            }
-        }
-    }
-
-    topLevelAt_cache = 0;
-    return 0;
-#endif
-}
-
-/*****************************************************************************
-  Main event loop
- *****************************************************************************/
-
-bool QApplicationPrivate::modalState()
-{
-    return app_do_modal;
-}
-
-#ifdef QT_MAC_USE_COCOA
-#endif
-
-void QApplicationPrivate::enterModal_sys(QWidget *widget)
-{
-#ifdef DEBUG_MODAL_EVENTS
-    Q_ASSERT(widget);
-    qDebug("Entering modal state with %s::%s::%p (%d)", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(),
-            widget, qt_modal_stack ? (int)qt_modal_stack->count() : -1);
-#endif
-    if (!qt_modal_stack)
-        qt_modal_stack = new QWidgetList;
-
-    dispatchEnterLeave(0, qt_last_mouse_receiver);
-    qt_last_mouse_receiver = 0;
-
-    qt_modal_stack->insert(0, widget);
-    if (!app_do_modal)
-        qt_event_request_menubarupdate();
-    app_do_modal = true;
-    qt_button_down = 0;
-
-#ifdef QT_MAC_USE_COCOA
-    if (!qt_mac_is_macsheet(widget))
-        QEventDispatcherMacPrivate::beginModalSession(widget);
-#endif
-}
-
-void QApplicationPrivate::leaveModal_sys(QWidget *widget)
-{
-    if (qt_modal_stack && qt_modal_stack->removeAll(widget)) {
-#ifdef DEBUG_MODAL_EVENTS
-        qDebug("Leaving modal state with %s::%s::%p (%d)", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(),
-               widget, qt_modal_stack->count());
-#endif
-        if (qt_modal_stack->isEmpty()) {
-            delete qt_modal_stack;
-            qt_modal_stack = 0;
-            QPoint p(QCursor::pos());
-            app_do_modal = false;
-            QWidget* w = 0;
-            if (QWidget *grabber = QWidget::mouseGrabber())
-                w = grabber;
-            else
-                w = QApplication::widgetAt(p.x(), p.y());
-            dispatchEnterLeave(w, qt_last_mouse_receiver); // send synthetic enter event
-            qt_last_mouse_receiver = w;
-        }
-#ifdef QT_MAC_USE_COCOA
-        if (!qt_mac_is_macsheet(widget))
-            QEventDispatcherMacPrivate::endModalSession(widget);
-#endif
-    }
-#ifdef DEBUG_MODAL_EVENTS
-    else qDebug("Failure to remove %s::%s::%p -- %p", widget->metaObject()->className(), widget->objectName().toLocal8Bit().constData(), widget, qt_modal_stack);
-#endif
-    app_do_modal = (qt_modal_stack != 0);
-    if (!app_do_modal)
-        qt_event_request_menubarupdate();
-}
-
-QWidget *QApplicationPrivate::tryModalHelper_sys(QWidget *top)
-{
-#ifndef QT_MAC_USE_COCOA
-    if(top && qt_mac_is_macsheet(top) && !IsWindowVisible(qt_mac_window_for(top))) {
-        if(OSWindowRef wp = GetFrontWindowOfClass(kSheetWindowClass, true)) {
-            if(QWidget *sheet = qt_mac_find_window(wp))
-                top = sheet;
-        }
-    }
-#endif
-    return top;
-}
-
-#ifndef QT_MAC_USE_COCOA
-static bool qt_try_modal(QWidget *widget, EventRef event)
-{
-    QWidget * top = 0;
-
-    if (QApplicationPrivate::tryModalHelper(widget, &top))
-        return true;
-
-    // INVARIANT: widget is modally shaddowed within its
-    // window, and should therefore not handle the event.
-    // However, if the window is not active, the event
-    // might suggest that we should bring it to front:
-
-    bool block_event = false;
-
-    if (event) {
-        switch (GetEventClass(event)) {
-        case kEventClassMouse:
-        case kEventClassKeyboard:
-            block_event = true;
-            break;
-        }
-    }
-
-    QWidget *activeWidget = QApplication::activeWindow();
-    if ((!activeWidget || QApplicationPrivate::isBlockedByModal(activeWidget)) &&
-       top->isWindow() && block_event && !QApplicationPrivate::native_modal_dialog_active)
-        top->raise();
-
-#ifdef DEBUG_MODAL_EVENTS
-    qDebug("%s:%d -- final decision! (%s)", __FILE__, __LINE__, block_event ? "false" : "true");
-#endif
-    return !block_event;
-}
-#endif
-
-OSStatus QApplicationPrivate::tabletProximityCallback(EventHandlerCallRef, EventRef carbonEvent,
-                                                      void *)
-{
-    OSType eventClass = GetEventClass(carbonEvent);
-    UInt32 eventKind = GetEventKind(carbonEvent);
-    if (eventClass != kEventClassTablet || eventKind != kEventTabletProximity)
-        return eventNotHandledErr;
-
-    // Get the current point of the device and its unique ID.
-    ::TabletProximityRec proxRec;
-    GetEventParameter(carbonEvent, kEventParamTabletProximityRec, typeTabletProximityRec, 0,
-                      sizeof(proxRec), 0, &proxRec);
-    qt_dispatchTabletProximityEvent(proxRec);
-    return noErr;
-}
-
-OSStatus
-QApplicationPrivate::globalEventProcessor(EventHandlerCallRef er, EventRef event, void *data)
-{
-#ifndef QT_MAC_USE_COCOA
-    QApplication *app = (QApplication *)data;
-    QScopedLoopLevelCounter loopLevelCounter(app->d_func()->threadData);
-    long result;
-    if (app->filterEvent(&event, &result))
-        return result;
-    if(app->macEventFilter(er, event)) //someone else ate it
-        return noErr;
-    QPointer<QWidget> widget;
-
-    /*We assume all events are handled and in
-      the code below we set it to false when we know we didn't handle it, this
-      will let rogue events through (shouldn't really happen, but better safe
-      than sorry) */
-    bool handled_event=true;
-    UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
-    switch(eclass)
-    {
-    case kEventClassQt:
-        if(ekind == kEventQtRequestShowSheet) {
-            request_showsheet_pending = 0;
-            QWidget *widget = 0;
-            GetEventParameter(event, kEventParamQWidget, typeQWidget, 0,
-                              sizeof(widget), 0, &widget);
-            if(widget) {
-                if (widget->macEvent(er, event))
-                    return noErr;
-                WindowPtr window = qt_mac_window_for(widget);
-                bool just_show = !qt_mac_is_macsheet(widget);
-                if(!just_show) {
-                    OSStatus err = ShowSheetWindow(window, qt_mac_window_for(widget->parentWidget()));
-                    if(err != noErr)
-                        qWarning("Qt: QWidget: Unable to show as sheet %s::%s [%ld]", widget->metaObject()->className(),
-                                 widget->objectName().toLocal8Bit().constData(), long(err));
-                    just_show = true;
-                }
-                if(just_show) //at least the window will be visible, but the sheet flag doesn't work sadly (probalby too many sheets)
-                    ShowHide(window, true);
-            }
-        } else if(ekind == kEventQtRequestWindowChange) {
-            qt_mac_event_release(request_window_change_pending);
-        } else if(ekind == kEventQtRequestMenubarUpdate) {
-            qt_mac_event_release(request_menubarupdate_pending);
-            QMenuBar::macUpdateMenuBar();
-        } else if(ekind == kEventQtRequestActivate) {
-            qt_mac_event_release(request_activate_pending.event);
-            if(request_activate_pending.widget) {
-                QWidget *tlw = request_activate_pending.widget->window();
-                if (tlw->macEvent(er, event))
-                    return noErr;
-                request_activate_pending.widget = 0;
-                tlw->activateWindow();
-                SelectWindow(qt_mac_window_for(tlw));
-            }
-        } else if(ekind == kEventQtRequestContext) {
-            bool send = false;
-            if ((send = (event == request_context_pending)))
-                qt_mac_event_release(request_context_pending);
-            if(send) {
-                //figure out which widget to send it to
-                QPoint where = QCursor::pos();
-                QWidget *widget = 0;
-                GetEventParameter(event, kEventParamQWidget, typeQWidget, 0,
-                                  sizeof(widget), 0, &widget);
-                if(!widget) {
-                    if(qt_button_down)
-                        widget = qt_button_down;
-                    else
-                        widget = QApplication::widgetAt(where.x(), where.y());
-                }
-                if(widget && !isBlockedByModal(widget)) {
-                    if (widget->macEvent(er, event))
-                        return noErr;
-                    QPoint plocal(widget->mapFromGlobal(where));
-                    const Qt::KeyboardModifiers keyboardModifiers = qt_mac_get_modifiers(GetCurrentEventKeyModifiers());
-                    QContextMenuEvent qme(QContextMenuEvent::Mouse, plocal, where, keyboardModifiers);
-                    QApplication::sendEvent(widget, &qme);
-                    if(qme.isAccepted()) { //once this happens the events before are pitched
-                        qt_button_down = 0;
-                        qt_mac_dblclick.last_widget = 0;
-                    }
-                } else {
-                    handled_event = false;
-                }
-            }
-        } else {
-            handled_event = false;
-        }
-        break;
-    case kEventClassTablet:
-        switch (ekind) {
-        case kEventTabletProximity:
-            // Get the current point of the device and its unique ID.
-            ::TabletProximityRec proxRec;
-            GetEventParameter(event, kEventParamTabletProximityRec, typeTabletProximityRec, 0,
-                              sizeof(proxRec), 0, &proxRec);
-            qt_dispatchTabletProximityEvent(proxRec);
-        }
-        break;
-    case kEventClassMouse:
-    {
-        static const int kEventParamQAppSeenMouseEvent = 'QASM';
-        // Check if we've seen the event, if we have we shouldn't process
-        // it again as it may lead to spurious "double events"
-        bool seenEvent;
-        if (GetEventParameter(event, kEventParamQAppSeenMouseEvent,
-                              typeBoolean, 0, sizeof(bool), 0, &seenEvent) == noErr) {
-            if (seenEvent)
-                return eventNotHandledErr;
-        }
-        seenEvent = true;
-        SetEventParameter(event, kEventParamQAppSeenMouseEvent, typeBoolean,
-                          sizeof(bool), &seenEvent);
-
-        Point where;
-        bool inNonClientArea = false;
-        GetEventParameter(event, kEventParamMouseLocation, typeQDPoint, 0,
-                          sizeof(where), 0, &where);
-#if defined(DEBUG_MOUSE_MAPS)
-        const char *edesc = 0;
-        switch(ekind) {
-        case kEventMouseDown: edesc = "MouseButtonPress"; break;
-        case kEventMouseUp: edesc = "MouseButtonRelease"; break;
-        case kEventMouseDragged: case kEventMouseMoved: edesc = "MouseMove"; break;
-        case kEventMouseScroll: edesc = "MouseWheelScroll"; break;
-        case kEventMouseWheelMoved: edesc = "MouseWheelMove"; break;
-        }
-        if(ekind == kEventMouseDown || ekind == kEventMouseUp)
-            qDebug("Handling mouse: %s", edesc);
-#endif
-        QEvent::Type etype = QEvent::None;
-        Qt::KeyboardModifiers modifiers;
-        {
-            UInt32 mac_modifiers = 0;
-            GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, 0,
-                              sizeof(mac_modifiers), 0, &mac_modifiers);
-            modifiers = qt_mac_get_modifiers(mac_modifiers);
-        }
-        Qt::MouseButtons buttons;
-        {
-            UInt32 mac_buttons = 0;
-            GetEventParameter(event, kEventParamMouseChord, typeUInt32, 0,
-                              sizeof(mac_buttons), 0, &mac_buttons);
-            if (ekind != kEventMouseWheelMoved)
-                buttons = qt_mac_get_buttons(mac_buttons);
-            else
-                buttons = QApplication::mouseButtons();
-        }
-
-        int wheel_deltaX = 0;
-        int wheel_deltaY = 0;
-        static EventRef compatibilityEvent = 0;
-
-        if (ekind == kEventMouseScroll) {
-            // kEventMouseScroll is the new way of dealing with mouse wheel
-            // events (kEventMouseWheelMoved was the old). kEventMouseScroll results
-            // in much smoother scrolling when using Mighty Mouse or TrackPad. For
-            // compatibility with older applications, carbon will also send us
-            // kEventMouseWheelMoved events if we dont eat this event
-            // (actually two events; one for horizontal and one for vertical).
-            // As a results of this, and to make sure we dont't receive duplicate events,
-            // we try to detect when this happend by checking the 'compatibilityEvent'.
-            // Since delta is delivered as pixels rather than degrees, we need to
-            // convert from pixels to degrees in a sensible manner.
-            // It looks like 1/4 degrees per pixel behaves most native.
-            // (NB: Qt expects the unit for delta to be 8 per degree):
-            const int pixelsToDegrees = 2;
-            SInt32 mdelt = 0;
-            GetEventParameter(event, kEventParamMouseWheelSmoothHorizontalDelta, typeSInt32, 0,
-                              sizeof(mdelt), 0, &mdelt);
-            wheel_deltaX = mdelt * pixelsToDegrees;
-            mdelt = 0;
-            GetEventParameter(event, kEventParamMouseWheelSmoothVerticalDelta, typeSInt32, 0,
-                              sizeof(mdelt), 0, &mdelt);
-            wheel_deltaY = mdelt * pixelsToDegrees;
-            GetEventParameter(event, kEventParamEventRef, typeEventRef, 0,
-                              sizeof(compatibilityEvent), 0, &compatibilityEvent);
-        } else if (ekind == kEventMouseWheelMoved) {
-            if (event != compatibilityEvent) {
-                compatibilityEvent = 0;
-                int mdelt = 0;
-                GetEventParameter(event, kEventParamMouseWheelDelta, typeSInt32, 0,
-                        sizeof(mdelt), 0, &mdelt);
-                EventMouseWheelAxis axis;
-                GetEventParameter(event, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0,
-                        sizeof(axis), 0, &axis);
-
-                // Remove acceleration, and use either -120 or 120 as delta:
-                if (axis == kEventMouseWheelAxisX)
-                    wheel_deltaX = qBound(-120, int(mdelt * 10000), 120);
-                else
-                    wheel_deltaY = qBound(-120, int(mdelt * 10000), 120);
-            }
-        }
-
-        Qt::MouseButton button = Qt::NoButton;
-        if(ekind == kEventMouseDown || ekind == kEventMouseUp) {
-            EventMouseButton mac_button = 0;
-            GetEventParameter(event, kEventParamMouseButton, typeMouseButton, 0,
-                              sizeof(mac_button), 0, &mac_button);
-            button = qt_mac_get_button(mac_button);
-        }
-
-        switch(ekind) {
-        case kEventMouseDown:
-            etype = QEvent::MouseButtonPress;
-            break;
-        case kEventMouseUp:
-            etype = QEvent::MouseButtonRelease;
-            break;
-        case kEventMouseDragged:
-        case kEventMouseMoved:
-            etype = QEvent::MouseMove;
-            break;
-        }
-
-        const bool inPopupMode = app->d_func()->inPopupMode();
-
-        // A click outside a popup closes the popup. Make sure
-        // that no events are generated for the release part of that click.
-        // (The press goes to the popup and closes it.)
-        if (etype == QEvent::MouseButtonPress) {
-            qt_mac_previous_press_in_popup_mode = inPopupMode;
-        } else if (qt_mac_previous_press_in_popup_mode && !inPopupMode && etype == QEvent::MouseButtonRelease) {
-            qt_mac_previous_press_in_popup_mode = false;
-            handled_event = true;
-#if defined(DEBUG_MOUSE_MAPS)
-            qDebug("Bail out early due to qt_mac_previous_press_in_popup_mode");
-#endif
-            break; // break from case kEventClassMouse
-        }
-
-        //figure out which widget to send it to
-        if(inPopupMode) {
-            QWidget *popup = qApp->activePopupWidget();
-            if (qt_button_down && qt_button_down->window() == popup) {
-                widget = qt_button_down;
-            } else {
-                QPoint pos = popup->mapFromGlobal(QPoint(where.h, where.v));
-                widget = popup->childAt(pos);
-            }
-            if(!widget)
-                widget = popup;
-        } else {
-            if(mac_mouse_grabber) {
-                widget = mac_mouse_grabber;
-            } else if (qt_button_down) {
-                widget = qt_button_down;
-            } else {
-                {
-                    WindowPtr window = 0;
-                    if(GetEventParameter(event, kEventParamWindowRef, typeWindowRef, 0,
-                                         sizeof(window), 0, &window) != noErr)
-                        FindWindowOfClass(&where, kAllWindowClasses, &window, 0);
-                    if(window) {
-                        HIViewRef hiview;
-                        if(HIViewGetViewForMouseEvent(HIViewGetRoot(window), event, &hiview) == noErr) {
-                            widget = QWidget::find((WId)hiview);
-                            if (widget) {
-                                // Make sure we didn't pass over a widget with a "fake hole" in it.
-                                QWidget *otherWidget = QApplication::widgetAt(where.h, where.v);
-                                if (otherWidget && otherWidget->testAttribute(Qt::WA_MouseNoMask))
-                                    widget = otherWidget;
-                            }
-                        }
-                    }
-                }
-                if(!widget) //fallback
-                    widget = QApplication::widgetAt(where.h, where.v);
-                if(ekind == kEventMouseUp && widget) {
-                    short part = qt_mac_window_at(where.h, where.v);
-                    if(part == inDrag) {
-                        UInt32 count = 0;
-                        GetEventParameter(event, kEventParamClickCount, typeUInt32, NULL,
-                                          sizeof(count), NULL, &count);
-                        if(count == 2 && qt_mac_collapse_on_dblclick) {
-                            if (widget->macEvent(er, event))
-                                return noErr;
-                            widget->setWindowState(widget->windowState() | Qt::WindowMinimized);
-                            //we send a hide to be like X11/Windows
-                            QEvent e(QEvent::Hide);
-                            QApplication::sendSpontaneousEvent(widget, &e);
-                            break;
-                        }
-                    }
-                }
-            }
-        }
-        if (widget && widget->macEvent(er, event))
-            return noErr;
-        WindowPartCode wpc = qt_mac_window_at(where.h, where.v, 0);
-        if (wpc == inProxyIcon && modifiers == Qt::ControlModifier && buttons != Qt::NoButton) {
-            QIconDragEvent e;
-            QApplication::sendSpontaneousEvent(widget, &e);
-            if (e.isAccepted()) {
-                return noErr; // IconDrag ate it.
-            }
-        }
-        if (inPopupMode == false
-                && (qt_button_down == 0 || qt_button_down_in_content == false)
-                && (wpc != inContent && wpc != inStructure)) {
-            inNonClientArea = true;
-            switch (etype) {
-            case QEvent::MouseButtonPress: {
-                UInt32 count = 0;
-                GetEventParameter(event, kEventParamClickCount, typeUInt32, 0,
-                                      sizeof(count), 0, &count);
-                if(count % 2 || count == 0) {
-                    etype = QEvent::NonClientAreaMouseButtonPress;
-                } else {
-                    etype = QEvent::NonClientAreaMouseButtonDblClick;
-                }} break;
-            case QEvent::MouseButtonRelease:
-                etype = QEvent::NonClientAreaMouseButtonRelease;
-                break;
-            case QEvent::MouseMove:
-                if (widget == 0 || widget->hasMouseTracking())
-                    etype = QEvent::NonClientAreaMouseMove;
-                break;
-            default:
-                break;
-            }
-        }
-
-        if(qt_mac_find_window((FrontWindow()))) { //set the cursor up
-            QCursor cursor(Qt::ArrowCursor);
-            QWidget *cursor_widget = widget;
-            if(cursor_widget && cursor_widget == qt_button_down && ekind == kEventMouseUp)
-                cursor_widget = QApplication::widgetAt(where.h, where.v);
-            if(cursor_widget) { //only over the app, do we set a cursor..
-                if(!qApp->d_func()->cursor_list.isEmpty()) {
-                    cursor = qApp->d_func()->cursor_list.first();
-                } else {
-                    for(; cursor_widget; cursor_widget = cursor_widget->parentWidget()) {
-                        QWExtra *extra = cursor_widget->d_func()->extraData();
-                        if(extra && extra->curs && cursor_widget->isEnabled()) {
-                            cursor = *extra->curs;
-                            break;
-                        }
-                    }
-                }
-            }
-            qt_mac_set_cursor(&cursor);
-        }
-
-        //This mouse button state stuff looks like this on purpose
-        //although it looks hacky it is VERY intentional..
-        if(widget && app_do_modal && !qt_try_modal(widget, event)) {
-            if(ekind == kEventMouseDown && qt_mac_is_macsheet(QApplication::activeModalWidget()))
-                QApplication::activeModalWidget()->parentWidget()->activateWindow(); //sheets have a parent
-            handled_event = false;
-#if defined(DEBUG_MOUSE_MAPS)
-            qDebug("Bail out early due to qt_try_modal");
-#endif
-            break;
-        }
-
-        UInt32 tabletEventType = 0;
-        GetEventParameter(event, kEventParamTabletEventType, typeUInt32, 0,
-                          sizeof(tabletEventType), 0, &tabletEventType);
-        if (tabletEventType == kEventTabletPoint) {
-            TabletPointRec tabletPointRec;
-            GetEventParameter(event, kEventParamTabletPointRec, typeTabletPointRec, 0,
-                              sizeof(tabletPointRec), 0, &tabletPointRec);
-            QEvent::Type t = QEvent::TabletMove; //default
-            int new_tablet_button_state = tabletPointRec.buttons ? 1 : 0;
-            if (new_tablet_button_state != tablet_button_state)
-                if (new_tablet_button_state)
-                    t = QEvent::TabletPress;
-                else
-                    t = QEvent::TabletRelease;
-            tablet_button_state = new_tablet_button_state;
-
-            QMacTabletHash *tabletHash = qt_mac_tablet_hash();
-            if (!tabletHash->contains(tabletPointRec.deviceID) && t != QEvent::TabletRelease) {
-                // Never discard TabletRelease events as they may be delivered *after* TabletLeaveProximity events
-                qWarning("handleTabletEvent: This tablet device is unknown"
-                         " (received no proximity event for it). Discarding event.");
-                return false;
-            }
-            QTabletDeviceData &deviceData = tabletHash->operator[](tabletPointRec.deviceID);
-            if (t == QEvent::TabletPress) {
-                deviceData.widgetToGetPress = widget;
-            } else if (t == QEvent::TabletRelease && deviceData.widgetToGetPress) {
-                widget = deviceData.widgetToGetPress;
-                deviceData.widgetToGetPress = 0;
-            }
-
-            if (widget) {
-                int tiltX = ((int)tabletPointRec.tiltX)/(32767/64); // 32K -> 60
-                int tiltY = ((int)tabletPointRec.tiltY)/(-32767/64); // 32K -> 60
-                HIPoint hiPoint;
-                GetEventParameter(event, kEventParamMouseLocation, typeHIPoint, 0, sizeof(HIPoint), 0, &hiPoint);
-                QPointF hiRes(hiPoint.x, hiPoint.y);
-                QPoint global(where.h, where.v);
-
-
-
-                QPoint local(widget->mapFromGlobal(global));
-                int z = 0;
-                qreal rotation = 0.0;
-                qreal tp = 0.0;
-                // Again from the Wacom.h header
-
-                if (deviceData.capabilityMask & 0x0200)     // Z-axis
-                    z = tabletPointRec.absZ;
-
-                if (deviceData.capabilityMask & 0x0800)  // Tangential pressure
-                    tp = tabletPointRec.tangentialPressure / 32767.0;
-
-                if (deviceData.capabilityMask & 0x2000) // Rotation
-                    rotation = qreal(tabletPointRec.rotation) / 64.0;
-
-                QTabletEvent e(t, local, global, hiRes, deviceData.tabletDeviceType,
-                               deviceData.tabletPointerType,
-                               qreal(tabletPointRec.pressure / qreal(0xffff)), tiltX, tiltY,
-                               tp, rotation, z, modifiers, deviceData.tabletUniqueID);
-                QApplication::sendSpontaneousEvent(widget, &e);
-                if (e.isAccepted()) {
-                    if (t == QEvent::TabletPress) {
-                        qt_button_down = widget;
-                    } else if (t == QEvent::TabletRelease) {
-                        qt_button_down = 0;
-                    }
-#if defined(DEBUG_MOUSE_MAPS)
-                    qDebug("Bail out early due to tablet acceptance");
-#endif
-                    break;
-                }
-            }
-        }
-
-        if(ekind == kEventMouseDown) {
-            qt_mac_no_click_through_mode = false;
-            const short windowPart = qt_mac_window_at(where.h, where.v, 0);
-            // Menubar almost always wins.
-            if (!inPopupMode && windowPart == inMenuBar) {
-                MenuSelect(where); //allow menu tracking
-                return noErr;
-            }
-
-            if (widget && !(GetCurrentKeyModifiers() & cmdKey)) {
-                extern bool qt_isGenuineQWidget(const QWidget *); // qwidget_mac.cpp
-                QWidget *window = widget->window();
-                bool genuineQtWidget = qt_isGenuineQWidget(widget);  // the widget, not the window.
-                window->raise();
-
-                bool needActivate = (window->windowType() != Qt::Desktop)
-                                     && (window->windowType() != Qt::Popup)
-                                     && !qt_mac_is_macsheet(window);
-                if (needActivate && (!window->isModal() && qobject_cast<QDockWidget *>(window)))
-                    needActivate = false;
-
-                if (genuineQtWidget && needActivate)
-                    needActivate = !window->isActiveWindow()
-                                    || !IsWindowActive(qt_mac_window_for(window));
-
-                if (needActivate) {
-                    window->activateWindow();
-                    if (!qt_mac_can_clickThrough(widget)) {
-                        qt_mac_no_click_through_mode = true;
-                        handled_event = false;
-#if defined(DEBUG_MOUSE_MAPS)
-                        qDebug("Bail out early due to qt_mac_canClickThrough %s::%s", widget->metaObject()->className(),
-                                widget->objectName().toLocal8Bit().constData());
-#endif
-                        break;
-                    }
-                }
-            }
-
-            if(qt_mac_dblclick.last_widget &&
-               qt_mac_dblclick.last_x != -1 && qt_mac_dblclick.last_y != -1 &&
-               QRect(qt_mac_dblclick.last_x-2, qt_mac_dblclick.last_y-2, 4, 4).contains(QPoint(where.h, where.v))) {
-                if(qt_mac_dblclick.use_qt_time_limit) {
-                    EventTime now = GetEventTime(event);
-                    if(qt_mac_dblclick.last_time != -2 && qt_mac_dblclick.last_widget == widget &&
-                       now - qt_mac_dblclick.last_time <= ((double)QApplicationPrivate::mouse_double_click_time)/1000 &&
-                       qt_mac_dblclick.last_button == button)
-                        etype = QEvent::MouseButtonDblClick;
-                } else {
-                    UInt32 count = 0;
-                    GetEventParameter(event, kEventParamClickCount, typeUInt32, 0,
-                                      sizeof(count), 0, &count);
-                    if(!(count % 2) && qt_mac_dblclick.last_modifiers == modifiers &&
-                       qt_mac_dblclick.last_widget == widget && qt_mac_dblclick.last_button == button)
-                        etype = QEvent::MouseButtonDblClick;
-                }
-                if(etype == QEvent::MouseButtonDblClick)
-                    qt_mac_dblclick.last_widget = 0;
-            }
-            if(etype != QEvent::MouseButtonDblClick) {
-                qt_mac_dblclick.last_x = where.h;
-                qt_mac_dblclick.last_y = where.v;
-            } else {
-                qt_mac_dblclick.last_x = qt_mac_dblclick.last_y = -1;
-            }
-        } else if(qt_mac_no_click_through_mode) {
-            if(ekind == kEventMouseUp)
-                qt_mac_no_click_through_mode = false;
-            handled_event = false;
-#if defined(DEBUG_MOUSE_MAPS)
-            qDebug("Bail out early due to qt_mac_no_click_through_mode");
-#endif
-            break;
-        }
-
-        QPointer<QWidget> leaveAfterRelease = 0;
-        switch(ekind) {
-        case kEventMouseUp:
-            if (!buttons) {
-                if (!inPopupMode && !QWidget::mouseGrabber())
-                    leaveAfterRelease = qt_button_down;
-                qt_button_down = 0;
-            }
-            break;
-        case kEventMouseDown: {
-            if (!qt_button_down)
-                qt_button_down = widget;
-            WindowPartCode wpc = qt_mac_window_at(where.h, where.v, 0);
-            qt_button_down_in_content = (wpc == inContent || wpc == inStructure);
-            break;  }
-        }
-
-        // Check if we should send enter/leave events:
-        switch(ekind) {
-        case kEventMouseDragged:
-        case kEventMouseMoved:
-        case kEventMouseUp:
-        case kEventMouseDown: {
-            // If we are in popup mode, widget will point to the current popup no matter
-            // where the mouse cursor is. In that case find out if the mouse cursor is
-            // really over the popup in order to send correct enter / leave envents.
-            QWidget * const enterLeaveWidget = (inPopupMode || ekind == kEventMouseUp) ?
-                    QApplication::widgetAt(where.h, where.v) :  static_cast<QWidget*>(widget);
-
-            if ((QWidget *) qt_last_mouse_receiver != enterLeaveWidget || inNonClientArea) {
-#ifdef DEBUG_MOUSE_MAPS
-                qDebug("Entering: %p - %s (%s), Leaving %s (%s)", (QWidget*)enterLeaveWidget,
-                       enterLeaveWidget ? enterLeaveWidget->metaObject()->className() : "none",
-                       enterLeaveWidget ? enterLeaveWidget->objectName().toLocal8Bit().constData() : "",
-                       qt_last_mouse_receiver ? qt_last_mouse_receiver->metaObject()->className() : "none",
-                       qt_last_mouse_receiver ? qt_last_mouse_receiver->objectName().toLocal8Bit().constData() : "");
-#endif
-
-                QWidget * const mouseGrabber = QWidget::mouseGrabber();
-
-                if (inPopupMode) {
-                    QWidget *enter = enterLeaveWidget;
-                    QWidget *leave = qt_last_mouse_receiver;
-                    if (mouseGrabber) {
-                        QWidget * const popupWidget = qApp->activePopupWidget();
-                        if (leave == popupWidget)
-                            enter = mouseGrabber;
-                        if (enter == popupWidget)
-                            leave = mouseGrabber;
-                        if ((enter == mouseGrabber && leave == popupWidget)
-                            || (leave == mouseGrabber  && enter == popupWidget)) {
-                            QApplicationPrivate::dispatchEnterLeave(enter, leave);
-                            qt_last_mouse_receiver = enter;
-                        }
-                    } else {
-                        QApplicationPrivate::dispatchEnterLeave(enter, leave);
-                        qt_last_mouse_receiver = enter;
-                    }
-                } else if ((!qt_button_down || !qt_last_mouse_receiver) && !mouseGrabber && !leaveAfterRelease) {
-                    QApplicationPrivate::dispatchEnterLeave(enterLeaveWidget, qt_last_mouse_receiver);
-                    qt_last_mouse_receiver = enterLeaveWidget;
-                }
-            }
-            break; }
-        }
-
-        if(widget) {
-            QPoint p(where.h, where.v);
-            QPoint plocal(widget->mapFromGlobal(p));
-            if(etype == QEvent::MouseButtonPress) {
-                qt_mac_dblclick.last_widget = widget;
-                qt_mac_dblclick.last_modifiers = modifiers;
-                qt_mac_dblclick.last_button = button;
-                qt_mac_dblclick.last_time = GetEventTime(event);
-            }
-
-            if (wheel_deltaX || wheel_deltaY) {
-#ifndef QT_NO_WHEELEVENT
-                if (wheel_deltaX) {
-                    QWheelEvent qwe(plocal, p, wheel_deltaX, buttons, modifiers, Qt::Horizontal);
-                    QApplication::sendSpontaneousEvent(widget, &qwe);
-                    if (!qwe.isAccepted() && QApplicationPrivate::focus_widget && QApplicationPrivate::focus_widget != widget) {
-                        QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(p), p,
-                                wheel_deltaX, buttons, modifiers, Qt::Horizontal);
-                        QApplication::sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2);
-                        if (!qwe2.isAccepted())
-                            handled_event = false;
-                    }
-                }
-                if (wheel_deltaY) {
-                    QWheelEvent qwe(plocal, p, wheel_deltaY, buttons, modifiers, Qt::Vertical);
-                    QApplication::sendSpontaneousEvent(widget, &qwe);
-                    if (!qwe.isAccepted() && QApplicationPrivate::focus_widget && QApplicationPrivate::focus_widget != widget) {
-                        QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(p), p,
-                                wheel_deltaY, buttons, modifiers, Qt::Vertical);
-                        QApplication::sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2);
-                        if (!qwe2.isAccepted())
-                            handled_event = false;
-                    }
-                }
-#endif // QT_NO_WHEELEVENT
-            } else {
-#ifdef QMAC_SPEAK_TO_ME
-                const int speak_keys = Qt::AltModifier | Qt::ShiftModifier;
-               if(etype == QMouseEvent::MouseButtonDblClick && ((modifiers & speak_keys) == speak_keys)) {
-                    QVariant v = widget->property("displayText");
-                    if(!v.isValid()) v = widget->property("text");
-                    if(!v.isValid()) v = widget->property("windowTitle");
-                    if(v.isValid()) {
-                        QString s = v.toString();
-                        s.replace(QRegExp(QString::fromLatin1("(\\&|\\<[^\\>]*\\>)")), QLatin1String(""));
-                        SpeechChannel ch;
-                        NewSpeechChannel(0, &ch);
-                        SpeakText(ch, s.toLatin1().constData(), s.length());
-                        DisposeSpeechChannel(ch);
-                    }
-                }
-#endif
-                Qt::MouseButton buttonToSend = button;
-                static bool lastButtonTranslated = false;
-                if(ekind == kEventMouseDown &&
-                   button == Qt::LeftButton && (modifiers & Qt::MetaModifier)) {
-                    buttonToSend = Qt::RightButton;
-                    lastButtonTranslated = true;
-                } else if(ekind == kEventMouseUp && lastButtonTranslated) {
-                    buttonToSend = Qt::RightButton;
-                    lastButtonTranslated = false;
-                }
-                QMouseEvent qme(etype, plocal, p, buttonToSend, buttons, modifiers);
-                QApplication::sendSpontaneousEvent(widget, &qme);
-                if(!qme.isAccepted() || inNonClientArea)
-                    handled_event = false;
-            }
-
-            if (leaveAfterRelease) {
-                QWidget *enter = QApplication::widgetAt(where.h, where.v);
-                QApplicationPrivate::dispatchEnterLeave(enter, leaveAfterRelease);
-                qt_last_mouse_receiver = enter;
-                leaveAfterRelease = 0;
-            }
-
-            if(ekind == kEventMouseDown &&
-               ((button == Qt::RightButton) ||
-                (button == Qt::LeftButton && (modifiers & Qt::MetaModifier))))
-                qt_event_request_context();
-
-#ifdef DEBUG_MOUSE_MAPS
-            const char *event_desc = edesc;
-            if(etype == QEvent::MouseButtonDblClick)
-                event_desc = "Double Click";
-            else if(etype == QEvent::NonClientAreaMouseButtonPress)
-                event_desc = "NonClientMousePress";
-            else if(etype == QEvent::NonClientAreaMouseButtonRelease)
-                event_desc = "NonClientMouseRelease";
-            else if(etype == QEvent::NonClientAreaMouseMove)
-                event_desc = "NonClientMouseMove";
-            else if(etype == QEvent::NonClientAreaMouseButtonDblClick)
-                event_desc = "NonClientMouseDblClick";
-            qDebug("%d %d (%d %d) - Would send (%s) event to %p %s %s (%d 0x%08x 0x%08x %d)", p.x(), p.y(),
-                   plocal.x(), plocal.y(), event_desc, (QWidget*)widget,
-                   widget ? widget->objectName().toLocal8Bit().constData() : "*Unknown*",
-                   widget ? widget->metaObject()->className() : "*Unknown*",
-                   button, (int)buttons, (int)modifiers, wheel_deltaX);
-#endif
-        } else {
-            handled_event = false;
-        }
-        break;
-    }
-    case kEventClassTextInput:
-    case kEventClassKeyboard: {
-        EventRef key_event = event;
-        if(eclass == kEventClassTextInput) {
-            Q_ASSERT(ekind == kEventTextInputUnicodeForKeyEvent);
-            OSStatus err = GetEventParameter(event, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0,
-                                             sizeof(key_event), 0, &key_event);
-            Q_ASSERT(err == noErr);
-            Q_UNUSED(err);
-        }
-        const UInt32 key_ekind = GetEventKind(key_event);
-        Q_ASSERT(GetEventClass(key_event) == kEventClassKeyboard);
-
-        if(key_ekind == kEventRawKeyDown)
-            qt_keymapper_private()->updateKeyMap(er, key_event, data);
-        if(mac_keyboard_grabber)
-            widget = mac_keyboard_grabber;
-        else if (app->activePopupWidget())
-            widget = (app->activePopupWidget()->focusWidget() ?
-                      app->activePopupWidget()->focusWidget() : app->activePopupWidget());
-        else if(QApplication::focusWidget())
-            widget = QApplication::focusWidget();
-        else
-            widget = app->activeWindow();
-
-        if (widget) {
-            if (widget->macEvent(er, event))
-                return noErr;
-        } else {
-            // Darn, I need to update tho modifier state, even though
-            // Qt itself isn't getting them, otherwise the keyboard state get inconsistent.
-            if (key_ekind == kEventRawKeyModifiersChanged) {
-                UInt32 modifiers = 0;
-                GetEventParameter(key_event, kEventParamKeyModifiers, typeUInt32, 0,
-                                  sizeof(modifiers), 0, &modifiers);
-                extern void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object); // qkeymapper_mac.cpp
-                // Just send it to the qApp for the time being.
-                qt_mac_send_modifiers_changed(modifiers, qApp);
-            }
-            handled_event = false;
-            break;
-        }
-
-        if(app_do_modal && !qt_try_modal(widget, key_event))
-            break;
-        if (eclass == kEventClassTextInput) {
-            handled_event = false;
-        } else {
-            handled_event = qt_keymapper_private()->translateKeyEvent(widget, er, key_event, data,
-                                                                      widget == mac_keyboard_grabber);
-        }
-        break; }
-    case kEventClassWindow: {
-        WindowRef wid = 0;
-        GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
-                          sizeof(WindowRef), 0, &wid);
-        widget = qt_mac_find_window(wid);
-        if (widget && widget->macEvent(er, event))
-            return noErr;
-        if(ekind == kEventWindowActivated) {
-            if(QApplicationPrivate::app_style) {
-                QEvent ev(QEvent::Style);
-                QApplication::sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
-            }
-
-            if(widget && app_do_modal && !qt_try_modal(widget, event))
-                break;
-
-            if(widget && widget->window()->isVisible()) {
-                QWidget *tlw = widget->window();
-               if(tlw->isWindow() && !(tlw->windowType() == Qt::Popup)
-                   && !qt_mac_is_macdrawer(tlw)
-                   && (!tlw->parentWidget() || tlw->isModal()
-                       || !(tlw->windowType() == Qt::Tool))) {
-                    bool just_send_event = false;
-                    {
-                        WindowActivationScope scope;
-                        if(GetWindowActivationScope((WindowRef)wid, &scope) == noErr &&
-                           scope == kWindowActivationScopeIndependent) {
-                            if(GetFrontWindowOfClass(kAllWindowClasses, true) != wid)
-                                just_send_event = true;
-                        }
-                    }
-                    if(just_send_event) {
-                        QEvent e(QEvent::WindowActivate);
-                        QApplication::sendSpontaneousEvent(widget, &e);
-                    } else {
-                        app->setActiveWindow(tlw);
-                    }
-                }
-                QMenuBar::macUpdateMenuBar();
-            }
-        } else if(ekind == kEventWindowDeactivated) {
-            if(widget && QApplicationPrivate::active_window == widget)
-                app->setActiveWindow(0);
-        } else {
-            handled_event = false;
-        }
-        break; }
-    case kEventClassApplication:
-        if(ekind == kEventAppActivated) {
-            if(QApplication::desktopSettingsAware())
-                qt_mac_update_os_settings();
-            if(qt_clipboard) { //manufacture an event so the clipboard can see if it has changed
-                QEvent ev(QEvent::Clipboard);
-                QApplication::sendSpontaneousEvent(qt_clipboard, &ev);
-            }
-            if(app) {
-                QEvent ev(QEvent::ApplicationActivate);
-                QApplication::sendSpontaneousEvent(app, &ev);
-            }
-            if(!app->activeWindow()) {
-                WindowPtr wp = ActiveNonFloatingWindow();
-                if(QWidget *tmp_w = qt_mac_find_window(wp))
-                    app->setActiveWindow(tmp_w);
-            }
-            QMenuBar::macUpdateMenuBar();
-        } else if(ekind == kEventAppDeactivated) {
-            //qt_mac_no_click_through_mode = false;
-            while(app->d_func()->inPopupMode())
-                app->activePopupWidget()->close();
-            if(app) {
-                QEvent ev(QEvent::ApplicationDeactivate);
-                QApplication::sendSpontaneousEvent(app, &ev);
-            }
-            app->setActiveWindow(0);
-        } else if(ekind == kEventAppAvailableWindowBoundsChanged) {
-            QDesktopWidgetImplementation::instance()->onResize();
-        } else {
-            handled_event = false;
-        }
-        break;
-    case kAppearanceEventClass:
-        if(ekind == kAEAppearanceChanged) {
-            if(QApplication::desktopSettingsAware())
-                qt_mac_update_os_settings();
-            if(QApplicationPrivate::app_style) {
-                QEvent ev(QEvent::Style);
-                QApplication::sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
-            }
-        } else {
-            handled_event = false;
-        }
-        break;
-    case kEventClassAppleEvent:
-        if(ekind == kEventAppleEvent) {
-            EventRecord erec;
-            if(!ConvertEventRefToEventRecord(event, &erec))
-                qDebug("Qt: internal: WH0A, unexpected condition reached. %s:%d", __FILE__, __LINE__);
-            else if(AEProcessAppleEvent(&erec) != noErr)
-                handled_event = false;
-        } else {
-            handled_event = false;
-        }
-        break;
-    case kEventClassCommand:
-        if(ekind == kEventCommandProcess) {
-            HICommand cmd;
-            GetEventParameter(event, kEventParamDirectObject, typeHICommand,
-                              0, sizeof(cmd), 0, &cmd);
-            handled_event = false;
-            if(!cmd.menu.menuRef && GetApplicationDockTileMenu()) {
-                EventRef copy = CopyEvent(event);
-                HICommand copy_cmd;
-                GetEventParameter(event, kEventParamDirectObject, typeHICommand,
-                                  0, sizeof(copy_cmd), 0, &copy_cmd);
-                copy_cmd.menu.menuRef = GetApplicationDockTileMenu();
-                SetEventParameter(copy, kEventParamDirectObject, typeHICommand, sizeof(copy_cmd), &copy_cmd);
-                if(SendEventToMenu(copy, copy_cmd.menu.menuRef) == noErr)
-                    handled_event = true;
-            }
-            if(!handled_event) {
-                if(cmd.commandID == kHICommandQuit) {
-                    // Quitting the application is not Qt's responsibility if
-                    // used in a plugin or just embedded into a native application.
-                    // In that case, let the event pass down to the native apps event handler.
-                    if (!QApplication::testAttribute(Qt::AA_MacPluginApplication)) {
-                        handled_event = true;
-                        HiliteMenu(0);
-                        bool handle_quit = true;
-                        if(QApplicationPrivate::modalState()) {
-                            int visible = 0;
-                            const QWidgetList tlws = QApplication::topLevelWidgets();
-                            for(int i = 0; i < tlws.size(); ++i) {
-                                if(tlws.at(i)->isVisible())
-                                    ++visible;
-                            }
-                            handle_quit = (visible <= 1);
-                        }
-                        if(handle_quit) {
-                            QCloseEvent ev;
-                            QApplication::sendSpontaneousEvent(app, &ev);
-                            if(ev.isAccepted())
-                                app->quit();
-                        } else {
-                            QApplication::beep();
-                        }
-                    }
-                } else if(cmd.commandID == kHICommandSelectWindow) {
-                    if((GetCurrentKeyModifiers() & cmdKey))
-                        handled_event = true;
-                } else if(cmd.commandID == kHICommandAbout) {
-                    QMessageBox::aboutQt(0);
-                    HiliteMenu(0);
-                    handled_event = true;
-                }
-            }
-        }
-        break;
-    }
-
-#ifdef DEBUG_EVENTS
-    qDebug("%shandled event %c%c%c%c %d", handled_event ? "(*) " : "",
-           char(eclass >> 24), char((eclass >> 16) & 255), char((eclass >> 8) & 255),
-           char(eclass & 255), (int)ekind);
-#endif
-    if(!handled_event) //let the event go through
-        return eventNotHandledErr;
-    return noErr; //we eat the event
-#else
-    Q_UNUSED(er);
-    Q_UNUSED(event);
-    Q_UNUSED(data);
-    return eventNotHandledErr;
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QApplicationPrivate::qt_initAfterNSAppStarted()
-{
-    setupAppleEvents();
-    qt_mac_update_cursor();
-}
-
-void QApplicationPrivate::setupAppleEvents()
-{
-    // This function is called from the event dispatcher when NSApplication has
-    // finished initialization, which appears to be just after [NSApplication run] has
-    // started to execute. By setting up our apple events handlers this late, we override
-    // the ones set up by NSApplication.
-
-    // If Qt is used as a plugin, we let the 3rd party application handle events
-    // like quit and open file events. Otherwise, if we install our own handlers, we
-    // easily end up breaking functionallity the 3rd party application depend on:
-    if (QApplication::testAttribute(Qt::AA_MacPluginApplication))
-        return;
-
-    QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *newDelegate = [QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate];
-    NSAppleEventManager *eventManager = [NSAppleEventManager sharedAppleEventManager];
-    [eventManager setEventHandler:newDelegate andSelector:@selector(appleEventQuit:withReplyEvent:)
-     forEventClass:kCoreEventClass andEventID:kAEQuitApplication];
-    [eventManager setEventHandler:newDelegate andSelector:@selector(getUrl:withReplyEvent:)
-      forEventClass:kInternetEventClass andEventID:kAEGetURL];
-}
-#endif
-
-// In Carbon this is your one stop for apple events.
-// In Cocoa, it ISN'T. This is the catch-all Apple Event handler that exists
-// for the time between instantiating the NSApplication, but before the
-// NSApplication has installed it's OWN Apple Event handler. When Cocoa has
-// that set up, we remove this.  So, if you are debugging problems, you likely
-// want to check out QCocoaApplicationDelegate instead.
-OSStatus QApplicationPrivate::globalAppleEventProcessor(const AppleEvent *ae, AppleEvent *, long handlerRefcon)
-{
-    QApplication *app = (QApplication *)handlerRefcon;
-    bool handled_event=false;
-    OSType aeID=typeWildCard, aeClass=typeWildCard;
-    AEGetAttributePtr(ae, keyEventClassAttr, typeType, 0, &aeClass, sizeof(aeClass), 0);
-    AEGetAttributePtr(ae, keyEventIDAttr, typeType, 0, &aeID, sizeof(aeID), 0);
-    if(aeClass == kCoreEventClass) {
-        switch(aeID) {
-        case kAEQuitApplication: {
-            extern bool qt_mac_quit_menu_item_enabled; // qmenu_mac.cpp
-            if (qt_mac_quit_menu_item_enabled) {
-                QCloseEvent ev;
-                QApplication::sendSpontaneousEvent(app, &ev);
-                if(ev.isAccepted()) {
-                    handled_event = true;
-                    app->quit();
-                }
-            } else {
-                QApplication::beep();  // Sorry, you can't quit right now.
-            }
-            break; }
-        case kAEOpenDocuments: {
-            AEDescList docs;
-            if(AEGetParamDesc(ae, keyDirectObject, typeAEList, &docs) == noErr) {
-                long cnt = 0;
-                AECountItems(&docs, &cnt);
-                UInt8 *str_buffer = NULL;
-                for(int i = 0; i < cnt; i++) {
-                    FSRef ref;
-                    if(AEGetNthPtr(&docs, i+1, typeFSRef, 0, 0, &ref, sizeof(ref), 0) != noErr)
-                        continue;
-                    if(!str_buffer)
-                        str_buffer = (UInt8 *)malloc(1024);
-                    FSRefMakePath(&ref, str_buffer, 1024);
-                    QFileOpenEvent ev(QString::fromUtf8((const char *)str_buffer));
-                    QApplication::sendSpontaneousEvent(app, &ev);
-                }
-                if(str_buffer)
-                    free(str_buffer);
-            }
-            break; }
-        default:
-            break;
-        }
-    } else if (aeClass == kInternetEventClass) {
-        switch (aeID) {
-        case kAEGetURL: {
-            char urlData[1024];
-            Size actualSize;
-            if (AEGetParamPtr(ae, keyDirectObject, typeChar, 0, urlData,
-                    sizeof(urlData) - 1, &actualSize) == noErr) {
-                urlData[actualSize] = 0;
-                QFileOpenEvent ev(QUrl(QString::fromUtf8(urlData)));
-                QApplication::sendSpontaneousEvent(app, &ev);
-            }
-            break;
-        }
-        default:
-            break;
-        }
-    }
-#ifdef DEBUG_EVENTS
-    qDebug("Qt: internal: %shandled Apple event! %c%c%c%c %c%c%c%c", handled_event ? "(*)" : "",
-           char(aeID >> 24), char((aeID >> 16) & 255), char((aeID >> 8) & 255),char(aeID & 255),
-           char(aeClass >> 24), char((aeClass >> 16) & 255), char((aeClass >> 8) & 255),char(aeClass & 255));
-#else
-    if(!handled_event) //let the event go through
-        return eventNotHandledErr;
-    return noErr; //we eat the event
-#endif
-}
-
-/*!
-    \fn bool QApplication::macEventFilter(EventHandlerCallRef caller, EventRef event)
-
-    \warning This virtual function is only used under Mac OS X, and behaves different
-    depending on if Qt is based on Carbon or Cocoa.
-
-    For the Carbon port, If you create an application that inherits QApplication and reimplement
-    this function, you get direct access to all Carbon Events that Qt registers
-    for from Mac OS X with this function being called with the \a caller and
-    the \a event.
-
-    For the Cocoa port, If you create an application that inherits QApplication and reimplement
-    this function, you get direct access to all Cocoa Events that Qt receives
-    from Mac OS X with this function being called with the \a caller being 0 and
-    the \a event being an NSEvent pointer:
-
-    NSEvent *e = reinterpret_cast<NSEvent *>(event);
-
-    Return true if you want to stop the event from being processed.
-    Return false for normal event dispatching. The default
-    implementation returns false.
-*/
-bool QApplication::macEventFilter(EventHandlerCallRef, EventRef)
-{
-    return false;
-}
-
-/*!
-    \internal
-*/
-void QApplicationPrivate::openPopup(QWidget *popup)
-{
-    if (!QApplicationPrivate::popupWidgets)                        // create list
-        QApplicationPrivate::popupWidgets = new QWidgetList;
-    QApplicationPrivate::popupWidgets->append(popup);                // add to end of list
-
-    // popups are not focus-handled by the window system (the first
-    // popup grabbed the keyboard), so we have to do that manually: A
-    // new popup gets the focus
-    if (popup->focusWidget()) {
-        popup->focusWidget()->setFocus(Qt::PopupFocusReason);
-    } else if (QApplicationPrivate::popupWidgets->count() == 1) { // this was the first popup
-        popup->setFocus(Qt::PopupFocusReason);
-    }
-}
-
-/*!
-    \internal
-*/
-void QApplicationPrivate::closePopup(QWidget *popup)
-{
-    Q_Q(QApplication);
-    if (!QApplicationPrivate::popupWidgets)
-        return;
-
-    QApplicationPrivate::popupWidgets->removeAll(popup);
-    if (popup == qt_button_down)
-        qt_button_down = 0;
-    if (QApplicationPrivate::popupWidgets->isEmpty()) {  // this was the last popup
-        delete QApplicationPrivate::popupWidgets;
-        QApplicationPrivate::popupWidgets = 0;
-
-        // Special case for Tool windows: since they are activated and deactived together
-        // with a normal window they never become the QApplicationPrivate::active_window.
-        QWidget *appFocusWidget = QApplication::focusWidget();
-        if (appFocusWidget && appFocusWidget->window()->windowType() == Qt::Tool) {
-            appFocusWidget->setFocus(Qt::PopupFocusReason);
-        } else if (QApplicationPrivate::active_window) {
-            if (QWidget *fw = QApplicationPrivate::active_window->focusWidget()) {
-                if (fw != QApplication::focusWidget()) {
-                    fw->setFocus(Qt::PopupFocusReason);
-                } else {
-                    QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
-                    q->sendEvent(fw, &e);
-                }
-            }
-        }
-    } else {
-        // popups are not focus-handled by the window system (the
-        // first popup grabbed the keyboard), so we have to do that
-        // manually: A popup was closed, so the previous popup gets
-        // the focus.
-        QWidget* aw = QApplicationPrivate::popupWidgets->last();
-        if (QWidget *fw = aw->focusWidget())
-            fw->setFocus(Qt::PopupFocusReason);
-    }
-}
-
-void QApplication::beep()
-{
-    qt_mac_beep();
-}
-
-void QApplication::alert(QWidget *widget, int duration)
-{
-    if (!QApplicationPrivate::checkInstance("alert"))
-        return;
-
-    QWidgetList windowsToMark;
-    if (!widget)
-        windowsToMark += topLevelWidgets();
-    else
-        windowsToMark.append(widget->window());
-
-    bool needNotification = false;
-    for (int i = 0; i < windowsToMark.size(); ++i) {
-        QWidget *window = windowsToMark.at(i);
-        if (!window->isActiveWindow() && window->isVisible()) {
-            needNotification = true; // yeah, we may set it multiple times, but that's OK.
-            if (duration != 0) {
-               QTimer *timer = new QTimer(qApp);
-               timer->setSingleShot(true);
-               connect(timer, SIGNAL(timeout()), qApp, SLOT(_q_alertTimeOut()));
-               if (QTimer *oldTimer = qApp->d_func()->alertTimerHash.value(widget)) {
-                   qApp->d_func()->alertTimerHash.remove(widget);
-                   delete oldTimer;
-               }
-               qApp->d_func()->alertTimerHash.insert(widget, timer);
-               timer->start(duration);
-            }
-        }
-    }
-    if (needNotification)
-        qt_mac_send_notification();
-}
-
-void QApplicationPrivate::_q_alertTimeOut()
-{
-    if (QTimer *timer = qobject_cast<QTimer *>(q_func()->sender())) {
-        QHash<QWidget *, QTimer *>::iterator it = alertTimerHash.begin();
-        while (it != alertTimerHash.end()) {
-            if (it.value() == timer) {
-                alertTimerHash.erase(it);
-                timer->deleteLater();
-                break;
-            }
-            ++it;
-        }
-        if (alertTimerHash.isEmpty()) {
-            qt_mac_cancel_notification();
-        }
-    }
-}
-
-void  QApplication::setCursorFlashTime(int msecs)
-{
-    QApplicationPrivate::cursor_flash_time = msecs;
-}
-
-int QApplication::cursorFlashTime()
-{
-    return QApplicationPrivate::cursor_flash_time;
-}
-
-void QApplication::setDoubleClickInterval(int ms)
-{
-    qt_mac_dblclick.use_qt_time_limit = true;
-    QApplicationPrivate::mouse_double_click_time = ms;
-}
-
-int QApplication::doubleClickInterval()
-{
-    if (!qt_mac_dblclick.use_qt_time_limit) { //get it from the system
-        QSettings appleSettings(QLatin1String("apple.com"));
-        /* First worked as of 10.3.3 */
-        double dci = appleSettings.value(QLatin1String("com/apple/mouse/doubleClickThreshold"), 0.5).toDouble();
-        return int(dci * 1000);
-    }
-    return QApplicationPrivate::mouse_double_click_time;
-}
-
-void QApplication::setKeyboardInputInterval(int ms)
-{
-    QApplicationPrivate::keyboard_input_time = ms;
-}
-
-int QApplication::keyboardInputInterval()
-{
-    // FIXME: get from the system
-    return QApplicationPrivate::keyboard_input_time;
-}
-
-#ifndef QT_NO_WHEELEVENT
-void QApplication::setWheelScrollLines(int n)
-{
-    QApplicationPrivate::wheel_scroll_lines = n;
-}
-
-int QApplication::wheelScrollLines()
-{
-    return QApplicationPrivate::wheel_scroll_lines;
-}
-#endif
-
-void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
-{
-    switch (effect) {
-    case Qt::UI_FadeMenu:
-        QApplicationPrivate::fade_menu = enable;
-        break;
-    case Qt::UI_AnimateMenu:
-        QApplicationPrivate::animate_menu = enable;
-        break;
-    case Qt::UI_FadeTooltip:
-        QApplicationPrivate::fade_tooltip = enable;
-        break;
-    case Qt::UI_AnimateTooltip:
-        QApplicationPrivate::animate_tooltip = enable;
-        break;
-    case Qt::UI_AnimateCombo:
-        QApplicationPrivate::animate_combo = enable;
-        break;
-    case Qt::UI_AnimateToolBox:
-        QApplicationPrivate::animate_toolbox = enable;
-        break;
-    case Qt::UI_General:
-        QApplicationPrivate::fade_tooltip = true;
-        break;
-    default:
-        QApplicationPrivate::animate_ui = enable;
-        break;
-    }
-
-    if (enable)
-        QApplicationPrivate::animate_ui = true;
-}
-
-bool QApplication::isEffectEnabled(Qt::UIEffect effect)
-{
-    if (QColormap::instance().depth() < 16 || !QApplicationPrivate::animate_ui)
-        return false;
-
-    switch(effect) {
-    case Qt::UI_AnimateMenu:
-        return QApplicationPrivate::animate_menu;
-    case Qt::UI_FadeMenu:
-        return QApplicationPrivate::fade_menu;
-    case Qt::UI_AnimateCombo:
-        return QApplicationPrivate::animate_combo;
-    case Qt::UI_AnimateTooltip:
-        return QApplicationPrivate::animate_tooltip;
-    case Qt::UI_FadeTooltip:
-        return QApplicationPrivate::fade_tooltip;
-    case Qt::UI_AnimateToolBox:
-        return QApplicationPrivate::animate_toolbox;
-    default:
-        break;
-    }
-    return QApplicationPrivate::animate_ui;
-}
-
-/*!
-    \internal
-*/
-bool QApplicationPrivate::qt_mac_apply_settings()
-{
-    QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
-    settings.beginGroup(QLatin1String("Qt"));
-
-    /*
-      Qt settings.  This is how they are written into the datastream.
-      Palette/ *             - QPalette
-      font                   - QFont
-      libraryPath            - QStringList
-      style                  - QString
-      doubleClickInterval    - int
-      cursorFlashTime        - int
-      wheelScrollLines       - int
-      defaultCodec           - QString
-      globalStrut/width      - int
-      globalStrut/height     - int
-      GUIEffects             - QStringList
-      Font Substitutions/ *  - QStringList
-      Font Substitutions/... - QStringList
-    */
-
-    // read library (ie. plugin) path list
-    QString libpathkey =
-        QString::fromLatin1("%1.%2/libraryPath")
-                    .arg(QT_VERSION >> 16)
-                    .arg((QT_VERSION & 0xff00) >> 8);
-    QStringList pathlist = settings.value(libpathkey).toString().split(QLatin1Char(':'));
-    if (!pathlist.isEmpty()) {
-        QStringList::ConstIterator it = pathlist.begin();
-        while(it != pathlist.end())
-            QApplication::addLibraryPath(*it++);
-    }
-
-    QString defaultcodec = settings.value(QLatin1String("defaultCodec"), QVariant(QLatin1String("none"))).toString();
-    if (defaultcodec != QLatin1String("none")) {
-        QTextCodec *codec = QTextCodec::codecForName(defaultcodec.toLatin1().constData());
-        if (codec)
-            QTextCodec::setCodecForTr(codec);
-    }
-
-    if (qt_is_gui_used) {
-        QString str;
-        QStringList strlist;
-        int num;
-
-        // read new palette
-        int i;
-        QPalette pal(QApplication::palette());
-        strlist = settings.value(QLatin1String("Palette/active")).toStringList();
-        if (strlist.count() == QPalette::NColorRoles) {
-            for (i = 0; i < QPalette::NColorRoles; i++)
-                pal.setColor(QPalette::Active, (QPalette::ColorRole) i,
-                            QColor(strlist[i]));
-        }
-        strlist = settings.value(QLatin1String("Palette/inactive")).toStringList();
-        if (strlist.count() == QPalette::NColorRoles) {
-            for (i = 0; i < QPalette::NColorRoles; i++)
-                pal.setColor(QPalette::Inactive, (QPalette::ColorRole) i,
-                            QColor(strlist[i]));
-        }
-        strlist = settings.value(QLatin1String("Palette/disabled")).toStringList();
-        if (strlist.count() == QPalette::NColorRoles) {
-            for (i = 0; i < QPalette::NColorRoles; i++)
-                pal.setColor(QPalette::Disabled, (QPalette::ColorRole) i,
-                            QColor(strlist[i]));
-        }
-
-        if (pal != QApplication::palette())
-            QApplication::setPalette(pal);
-
-        // read new font
-        QFont font(QApplication::font());
-        str = settings.value(QLatin1String("font")).toString();
-        if (!str.isEmpty()) {
-            font.fromString(str);
-            if (font != QApplication::font())
-                QApplication::setFont(font);
-        }
-
-        // read new QStyle
-        QString stylename = settings.value(QLatin1String("style")).toString();
-        if (! stylename.isNull() && ! stylename.isEmpty()) {
-            QStyle *style = QStyleFactory::create(stylename);
-            if (style)
-                QApplication::setStyle(style);
-            else
-                stylename = QLatin1String("default");
-        } else {
-            stylename = QLatin1String("default");
-        }
-
-        num = settings.value(QLatin1String("doubleClickInterval"),
-                            QApplication::doubleClickInterval()).toInt();
-        QApplication::setDoubleClickInterval(num);
-
-        num = settings.value(QLatin1String("cursorFlashTime"),
-                            QApplication::cursorFlashTime()).toInt();
-        QApplication::setCursorFlashTime(num);
-
-#ifndef QT_NO_WHEELEVENT
-        num = settings.value(QLatin1String("wheelScrollLines"),
-                            QApplication::wheelScrollLines()).toInt();
-        QApplication::setWheelScrollLines(num);
-#endif
-
-        int w = settings.value(QLatin1String("globalStrut/width")).toInt();
-        int h = settings.value(QLatin1String("globalStrut/height")).toInt();
-        QSize strut(w, h);
-        if (strut.isValid())
-            QApplication::setGlobalStrut(strut);
-
-        QStringList effects = settings.value(QLatin1String("GUIEffects")).toStringList();
-        if (!effects.isEmpty()) {
-            if (effects.contains(QLatin1String("none")))
-                QApplication::setEffectEnabled(Qt::UI_General, false);
-            if (effects.contains(QLatin1String("general")))
-                QApplication::setEffectEnabled(Qt::UI_General, true);
-            if (effects.contains(QLatin1String("animatemenu")))
-                QApplication::setEffectEnabled(Qt::UI_AnimateMenu, true);
-            if (effects.contains(QLatin1String("fademenu")))
-                QApplication::setEffectEnabled(Qt::UI_FadeMenu, true);
-            if (effects.contains(QLatin1String("animatecombo")))
-                QApplication::setEffectEnabled(Qt::UI_AnimateCombo, true);
-            if (effects.contains(QLatin1String("animatetooltip")))
-                QApplication::setEffectEnabled(Qt::UI_AnimateTooltip, true);
-            if (effects.contains(QLatin1String("fadetooltip")))
-                QApplication::setEffectEnabled(Qt::UI_FadeTooltip, true);
-            if (effects.contains(QLatin1String("animatetoolbox")))
-                QApplication::setEffectEnabled(Qt::UI_AnimateToolBox, true);
-        } else {
-            QApplication::setEffectEnabled(Qt::UI_General, true);
-        }
-
-        settings.beginGroup(QLatin1String("Font Substitutions"));
-        QStringList fontsubs = settings.childKeys();
-        if (!fontsubs.isEmpty()) {
-            QStringList::Iterator it = fontsubs.begin();
-            for (; it != fontsubs.end(); ++it) {
-                QString fam = QString::fromLatin1((*it).toLatin1().constData());
-                QStringList subs = settings.value(fam).toStringList();
-                QFont::insertSubstitutions(fam, subs);
-            }
-        }
-        settings.endGroup();
-    }
-
-    settings.endGroup();
-    return true;
-}
-
-// DRSWAT
-
-bool QApplicationPrivate::canQuit()
-{
-#ifndef QT_MAC_USE_COCOA
-    return true;
-#else
-    Q_Q(QApplication);
-#ifdef QT_MAC_USE_COCOA
-    [[[NSApplication sharedApplication] mainMenu] cancelTracking];
-#else
-    HiliteMenu(0);
-#endif
-
-    bool handle_quit = true;
-    if (QApplicationPrivate::modalState() && [[[[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate]
-                                                   menuLoader] quitMenuItem] isEnabled]) {
-        int visible = 0;
-        const QWidgetList tlws = QApplication::topLevelWidgets();
-        for(int i = 0; i < tlws.size(); ++i) {
-            if (tlws.at(i)->isVisible())
-                ++visible;
-        }
-        handle_quit = (visible <= 1);
-    }
-    if (handle_quit) {
-        QCloseEvent ev;
-        QApplication::sendSpontaneousEvent(q, &ev);
-        if (ev.isAccepted()) {
-            return true;
-        }
-    }
-    return false;
-#endif
-}
-
-void onApplicationWindowChangedActivation(QWidget *widget, bool activated)
-{
-#ifdef QT_MAC_USE_COCOA
-    if (!widget)
-        return;
-
-    if (activated) {
-        if (QApplicationPrivate::app_style) {
-            QEvent ev(QEvent::Style);
-            qt_sendSpontaneousEvent(QApplicationPrivate::app_style, &ev);
-        }
-        qApp->setActiveWindow(widget);
-    } else { // deactivated
-        if (QApplicationPrivate::active_window == widget)
-            qApp->setActiveWindow(0);
-    }
-
-    QMenuBar::macUpdateMenuBar();
-    qt_mac_update_cursor();
-#else
-    Q_UNUSED(widget);
-    Q_UNUSED(activated);
-#endif
-}
-
-
-void onApplicationChangedActivation( bool activated )
-{
-#ifdef QT_MAC_USE_COCOA
-    QApplication    *app    = qApp;
-
-//NSLog(@"App Changed Activation\n");
-
-    if ( activated ) {
-        if (QApplication::desktopSettingsAware())
-            qt_mac_update_os_settings();
-
-        if (qt_clipboard) { //manufacture an event so the clipboard can see if it has changed
-            QEvent ev(QEvent::Clipboard);
-            qt_sendSpontaneousEvent(qt_clipboard, &ev);
-        }
-
-        if (app) {
-            QEvent ev(QEvent::ApplicationActivate);
-            qt_sendSpontaneousEvent(app, &ev);
-        }
-
-        if (!app->activeWindow()) {
-            OSWindowRef wp = [[NSApplication sharedApplication] keyWindow];
-            if (QWidget *tmp_w = qt_mac_find_window(wp))
-                app->setActiveWindow(tmp_w);
-        }
-        QMenuBar::macUpdateMenuBar();
-        qt_mac_update_cursor();
-    } else { // de-activated
-        QApplicationPrivate *priv = [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] qAppPrivate];
-        if (priv->inPopupMode())
-            app->activePopupWidget()->close();
-        if (app) {
-            QEvent ev(QEvent::ApplicationDeactivate);
-            qt_sendSpontaneousEvent(app, &ev);
-        }
-        app->setActiveWindow(0);
-    }
-#else
-    Q_UNUSED(activated);
-#endif
-}
-
-void QApplicationPrivate::initializeMultitouch_sys()
-{ }
-void QApplicationPrivate::cleanupMultitouch_sys()
-{ }
-
-#include "moc_qsessionmanager.h"
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp
deleted file mode 100644 (file)
index 2aa05a0..0000000
+++ /dev/null
@@ -1,4284 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifdef Q_WS_WINCE
-#include "qguifunctions_wince.h"
-#include "qmenubar.h"
-extern bool qt_wince_is_mobile();             //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_high_dpi();           //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_smartphone();         //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_pocket_pc();          //defined in qguifunctions_wince.cpp
-extern void qt_wince_hide_taskbar(HWND hwnd); //defined in qguifunctions_wince.cpp
-#endif
-#ifdef Q_WS_WINCE_WM
-#include <windowsm.h>
-#include <tpcshell.h>
-#ifdef QT_WINCE_GESTURES
-#ifndef QT_NO_GESTURES
-#include <gesture.h>
-#endif
-#endif
-#endif
-
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qeventdispatcher_win_p.h"
-#include "qeventloop.h"
-#include "qclipboard.h"
-#include "qcursor.h"
-#include "qdatetime.h"
-#include "qpointer.h"
-#include "qhash.h"
-#include "qmetaobject.h"
-#include "qmime.h"
-#include "qpainter.h"
-#include "qpixmapcache.h"
-#include "qsessionmanager.h"
-#include "qstyle.h"
-#include "qwhatsthis.h" // ######## dependency
-#include "qwidget.h"
-#include "qcolormap.h"
-#include "qlayout.h"
-#include "qtooltip.h"
-#include "qt_windows.h"
-#include "qscrollbar.h"
-#if defined(QT_NON_COMMERCIAL)
-#include "qnc_win.h"
-#endif
-#include "qwininputcontext_p.h"
-#include "qcursor_p.h"
-#include "qmath_p.h"
-#include "qapplication_p.h"
-#include "qbackingstore_p.h"
-#include "qwindowsurface_raster_p.h"
-#include "qdebug.h"
-#include <qkeymapper_p.h>
-#include <qlocale_p.h>
-#include <qsystemlibrary_p.h>
-#include "qevent_p.h"
-#include "qthread_p.h"
-
-//#define ALIEN_DEBUG
-
-#ifndef QT_NO_THREAD
-#include "qmutex.h"
-#endif
-
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-
-#include <oleacc.h>
-#ifndef WM_GETOBJECT
-#define WM_GETOBJECT                    0x003D
-#endif
-#endif // QT_NO_ACCESSIBILITY
-
-#if !defined(WINABLEAPI)
-#  if defined(Q_WS_WINCE)
-#    include <bldver.h>
-#  endif
-#  if !defined(Q_WS_WINCE)
-#    include <winable.h>
-#  endif
-#endif
-
-#ifndef QT_NO_GESTURES
-#  ifndef GID_ZOOM
-#    define GID_ZOOM              3
-#    define GID_TWOFINGERTAP      6
-#    define GID_PRESSANDTAP       7
-#    define GID_ROLLOVER          GID_PRESSANDTAP
-#  endif
-#endif
-
-#ifndef WM_TOUCH
-#  define WM_TOUCH 0x0240
-#endif
-
-#ifndef TOUCHEVENTF_MOVE
-#  define TOUCHEVENTF_MOVE       0x0001
-#  define TOUCHEVENTF_DOWN       0x0002
-#  define TOUCHEVENTF_UP         0x0004
-#  define TOUCHEVENTF_INRANGE    0x0008
-#  define TOUCHEVENTF_PRIMARY    0x0010
-#  define TOUCHEVENTF_NOCOALESCE 0x0020
-#  define TOUCHEVENTF_PEN        0x0040
-#  define TOUCHEVENTF_PALM       0x0080
-
-#  define TOUCHINPUTMASKF_TIMEFROMSYSTEM 0x0001
-#  define TOUCHINPUTMASKF_EXTRAINFO      0x0002
-#  define TOUCHINPUTMASKF_CONTACTAREA    0x0004
-
-typedef struct tagTOUCHINPUT
-{
-    LONG x;
-    LONG y;
-    HANDLE hSource;
-    DWORD dwID;
-    DWORD dwFlags;
-    DWORD dwMask;
-    DWORD dwTime;
-    ULONG_PTR dwExtraInfo;
-    DWORD cxContact;
-    DWORD cyContact;
-} TOUCHINPUT, *PTOUCHINPUT;
-
-#endif
-
-#include <windowsx.h>
-#include <limits.h>
-#include <string.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <math.h>
-
-#define PACKETDATA  (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE \
-                     | PK_ORIENTATION | PK_CURSOR | PK_Z)
-#define PACKETMODE  0
-
-#include <wintab.h>
-#ifndef CSR_TYPE
-#define CSR_TYPE 20 // Some old Wacom wintab.h may not provide this constant.
-#endif
-#include <pktdef.h>
-
-#if defined(__CYGWIN32__)
-#define __INSIDE_CYGWIN32__
-#include <mywinsock.h>
-#endif
-
-#ifndef IMR_RECONVERTSTRING
-#define IMR_RECONVERTSTRING 4
-#endif
-
-#ifndef IMR_CONFIRMRECONVERTSTRING
-#define IMR_CONFIRMRECONVERTSTRING 0x0005
-#endif
-QT_BEGIN_NAMESPACE
-
-#ifdef Q_WS_WINCE
-#ifndef SHRG_RETURNCMD
-struct SHRGINFO {
-    DWORD cbSize;
-    HWND hwndClient;
-    POINT ptDown;
-    DWORD dwFlags;
-};
-#define  GN_CONTEXTMENU       1000
-#define  SHRG_RETURNCMD       0x00000001
-#define  SHRG_NOANIMATION     0x00000010
-#endif
-
-#ifndef SPI_SETSIPINFO
-#define SPI_SETSIPINFO        224
-#endif
-
-#ifndef QT_NO_GESTURES
-typedef DWORD (API *AygRecognizeGesture)(SHRGINFO*);
-static AygRecognizeGesture ptrRecognizeGesture = 0;
-static bool aygResolved = false;
-static void resolveAygLibs()
-{
-    if (!aygResolved) {
-        QSystemLibrary ayglib(QLatin1String("aygshell"));
-        ptrRecognizeGesture = (AygRecognizeGesture) ayglib.resolve("SHRecognizeGesture");
-        aygResolved = true;
-    }
-}
-#endif // QT_NO_GESTURES
-
-#endif
-
-#ifndef SPI_SETFONTSMOOTHINGTYPE
-#  define SPI_SETFONTSMOOTHINGTYPE 0x200B
-#endif
-#ifndef SPI_GETFONTSMOOTHINGTYPE
-#  define SPI_GETFONTSMOOTHINGTYPE 0x200A
-#endif
-#ifndef FE_FONTSMOOTHINGCLEARTYPE
-#  define FE_FONTSMOOTHINGCLEARTYPE 0x0002
-#endif
-
-Q_GUI_EXPORT qreal qt_fontsmoothing_gamma;
-Q_GUI_EXPORT bool qt_cleartype_enabled;
-Q_GUI_EXPORT bool qt_win_owndc_required; // CS_OWNDC is required if we use the GL graphicssystem as default
-
-typedef HCTX (API *PtrWTOpen)(HWND, LPLOGCONTEXT, BOOL);
-typedef BOOL (API *PtrWTClose)(HCTX);
-typedef UINT (API *PtrWTInfo)(UINT, UINT, LPVOID);
-typedef BOOL (API *PtrWTEnable)(HCTX, BOOL);
-typedef BOOL (API *PtrWTOverlap)(HCTX, BOOL);
-typedef int  (API *PtrWTPacketsGet)(HCTX, int, LPVOID);
-typedef BOOL (API *PtrWTGet)(HCTX, LPLOGCONTEXT);
-typedef int  (API *PtrWTQueueSizeGet)(HCTX);
-typedef BOOL (API *PtrWTQueueSizeSet)(HCTX, int);
-
-static PtrWTInfo ptrWTInfo = 0;
-static PtrWTEnable ptrWTEnable = 0;
-static PtrWTOverlap ptrWTOverlap = 0;
-static PtrWTPacketsGet ptrWTPacketsGet = 0;
-static PtrWTGet ptrWTGet = 0;
-
-static PACKET localPacketBuf[QT_TABLET_NPACKETQSIZE];  // our own tablet packet queue.
-HCTX qt_tablet_context;  // the hardware context for the tablet (like a window handle)
-bool qt_tablet_tilt_support;
-QPointF oldHiResTabletGlobalPosF;
-
-// flags for extensions for special Languages, currently only for RTL languages
-bool qt_use_rtl_extensions = false;
-
-#ifndef QT_NO_TABLETEVENT
-static void tabletInit(const quint64 uniqueId, const UINT csr_type, HCTX hTab);
-static void tabletUpdateCursor(QTabletDeviceData &tdd, const UINT currentCursor);
-static void initWinTabFunctions();        // resolve the WINTAB api functions
-#endif // QT_NO_TABLETEVENT
-
-
-#ifndef QT_NO_ACCESSIBILITY
-extern IAccessible *qt_createWindowsAccessible(QAccessibleInterface *object);
-#endif // QT_NO_ACCESSIBILITY
-
-extern bool qt_tabletChokeMouse;
-extern QWidget* qt_get_tablet_widget();
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*);
-extern QRegion qt_dirtyRegion(QWidget *);
-
-typedef QHash<quint64, QTabletDeviceData> QTabletCursorInfo;
-Q_GLOBAL_STATIC(QTabletCursorInfo, tCursorInfo)
-QTabletDeviceData currentTabletPointer;
-
-// from qregion_win.cpp
-extern HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom);
-
-// support for on-the-fly changes of the XP theme engine
-#ifndef WM_THEMECHANGED
-#define WM_THEMECHANGED                 0x031A
-#endif
-#ifndef COLOR_MENUHILIGHT
-#define COLOR_MENUHILIGHT                29
-#define COLOR_MENUBAR                        30
-#endif
-
-// support for xbuttons
-#ifndef WM_XBUTTONDOWN
-#define WM_XBUTTONDOWN                  0x020B
-#define WM_XBUTTONUP                    0x020C
-#define WM_XBUTTONDBLCLK                0x020D
-#endif
-#ifndef GET_KEYSTATE_WPARAM
-#define GET_KEYSTATE_WPARAM(wParam)     (LOWORD(wParam))
-#define GET_XBUTTON_WPARAM(wParam)      (HIWORD(wParam))
-#define XBUTTON1      0x0001
-#define XBUTTON2      0x0002
-#endif
-#ifndef MK_XBUTTON1
-#define MK_XBUTTON1         0x0020
-#define MK_XBUTTON2         0x0040
-#endif
-
-// support for multi-media-keys
-#ifndef WM_APPCOMMAND
-#define WM_APPCOMMAND                   0x0319
-#endif
-
-#ifndef FAPPCOMMAND_MOUSE
-#define FAPPCOMMAND_MOUSE 0x8000
-#define FAPPCOMMAND_KEY   0
-#define FAPPCOMMAND_OEM   0x1000
-#define FAPPCOMMAND_MASK  0xF000
-#define GET_APPCOMMAND_LPARAM(lParam) ((short)(HIWORD(lParam) & ~FAPPCOMMAND_MASK))
-#define GET_DEVICE_LPARAM(lParam)     ((WORD)(HIWORD(lParam) & FAPPCOMMAND_MASK))
-#define GET_MOUSEORKEY_LPARAM         GET_DEVICE_LPARAM
-#define GET_FLAGS_LPARAM(lParam)      (LOWORD(lParam))
-#define GET_KEYSTATE_LPARAM(lParam)   GET_FLAGS_LPARAM(lParam)
-
-#define APPCOMMAND_BROWSER_BACKWARD       1
-#define APPCOMMAND_BROWSER_FORWARD        2
-#define APPCOMMAND_BROWSER_REFRESH        3
-#define APPCOMMAND_BROWSER_STOP           4
-#define APPCOMMAND_BROWSER_SEARCH         5
-#define APPCOMMAND_BROWSER_FAVORITES      6
-#define APPCOMMAND_BROWSER_HOME           7
-#define APPCOMMAND_VOLUME_MUTE            8
-#define APPCOMMAND_VOLUME_DOWN            9
-#define APPCOMMAND_VOLUME_UP              10
-#define APPCOMMAND_MEDIA_NEXTTRACK        11
-#define APPCOMMAND_MEDIA_PREVIOUSTRACK    12
-#define APPCOMMAND_MEDIA_STOP             13
-#define APPCOMMAND_MEDIA_PLAY_PAUSE       14
-#define APPCOMMAND_LAUNCH_MAIL            15
-#define APPCOMMAND_LAUNCH_MEDIA_SELECT    16
-#define APPCOMMAND_LAUNCH_APP1            17
-#define APPCOMMAND_LAUNCH_APP2            18
-#define APPCOMMAND_BASS_DOWN              19
-#define APPCOMMAND_BASS_BOOST             20
-#define APPCOMMAND_BASS_UP                21
-#define APPCOMMAND_TREBLE_DOWN            22
-#define APPCOMMAND_TREBLE_UP              23
-#endif // FAPPCOMMAND_MOUSE
-
-// New commands from Windows XP (some even Sp1)
-#ifndef APPCOMMAND_MICROPHONE_VOLUME_MUTE
-#define APPCOMMAND_MICROPHONE_VOLUME_MUTE 24
-#define APPCOMMAND_MICROPHONE_VOLUME_DOWN 25
-#define APPCOMMAND_MICROPHONE_VOLUME_UP   26
-#define APPCOMMAND_HELP                   27
-#define APPCOMMAND_FIND                   28
-#define APPCOMMAND_NEW                    29
-#define APPCOMMAND_OPEN                   30
-#define APPCOMMAND_CLOSE                  31
-#define APPCOMMAND_SAVE                   32
-#define APPCOMMAND_PRINT                  33
-#define APPCOMMAND_UNDO                   34
-#define APPCOMMAND_REDO                   35
-#define APPCOMMAND_COPY                   36
-#define APPCOMMAND_CUT                    37
-#define APPCOMMAND_PASTE                  38
-#define APPCOMMAND_REPLY_TO_MAIL          39
-#define APPCOMMAND_FORWARD_MAIL           40
-#define APPCOMMAND_SEND_MAIL              41
-#define APPCOMMAND_SPELL_CHECK            42
-#define APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE    43
-#define APPCOMMAND_MIC_ON_OFF_TOGGLE      44
-#define APPCOMMAND_CORRECTION_LIST        45
-#define APPCOMMAND_MEDIA_PLAY             46
-#define APPCOMMAND_MEDIA_PAUSE            47
-#define APPCOMMAND_MEDIA_RECORD           48
-#define APPCOMMAND_MEDIA_FAST_FORWARD     49
-#define APPCOMMAND_MEDIA_REWIND           50
-#define APPCOMMAND_MEDIA_CHANNEL_UP       51
-#define APPCOMMAND_MEDIA_CHANNEL_DOWN     52
-#endif // APPCOMMAND_MICROPHONE_VOLUME_MUTE
-
-#if (_WIN32_WINNT < 0x0400)
-// This struct is defined in winuser.h if the _WIN32_WINNT >= 0x0400 -- in the
-// other cases we have to define it on our own.
-typedef struct tagTRACKMOUSEEVENT {
-    DWORD cbSize;
-    DWORD dwFlags;
-    HWND  hwndTrack;
-    DWORD dwHoverTime;
-} TRACKMOUSEEVENT, *LPTRACKMOUSEEVENT;
-#endif
-#ifndef WM_MOUSELEAVE
-#define WM_MOUSELEAVE                   0x02A3
-#endif
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qwidget_p.h"
-QT_END_INCLUDE_NAMESPACE
-
-static int translateButtonState(int s, int type, int button);
-
-// ##### get rid of this!
-QRgb qt_colorref2qrgb(COLORREF col)
-{
-    return qRgb(GetRValue(col),GetGValue(col),GetBValue(col));
-}
-
-
-/*****************************************************************************
-  Internal variables and functions
- *****************************************************************************/
-
-static HWND         curWin                = 0;                // current window
-static HDC         displayDC        = 0;                // display device context
-
-// Session management
-static bool        sm_blockUserInput    = false;
-static bool        sm_smActive             = false;
-extern QSessionManager* qt_session_manager_self;
-static bool        sm_cancel;
-
-static bool replayPopupMouseEvent = false; // replay handling when popups close
-
-// ignore the next release event if return from a modal widget
-Q_GUI_EXPORT bool qt_win_ignoreNextMouseReleaseEvent = false;
-
-
-#if defined(QT_DEBUG)
-static bool        appNoGrab        = false;        // mouse/keyboard grabbing
-#endif
-
-static bool        app_do_modal           = false;        // modal mode
-extern QWidgetList *qt_modal_stack;
-extern QDesktopWidget *qt_desktopWidget;
-static QPointer<QWidget> popupButtonFocus;
-static bool        qt_try_modal(QWidget *, MSG *, int& ret);
-
-QWidget               *qt_button_down = 0;                // widget got last button-down
-QPointer<QWidget> qt_last_mouse_receiver = 0;
-
-static HWND        autoCaptureWnd = 0;
-static HWND        imeParentWnd = 0;
-static void        setAutoCapture(HWND);                // automatic capture
-static void        releaseAutoCapture();
-
-static void     unregWinClasses();
-
-extern QCursor *qt_grab_cursor();
-
-#if defined(Q_WS_WIN)
-#define __export
-#endif
-
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
-
-class QETWidget : public QWidget                // event translator widget
-{
-public:
-    QWExtra    *xtra() { return d_func()->extraData(); }
-    QTLWExtra  *topData() { return d_func()->topData(); }
-    QTLWExtra  *maybeTopData() { return d_func()->maybeTopData(); }
-    void syncBackingStore(const QRegion &rgn) { d_func()->syncBackingStore(rgn); }
-    void syncBackingStore() { d_func()->syncBackingStore(); }
-    QWidgetData *dataPtr() { return data; }
-    QWidgetPrivate *dptr() { return d_func(); }
-    QRect frameStrut() const { return d_func()->frameStrut(); }
-    bool        winEvent(MSG *m, long *r)        { return QWidget::winEvent(m, r); }
-    void        markFrameStrutDirty()        { data->fstrut_dirty = 1; }
-    bool        translateMouseEvent(const MSG &msg);
-    bool        translateWheelEvent(const MSG &msg);
-    bool        translatePaintEvent(const MSG &msg);
-    bool        translateConfigEvent(const MSG &msg);
-    bool        translateCloseEvent(const MSG &msg);
-    bool        translateTabletEvent(const MSG &msg, PACKET *localPacketBuf, int numPackets);
-#ifndef QT_NO_GESTURES
-    bool        translateGestureEvent(const MSG &msg, const GESTUREINFO &gi);
-#endif
-    void        repolishStyle(QStyle &style);
-    inline void showChildren(bool spontaneous) { d_func()->showChildren(spontaneous); }
-    inline void hideChildren(bool spontaneous) { d_func()->hideChildren(spontaneous); }
-    inline Qt::WindowStates testWindowState(Qt::WindowStates teststate){ return dataPtr()->window_state & teststate; }
-    inline void setWindowTitle_helper(const QString &title) { d_func()->setWindowTitle_helper(title); }
-    inline void forceUpdate() {
-        QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
-        if (tlwExtra && tlwExtra->backingStore)
-            tlwExtra->backingStore->markDirty(rect(), this, true, true);
-    }
-};
-
-// need to get default font?
-extern bool qt_app_has_font;
-
-extern QFont qt_LOGFONTtoQFont(LOGFONT& lf,bool scale);
-
-static void qt_set_windows_color_resources()
-{
-    // Do the color settings
-    QPalette pal;
-    pal.setColor(QPalette::WindowText,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOWTEXT))));
-    pal.setColor(QPalette::Button,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNFACE))));
-    pal.setColor(QPalette::Light,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNHIGHLIGHT))));
-    pal.setColor(QPalette::Dark,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNSHADOW))));
-    pal.setColor(QPalette::Mid, pal.button().color().darker(150));
-    pal.setColor(QPalette::Text,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOWTEXT))));
-    pal.setColor(QPalette::BrightText,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNHIGHLIGHT))));
-    pal.setColor(QPalette::Base,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_WINDOW))));
-    pal.setColor(QPalette::Window,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNFACE))));
-    pal.setColor(QPalette::ButtonText,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_BTNTEXT))));
-    pal.setColor(QPalette::Midlight,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_3DLIGHT))));
-    pal.setColor(QPalette::Shadow,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_3DDKSHADOW))));
-    pal.setColor(QPalette::Highlight,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHT))));
-    pal.setColor(QPalette::HighlightedText,
-                 QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHTTEXT))));
-
-#if defined(Q_WS_WINCE)
-    // ### hardcoded until I find out how to get it from the system settings.
-    pal.setColor(QPalette::LinkVisited, pal.highlight().color().dark(150));
-    pal.setColor(QPalette::Link, pal.highlight().color().light(130));
-    // Background == Base on Windows CE
-    if (qt_wince_is_smartphone() || qt_wince_is_pocket_pc())
-      pal.setColor(QPalette::Background, pal.base().color());
-#else
-    pal.setColor(QPalette::Link, Qt::blue);
-    pal.setColor(QPalette::LinkVisited, Qt::magenta);
-#endif
-
-
-
-    pal.setColor(QPalette::Inactive, QPalette::Button, pal.button().color());
-    pal.setColor(QPalette::Inactive, QPalette::Window, pal.background().color());
-    pal.setColor(QPalette::Inactive, QPalette::Light, pal.light().color());
-    pal.setColor(QPalette::Inactive, QPalette::Dark, pal.dark().color());
-
-    if (pal.midlight() == pal.button())
-        pal.setColor(QPalette::Midlight, pal.button().color().lighter(110));
-    if (pal.background() != pal.base()) {
-        pal.setColor(QPalette::Inactive, QPalette::Highlight, pal.color(QPalette::Inactive, QPalette::Window));
-        pal.setColor(QPalette::Inactive, QPalette::HighlightedText, pal.color(QPalette::Inactive, QPalette::Text));
-    }
-
-    const QColor bg = pal.background().color();
-    const QColor fg = pal.foreground().color(), btn = pal.button().color();
-    QColor disabled((fg.red()+btn.red())/2,(fg.green()+btn.green())/2,
-                     (fg.blue()+btn.blue())/2);
-    pal.setColorGroup(QPalette::Disabled, pal.foreground(), pal.button(), pal.light(),
-        pal.dark(), pal.mid(), pal.text(), pal.brightText(), pal.base(), pal.background() );
-    pal.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
-    pal.setColor(QPalette::Disabled, QPalette::Text, disabled);
-    pal.setColor(QPalette::Disabled, QPalette::ButtonText, disabled);
-    pal.setColor(QPalette::Disabled, QPalette::Highlight,
-                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHT))));
-    pal.setColor(QPalette::Disabled, QPalette::HighlightedText,
-                  QColor(qt_colorref2qrgb(GetSysColor(COLOR_HIGHLIGHTTEXT))));
-    pal.setColor(QPalette::Disabled, QPalette::Base, bg);
-
-    QApplicationPrivate::setSystemPalette(pal);
-
-    QApplicationPrivate::initializeWidgetPaletteHash();
-
-    QColor ttip(qt_colorref2qrgb(GetSysColor(COLOR_INFOBK)));
-
-    QColor ttipText(qt_colorref2qrgb(GetSysColor(COLOR_INFOTEXT)));
-    {
-#ifndef QT_NO_TOOLTIP
-        QPalette tiplabel(pal);
-        tiplabel.setColor(QPalette::All, QPalette::Button, ttip);
-        tiplabel.setColor(QPalette::All, QPalette::Window, ttip);
-        tiplabel.setColor(QPalette::All, QPalette::ToolTipBase, ttip);
-        tiplabel.setColor(QPalette::All, QPalette::Text, ttipText);
-        tiplabel.setColor(QPalette::All, QPalette::WindowText, ttipText);
-        tiplabel.setColor(QPalette::All, QPalette::ButtonText, ttipText);
-        tiplabel.setColor(QPalette::All, QPalette::Button, ttip);
-        tiplabel.setColor(QPalette::All, QPalette::Window, ttip);
-        tiplabel.setColor(QPalette::All, QPalette::Text, ttipText);
-        tiplabel.setColor(QPalette::All, QPalette::WindowText, ttipText);
-        tiplabel.setColor(QPalette::All, QPalette::ButtonText, ttipText);
-        tiplabel.setColor(QPalette::All, QPalette::ToolTipText, ttipText);
-        const QColor fg = tiplabel.foreground().color(), btn = tiplabel.button().color();
-        QColor disabled((fg.red()+btn.red())/2,(fg.green()+btn.green())/2,
-                         (fg.blue()+btn.blue())/2);
-        tiplabel.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
-        tiplabel.setColor(QPalette::Disabled, QPalette::ToolTipText, disabled);
-        tiplabel.setColor(QPalette::Disabled, QPalette::Text, disabled);
-        tiplabel.setColor(QPalette::Disabled, QPalette::Base, Qt::white);
-        tiplabel.setColor(QPalette::Disabled, QPalette::ToolTipBase, Qt::white);
-        tiplabel.setColor(QPalette::Disabled, QPalette::BrightText, Qt::white);
-        QToolTip::setPalette(tiplabel);
-#endif //QT_NO_TOOLTIP
-    }
-}
-
-static void qt_set_windows_font_resources()
-{
-#ifndef Q_WS_WINCE
-    NONCLIENTMETRICS ncm;
-    ncm.cbSize = FIELD_OFFSET(NONCLIENTMETRICS, lfMessageFont) + sizeof(LOGFONT);
-    SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize , &ncm, 0);
-
-    QFont menuFont = qt_LOGFONTtoQFont(ncm.lfMenuFont, true);
-    QFont messageFont = qt_LOGFONTtoQFont(ncm.lfMessageFont, true);
-    QFont statusFont = qt_LOGFONTtoQFont(ncm.lfStatusFont, true);
-    QFont titleFont = qt_LOGFONTtoQFont(ncm.lfCaptionFont, true);
-
-    LOGFONT lfIconTitleFont;
-    SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(lfIconTitleFont), &lfIconTitleFont, 0);
-    QFont iconTitleFont = qt_LOGFONTtoQFont(lfIconTitleFont, true);
-
-    QApplication::setFont(menuFont, "QMenu");
-    QApplication::setFont(menuFont, "QMenuBar");
-    QApplication::setFont(messageFont, "QMessageBox");
-    QApplication::setFont(statusFont, "QTipLabel");
-    QApplication::setFont(statusFont, "QStatusBar");
-    QApplication::setFont(titleFont, "QWorkspaceTitleBar");
-    QApplication::setFont(iconTitleFont, "QAbstractItemView");
-    QApplication::setFont(iconTitleFont, "QDockWidgetTitle");
-
-#else
-    LOGFONT lf;
-    HGDIOBJ stockFont = GetStockObject(SYSTEM_FONT);
-    GetObject(stockFont, sizeof(lf), &lf);
-    QFont systemFont = qt_LOGFONTtoQFont(lf, true);
-    QApplicationPrivate::setSystemFont(systemFont);
-    QFont smallerFont = systemFont;
-    if (qt_wince_is_mobile()) {
-        smallerFont.setPointSize(systemFont.pointSize()-1);
-        QApplication::setFont(smallerFont, "QTabBar");
-        smallerFont.setBold(true);
-        QApplication::setFont(smallerFont, "QAbstractButton");
-    }
-#endif// Q_WS_WINCE
-}
-
-static void qt_win_read_cleartype_settings()
-{
-    UINT result = 0;
-#ifdef Q_OS_WINCE
-    if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &result, 0))
-        qt_cleartype_enabled = result;
-#else
-    if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &result, 0))
-        qt_cleartype_enabled = (result == FE_FONTSMOOTHINGCLEARTYPE);
-#endif
-
-    int winSmooth;
-    if (SystemParametersInfo(0x200C /* SPI_GETFONTSMOOTHINGCONTRAST */, 0, &winSmooth, 0)) {
-        qt_fontsmoothing_gamma = winSmooth / qreal(1000.0);
-    } else {
-        qt_fontsmoothing_gamma = 1.0;
-    }
-
-    // Safeguard ourselves against corrupt registry values...
-    if (qt_fontsmoothing_gamma > 5 || qt_fontsmoothing_gamma < 1)
-        qt_fontsmoothing_gamma = qreal(1.4);
-}
-
-static void qt_set_windows_resources()
-{
-    if (QApplication::type() != QApplication::Tty)
-        (void) QApplication::style(); // trigger creation of application style
-    qt_set_windows_font_resources();
-    qt_set_windows_color_resources();
-}
-
-void QApplicationPrivate::initializeWidgetPaletteHash()
-{
-    QPalette pal = *QApplicationPrivate::sys_pal;
-    QColor menuCol(qt_colorref2qrgb(GetSysColor(COLOR_MENU)));
-    QColor menuText(qt_colorref2qrgb(GetSysColor(COLOR_MENUTEXT)));
-    BOOL isFlat = false;
-    if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
-        && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)))
-        SystemParametersInfo(SPI_GETFLATMENU, 0, &isFlat, 0);
-    QPalette menu(pal);
-    // we might need a special color group for the menu.
-    menu.setColor(QPalette::Active, QPalette::Button, menuCol);
-    menu.setColor(QPalette::Active, QPalette::Text, menuText);
-    menu.setColor(QPalette::Active, QPalette::WindowText, menuText);
-    menu.setColor(QPalette::Active, QPalette::ButtonText, menuText);
-    QColor disabled(qt_colorref2qrgb(GetSysColor(COLOR_GRAYTEXT)));
-    menu.setColor(QPalette::Disabled, QPalette::WindowText, disabled);
-    menu.setColor(QPalette::Disabled, QPalette::Text, disabled);
-    menu.setColor(QPalette::Disabled, QPalette::Highlight,
-                    QColor(qt_colorref2qrgb(GetSysColor(
-                                            (QSysInfo::WindowsVersion >= QSysInfo::WV_XP
-                                            && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based))
-                                            && isFlat ? COLOR_MENUHILIGHT : COLOR_HIGHLIGHT))));
-    menu.setColor(QPalette::Disabled, QPalette::HighlightedText, disabled);
-    menu.setColor(QPalette::Disabled, QPalette::Button,
-                    menu.color(QPalette::Active, QPalette::Button));
-    menu.setColor(QPalette::Inactive, QPalette::Button,
-                    menu.color(QPalette::Active, QPalette::Button));
-    menu.setColor(QPalette::Inactive, QPalette::Text,
-                    menu.color(QPalette::Active, QPalette::Text));
-    menu.setColor(QPalette::Inactive, QPalette::WindowText,
-                    menu.color(QPalette::Active, QPalette::WindowText));
-    menu.setColor(QPalette::Inactive, QPalette::ButtonText,
-                    menu.color(QPalette::Active, QPalette::ButtonText));
-    menu.setColor(QPalette::Inactive, QPalette::Highlight,
-                    menu.color(QPalette::Active, QPalette::Highlight));
-    menu.setColor(QPalette::Inactive, QPalette::HighlightedText,
-                    menu.color(QPalette::Active, QPalette::HighlightedText));
-    menu.setColor(QPalette::Inactive, QPalette::ButtonText,
-                    pal.color(QPalette::Inactive, QPalette::Dark));
-    QApplication::setPalette(menu, "QMenu");
-
-    if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
-        && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) && isFlat) {
-        QColor menubar(qt_colorref2qrgb(GetSysColor(COLOR_MENUBAR)));
-        menu.setColor(QPalette::Active, QPalette::Button, menubar);
-        menu.setColor(QPalette::Disabled, QPalette::Button, menubar);
-        menu.setColor(QPalette::Inactive, QPalette::Button, menubar);
-    }
-    QApplication::setPalette(menu, "QMenuBar");
-}
-
-static void qt_set_windows_updateScrollBar(QWidget *widget)
-{
-    QList<QObject*> children = widget->children();
-    for (int i = 0; i < children.size(); ++i) {
-        QObject *o = children.at(i);
-        if(!o->isWidgetType())
-            continue;
-        if (QWidget *w = static_cast<QWidget *>(o))
-            qt_set_windows_updateScrollBar(w);
-    }
-#ifndef QT_NO_SCROLLBAR
-    if (qobject_cast<QScrollBar*>(widget))
-        widget->updateGeometry();
-#endif
-}
-
-
-/*****************************************************************************
-  qt_init() - initializes Qt for Windows
- *****************************************************************************/
-
-typedef BOOL (WINAPI *PtrSetProcessDPIAware) (VOID);
-static PtrSetProcessDPIAware ptrSetProcessDPIAware = 0;
-PtrUpdateLayeredWindow ptrUpdateLayeredWindow = 0;
-PtrUpdateLayeredWindowIndirect ptrUpdateLayeredWindowIndirect = 0;
-static BOOL WINAPI qt_updateLayeredWindowIndirect(HWND hwnd, const Q_UPDATELAYEREDWINDOWINFO *info)
-{
-    return (*ptrUpdateLayeredWindow)(hwnd, info->hdcDst, info->pptDst, info->psize, info->hdcSrc,
-                                     info->pptSrc, info->crKey, info->pblend, info->dwFlags);
-}
-
-void qt_init(QApplicationPrivate *priv, int)
-{
-
-    int argc = priv->argc;
-    char **argv = priv->argv;
-    int i, j;
-
-  // Get command line params
-
-    j = argc ? 1 : 0;
-    for (i=1; i<argc; i++) {
-        if (argv[i] && *argv[i] != '-') {
-            argv[j++] = argv[i];
-            continue;
-        }
-#if defined(QT_DEBUG)
-        if (qstrcmp(argv[i], "-nograb") == 0)
-            appNoGrab = !appNoGrab;
-        else
-#endif // QT_DEBUG
-            argv[j++] = argv[i];
-    }
-    if(j < priv->argc) {
-        priv->argv[j] = 0;
-        priv->argc = j;
-    }
-
-#ifndef Q_WS_WINCE
-    // No message boxes but important ones
-    SetErrorMode(SetErrorMode(0) | SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
-#endif
-
-#ifndef Q_WS_WINCE
-    // Initialize OLE/COM
-    //         S_OK means success and S_FALSE means that it has already
-    //         been initialized
-    HRESULT r;
-    r = OleInitialize(0);
-    if (r != S_OK && r != S_FALSE) {
-        qWarning("Qt: Could not initialize OLE (error %x)", (unsigned int)r);
-    }
-#endif
-
-    // Misc. initialization
-#if defined(QT_DEBUG) && !defined(Q_WS_WINCE)
-    GdiSetBatchLimit(1);
-#endif
-
-    // initialize key mapper
-    QKeyMapper::changeKeyboard();
-
-    QColormap::initialize();
-    QFont::initialize();
-#ifndef QT_NO_CURSOR
-    if (QApplication::type() != QApplication::Tty)
-        QCursorData::initialize();
-#endif
-    qApp->setObjectName(priv->appName());
-
-    // default font
-#ifndef Q_WS_WINCE
-    HGDIOBJ stockFont = GetStockObject(DEFAULT_GUI_FONT);
-#else
-    HGDIOBJ stockFont = GetStockObject(SYSTEM_FONT);
-#endif
-
-    LOGFONT lf;
-    GetObject(stockFont, sizeof(lf), &lf);
-    QFont systemFont = qt_LOGFONTtoQFont(lf, true);
-
-#ifndef Q_WS_WINCE
-    if (systemFont.family() == QLatin1String("MS Shell Dlg")) {
-        systemFont.setFamily(QLatin1String("MS Shell Dlg 2"));
-    }
-#endif
-
-    QApplicationPrivate::setSystemFont(systemFont);
-
-    // QFont::locale_init();  ### Uncomment when it does something on Windows
-
-    if (QApplication::desktopSettingsAware())
-        qt_set_windows_resources();
-
-#ifndef QT_NO_TABLETEVENT
-    initWinTabFunctions();
-#endif // QT_NO_TABLETEVENT
-
-#ifndef QT_NO_IM
-    QApplicationPrivate::inputContext = new QWinInputContext(0);
-#endif
-
-    // Read the initial cleartype settings...
-    qt_win_read_cleartype_settings();
-    qt_win_owndc_required = false;
-
-    extern void qt_win_initialize_directdraw();
-    qt_win_initialize_directdraw();
-
-#ifndef Q_OS_WINCE
-    QSystemLibrary user32(QLatin1String("user32"));
-    ptrUpdateLayeredWindowIndirect = (PtrUpdateLayeredWindowIndirect)user32.resolve("UpdateLayeredWindowIndirect");
-    ptrUpdateLayeredWindow = (PtrUpdateLayeredWindow)user32.resolve("UpdateLayeredWindow");
-
-    if (ptrUpdateLayeredWindow && !ptrUpdateLayeredWindowIndirect)
-        ptrUpdateLayeredWindowIndirect = qt_updateLayeredWindowIndirect;
-
-    // Notify Vista and Windows 7 that we support highter DPI settings
-    ptrSetProcessDPIAware = (PtrSetProcessDPIAware)user32.resolve("SetProcessDPIAware");
-    if (ptrSetProcessDPIAware)
-        ptrSetProcessDPIAware();
-#endif
-
-#ifndef QT_NO_GESTURES
-    priv->GetGestureInfo = 0;
-    priv->GetGestureExtraArgs = 0;
-    priv->CloseGestureInfoHandle = 0;
-    priv->SetGestureConfig = 0;
-    priv->GetGestureConfig = 0;
-    priv->BeginPanningFeedback = 0;
-    priv->UpdatePanningFeedback = 0;
-    priv->EndPanningFeedback = 0;
-
-#if defined(Q_WS_WINCE_WM) && defined(QT_WINCE_GESTURES)
-    priv->GetGestureInfo = (PtrGetGestureInfo) &TKGetGestureInfo;
-    priv->GetGestureExtraArgs = (PtrGetGestureExtraArgs) &TKGetGestureExtraArguments;
-#elif !defined(Q_WS_WINCE)
-  #if !defined(QT_NO_NATIVE_GESTURES)
-    priv->GetGestureInfo = (PtrGetGestureInfo)user32.resolve("GetGestureInfo");
-    priv->GetGestureExtraArgs = (PtrGetGestureExtraArgs)user32.resolve("GetGestureExtraArgs");
-    priv->CloseGestureInfoHandle = (PtrCloseGestureInfoHandle)user32.resolve("CloseGestureInfoHandle");
-    priv->SetGestureConfig = (PtrSetGestureConfig)user32.resolve("SetGestureConfig");
-    priv->GetGestureConfig = (PtrGetGestureConfig)user32.resolve("GetGestureConfig");
-  #endif // QT_NO_NATIVE_GESTURES
-    QSystemLibrary libTheme(QLatin1String("uxtheme"));
-    priv->BeginPanningFeedback = (PtrBeginPanningFeedback)libTheme.resolve("BeginPanningFeedback");
-    priv->UpdatePanningFeedback = (PtrUpdatePanningFeedback)libTheme.resolve("UpdatePanningFeedback");
-    priv->EndPanningFeedback = (PtrEndPanningFeedback)libTheme.resolve("EndPanningFeedback");
-#endif
-#endif // QT_NO_GESTURES
-}
-
-/*****************************************************************************
-  qt_cleanup() - cleans up when the application is finished
- *****************************************************************************/
-
-void qt_cleanup()
-{
-    unregWinClasses();
-    QPixmapCache::clear();
-
-#ifndef QT_NO_CURSOR
-    if (QApplication::type() != QApplication::Tty)
-        QCursorData::cleanup();
-#endif
-    QFont::cleanup();
-    QColormap::cleanup();
-    if (displayDC) {
-        ReleaseDC(0, displayDC);
-        displayDC = 0;
-    }
-
-#ifndef QT_NO_IM
-    delete QApplicationPrivate::inputContext;
-    QApplicationPrivate::inputContext = 0;
-#endif
-
-#ifndef Q_WS_WINCE
-  // Deinitialize OLE/COM
-    OleUninitialize();
-#endif
-}
-
-
-/*****************************************************************************
-  Platform specific global and internal functions
- *****************************************************************************/
-
-Q_GUI_EXPORT HDC qt_win_display_dc()                        // get display DC
-{
-    Q_ASSERT(qApp && qApp->thread() == QThread::currentThread());
-    if (!displayDC)
-        displayDC = GetDC(0);
-    return displayDC;
-}
-
-bool qt_nograb()                                // application no-grab option
-{
-#if defined(QT_DEBUG)
-    return appNoGrab;
-#else
-    return false;
-#endif
-}
-
-typedef QHash<QString, int> WinClassNameHash;
-Q_GLOBAL_STATIC(WinClassNameHash, winclassNames)
-
-//
-// If 0 is passed as the widget pointer, register a window class
-// for QWidget as default. This is used in QGLTemporaryContext
-// during GL initialization, where we don't want to use temporary
-// QWidgets or QGLWidgets, neither do we want to have separate code
-// to register window classes.
-//
-const QString qt_reg_winclass(QWidget *w)        // register window class
-{
-    Qt::WindowFlags flags = w ? w->windowFlags() : (Qt::WindowFlags)0;
-    Qt::WindowFlags type = flags & Qt::WindowType_Mask;
-
-    uint style;
-    bool icon;
-    QString cname;
-    if (w && qt_widget_private(w)->isGLWidget) {
-        cname = QLatin1String("QGLWidget");
-        style = CS_DBLCLKS;
-#ifndef Q_WS_WINCE
-        style |= CS_OWNDC;
-#endif
-        icon  = true;
-    } else if (w && (flags & Qt::MSWindowsOwnDC)) {
-        cname = QLatin1String("QWidgetOwnDC");
-        style = CS_DBLCLKS;
-#ifndef Q_WS_WINCE
-        style |= CS_OWNDC;
-#endif
-        icon  = true;
-    } else if (w && (type == Qt::Tool || type == Qt::ToolTip)) {
-        style = CS_DBLCLKS;
-        if (type == Qt::ToolTip || w->inherits("QTipLabel") || w->inherits("QAlphaWidget")) {
-            if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
-                && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based))) {
-                style |= CS_DROPSHADOW;
-            }
-            cname = QLatin1String("QToolTip");
-        } else {
-            cname = QLatin1String("QTool");
-        }
-#ifndef Q_WS_WINCE
-        style |= CS_SAVEBITS;
-#endif
-        icon = false;
-    } else if (w && (type == Qt::Popup)) {
-        cname = QLatin1String("QPopup");
-        style = CS_DBLCLKS;
-#ifndef Q_WS_WINCE
-        style |= CS_SAVEBITS;
-#endif
-        if ((QSysInfo::WindowsVersion >= QSysInfo::WV_XP
-            && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)))
-            style |= CS_DROPSHADOW;
-        icon = false;
-    } else {
-        cname = QLatin1String("QWidget");
-        style = CS_DBLCLKS;
-        icon  = true;
-    }
-
-#ifndef Q_WS_WINCE
-    // force CS_OWNDC when the GL graphics system is
-    // used as the default renderer
-    if (qt_win_owndc_required)
-        style |= CS_OWNDC;
-#endif
-
-#ifdef Q_OS_WINCE
-    // We need to register the classes with the
-    // unique ID on WinCE to make sure we can
-    // move the windows to the front when starting
-    // a second instance.
-    wchar_t uniqueAppID[MAX_PATH];
-    GetModuleFileName(0, uniqueAppID, MAX_PATH);
-    cname = QString::number(RegisterWindowMessage(
-              (const wchar_t *) QString::fromWCharArray(uniqueAppID).toLower().replace(QLatin1Char('\\'),
-              QLatin1Char('_')).utf16()));
-#endif
-
-    // since multiple Qt versions can be used in one process
-    // each one has to have window class names with a unique name
-    // The first instance gets the unmodified name; if the class
-    // has already been registered by another instance of Qt then
-    // add an instance-specific ID, the address of the window proc.
-    static int classExists = -1;
-
-    if (classExists == -1) {
-        WNDCLASS wcinfo;
-        classExists = GetClassInfo((HINSTANCE)qWinAppInst(), (wchar_t*)cname.utf16(), &wcinfo);
-        classExists = classExists && wcinfo.lpfnWndProc != QtWndProc;
-    }
-
-    if (classExists)
-        cname += QString::number((quintptr)QtWndProc);
-
-    if (winclassNames()->contains(cname))        // already registered in our list
-        return cname;
-
-#ifndef Q_WS_WINCE
-    WNDCLASSEX wc;
-    wc.cbSize       = sizeof(WNDCLASSEX);
-#else
-    WNDCLASS wc;
-#endif
-    wc.style        = style;
-    wc.lpfnWndProc  = (WNDPROC)QtWndProc;
-    wc.cbClsExtra   = 0;
-    wc.cbWndExtra   = 0;
-    wc.hInstance    = qWinAppInst();
-    if (icon) {
-        wc.hIcon = (HICON)LoadImage(qWinAppInst(), L"IDI_ICON1", IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);
-#ifndef Q_WS_WINCE
-        if (wc.hIcon) {
-            int sw = GetSystemMetrics(SM_CXSMICON);
-            int sh = GetSystemMetrics(SM_CYSMICON);
-            wc.hIconSm = (HICON)LoadImage(qWinAppInst(), L"IDI_ICON1", IMAGE_ICON, sw, sh, 0);
-        } else {
-            wc.hIcon = (HICON)LoadImage(0, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
-            wc.hIconSm = 0;
-        }
-#endif
-    } else {
-        wc.hIcon    = 0;
-#ifndef Q_WS_WINCE
-        wc.hIconSm  = 0;
-#endif
-    }
-    wc.hCursor      = 0;
-#ifndef Q_WS_WINCE
-    HBRUSH brush = 0;
-    if (w && !qt_widget_private(w)->isGLWidget)
-        brush = (HBRUSH)GetSysColorBrush(COLOR_WINDOW);
-    wc.hbrBackground = brush;
-#else
-    wc.hbrBackground = 0;
-#endif
-    wc.lpszMenuName  = 0;
-    wc.lpszClassName = (wchar_t*)cname.utf16();
-
-#ifndef Q_WS_WINCE
-    ATOM atom = RegisterClassEx(&wc);
-#else
-    ATOM atom = RegisterClass(&wc);
-#endif
-
-#ifndef QT_NO_DEBUG
-    if (!atom)
-        qErrnoWarning("QApplication::regClass: Registering window class failed.");
-#else
-    Q_UNUSED(atom);
-#endif
-
-    winclassNames()->insert(cname, 1);
-    return cname;
-}
-
-Q_GUI_EXPORT const QString qt_getRegisteredWndClass()
-{
-    return qt_reg_winclass(0);
-}
-
-static void unregWinClasses()
-{
-    WinClassNameHash *hash = winclassNames();
-    QHash<QString, int>::ConstIterator it = hash->constBegin();
-    while (it != hash->constEnd()) {
-        UnregisterClass((wchar_t*)it.key().utf16(), qWinAppInst());
-        ++it;
-    }
-    hash->clear();
-}
-
-
-/*****************************************************************************
-  Safe configuration (move,resize,setGeometry) mechanism to avoid
-  recursion when processing messages.
- *****************************************************************************/
-
-struct QWinConfigRequest {
-    WId         id;                                        // widget to be configured
-    int         req;                                        // 0=move, 1=resize, 2=setGeo
-    int         x, y, w, h;                                // request parameters
-};
-
-static QList<QWinConfigRequest*> *configRequests = 0;
-
-void qWinRequestConfig(WId id, int req, int x, int y, int w, int h)
-{
-    if (!configRequests)                        // create queue
-        configRequests = new QList<QWinConfigRequest*>;
-    QWinConfigRequest *r = new QWinConfigRequest;
-    r->id = id;                                        // create new request
-    r->req = req;
-    r->x = x;
-    r->y = y;
-    r->w = w;
-    r->h = h;
-    configRequests->append(r);                // store request in queue
-}
-
-static void qWinProcessConfigRequests()                // perform requests in queue
-{
-    if (!configRequests)
-        return;
-    QWinConfigRequest *r;
-    for (;;) {
-        if (configRequests->isEmpty())
-            break;
-        r = configRequests->takeLast();
-        QWidget *w = QWidget::find(r->id);
-        QRect rect(r->x, r->y, r->w, r->h);
-        int req = r->req;
-        delete r;
-
-        if ( w ) {                              // widget exists
-            if (w->testAttribute(Qt::WA_WState_ConfigPending))
-                return;                         // biting our tail
-            if (req == 0)
-                w->move(rect.topLeft());
-            else if (req == 1)
-                w->resize(rect.size());
-            else
-                w->setGeometry(rect);
-        }
-    }
-    delete configRequests;
-    configRequests = 0;
-}
-
-
-/*****************************************************************************
-    GUI event dispatcher
- *****************************************************************************/
-
-class QGuiEventDispatcherWin32 : public QEventDispatcherWin32
-{
-    Q_DECLARE_PRIVATE(QEventDispatcherWin32)
-public:
-    QGuiEventDispatcherWin32(QObject *parent = 0);
-    bool processEvents(QEventLoop::ProcessEventsFlags flags);
-};
-
-QGuiEventDispatcherWin32::QGuiEventDispatcherWin32(QObject *parent)
-    : QEventDispatcherWin32(parent)
-{
-    createInternalHwnd();
-}
-
-bool QGuiEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
-{
-    if (!QEventDispatcherWin32::processEvents(flags))
-        return false;
-
-    if (configRequests)                        // any pending configs?
-        qWinProcessConfigRequests();
-
-    return true;
-}
-
-void QApplicationPrivate::createEventDispatcher()
-{
-    Q_Q(QApplication);
-    if (q->type() != QApplication::Tty)
-        eventDispatcher = new QGuiEventDispatcherWin32(q);
-    else
-        eventDispatcher = new QEventDispatcherWin32(q);
-}
-
-/*****************************************************************************
-  Platform specific QApplication members
- *****************************************************************************/
-
-
-#ifndef QT_NO_CURSOR
-
-/*****************************************************************************
-  QApplication cursor stack
- *****************************************************************************/
-
-void QApplication::setOverrideCursor(const QCursor &cursor)
-{
-    qApp->d_func()->cursor_list.prepend(cursor);
-    SetCursor(qApp->d_func()->cursor_list.first().handle());
-}
-
-void QApplication::restoreOverrideCursor()
-{
-    if (qApp->d_func()->cursor_list.isEmpty())
-        return;
-    qApp->d_func()->cursor_list.removeFirst();
-
-    if (!qApp->d_func()->cursor_list.isEmpty()) {
-        SetCursor(qApp->d_func()->cursor_list.first().handle());
-    } else {
-        QWidget *w = QWidget::find(curWin);
-        if (w)
-            SetCursor(w->cursor().handle());
-        else
-            SetCursor(QCursor(Qt::ArrowCursor).handle());
-    }
-}
-
-#endif
-
-/*
-  Internal function called from QWidget::setCursor()
-   force is true if this function is called from dispatchEnterLeave, it means that the
-   mouse is actually directly under this widget.
-*/
-
-#ifndef QT_NO_CURSOR
-void qt_win_set_cursor(QWidget *w, bool force)
-{
-    static QPointer<QWidget> lastUnderMouse = 0;
-    if (force) {
-        lastUnderMouse = w;
-    } else if (w->testAttribute(Qt::WA_WState_Created) && lastUnderMouse
-               && lastUnderMouse->effectiveWinId() == w->effectiveWinId()) {
-        w = lastUnderMouse;
-    }
-
-    if (!curWin && w && w->internalWinId())
-        return;
-    QWidget* cW = w && !w->internalWinId() ? w : QWidget::find(curWin);
-    if (!cW || cW->window() != w->window() ||
-         !cW->isVisible() || !cW->underMouse() || QApplication::overrideCursor())
-        return;
-
-    SetCursor(cW->cursor().handle());
-}
-#endif // QT_NO_CURSOR
-
-Qt::KeyboardModifiers qt_win_getKeyboardModifiers()
-{
-    Qt::KeyboardModifiers modifiers = Qt::NoModifier;
-    if (GetKeyState(VK_SHIFT) < 0)
-        modifiers |= Qt::ShiftModifier;
-    if (GetKeyState(VK_CONTROL) < 0)
-        modifiers |= Qt::ControlModifier;
-    if (GetKeyState(VK_MENU) < 0)
-        modifiers |= Qt::AltModifier;
-    return modifiers;
-}
-
-Qt::KeyboardModifiers QApplication::queryKeyboardModifiers()
-{
-    return qt_win_getKeyboardModifiers();
-}
-
-/*****************************************************************************
-  Routines to find a Qt widget from a screen position
- *****************************************************************************/
-
-QWidget *QApplication::topLevelAt(const QPoint &pos)
-{
-    POINT p;
-    HWND  win;
-    QWidget *w;
-    p.x = pos.x();
-    p.y = pos.y();
-    win = WindowFromPoint(p);
-    if (!win)
-        return 0;
-
-    w = QWidget::find(win);
-    while (!w && win) {
-        win = GetParent(win);
-        w = QWidget::find(win);
-    }
-    return w ? w->window() : 0;
-}
-
-void QApplication::beep()
-{
-    MessageBeep(MB_OK);
-}
-
-static void alert_widget(QWidget *widget, int duration)
-{
-#ifdef Q_OS_WINCE
-    Q_UNUSED(widget);
-    Q_UNUSED(duration);
-#else
-    bool stopFlash = duration < 0;
-
-    if (widget && (!widget->isActiveWindow() || stopFlash)) {
-        DWORD timeOut = GetCaretBlinkTime();
-        if (timeOut <= 0)
-            timeOut = 250;
-
-        UINT flashCount;
-        if (duration == 0)
-            flashCount = 10;
-        else
-            flashCount = duration/timeOut;
-
-        FLASHWINFO info;
-        info.cbSize = sizeof(info);
-        info.hwnd = widget->window()->winId();
-        info.dwFlags = stopFlash ? FLASHW_STOP : FLASHW_TRAY;
-        info.dwTimeout = stopFlash ? 0 : timeOut;
-        info.uCount = stopFlash ? 0 : flashCount;
-
-        FlashWindowEx(&info);
-    }
-#endif
-}
-
-void QApplication::alert(QWidget *widget, int duration)
-{
-    if (!QApplicationPrivate::checkInstance("alert"))
-        return;
-
-    if (widget) {
-        alert_widget(widget, duration);
-    } else {
-        const QWidgetList toplevels(topLevelWidgets());
-        for (int i = 0; i < toplevels.count(); ++i) {
-            QWidget *topLevel = toplevels.at(i);
-            alert_widget(topLevel, duration);
-        }
-    }
-}
-
-QString QApplicationPrivate::appName() const
-{
-    return QCoreApplicationPrivate::appName();
-}
-
-
-/*****************************************************************************
-  Main event loop
- *****************************************************************************/
-
-extern uint qGlobalPostedEventsCount();
-
-void QApplication::winFocus(QWidget *widget, bool gotFocus)
-{
-    if (d_func()->inPopupMode()) // some delayed focus event to ignore
-        return;
-    if (gotFocus) {
-        setActiveWindow(widget);
-        if (QApplicationPrivate::active_window
-            && (QApplicationPrivate::active_window->windowType() == Qt::Dialog)) {
-            // raise the entire application, not just the dialog
-            QWidget* mw = QApplicationPrivate::active_window;
-#ifndef Q_WS_WINCE
-            while(mw->parentWidget() && (mw->windowType() == Qt::Dialog))
-                mw = mw->parentWidget()->window();
-            if (mw->testAttribute(Qt::WA_WState_Created) && mw != QApplicationPrivate::active_window)
-                SetWindowPos(mw->internalWinId(), HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-#else
-            // On Desktop Windows, we set the first parent of the dialog on top
-            // Child windows will be automatically set above again.
-            // On Windows CE we pass no parent in CreateWindowEx as otherwise
-            // dialogs get embedded into the parent window. Thus we need to
-            // manually iterate and reactivate all windows from bottom up.
-            QList<QWidget*> raiseList;
-            raiseList.push_back(mw);
-            while(mw->parentWidget() && (mw->windowType() == Qt::Dialog)) {
-                mw = mw->parentWidget()->window();
-                raiseList.push_back(mw);
-            }
-            while(!raiseList.isEmpty()) {
-                mw = raiseList.takeLast();
-                if (mw->testAttribute(Qt::WA_WState_Created)) {
-                    HWND state = HWND_TOP;
-                    if (mw->windowFlags() & Qt::WindowStaysOnBottomHint)
-                        state = HWND_BOTTOM;
-                    else if (mw->windowFlags() & Qt::WindowStaysOnTopHint)
-                        state = HWND_TOPMOST;
-                    SetWindowPos(mw->internalWinId(), state, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-                }
-            }
-#endif
-        }
-    } else {
-        setActiveWindow(0);
-    }
-}
-
-
-//
-// QtWndProc() receives all messages from the main event loop
-//
-
-static bool inLoop = false;
-static int inputcharset = CP_ACP;
-
-#define RETURN(x) { inLoop=false;return x; }
-
-static bool qt_is_translatable_mouse_event(UINT message)
-{
-    return (((message >= WM_MOUSEFIRST && message <= WM_MOUSELAST) ||
-                (message >= WM_XBUTTONDOWN && message <= WM_XBUTTONDBLCLK))
-            && message != WM_MOUSEWHEEL
-            && message != WM_MOUSEHWHEEL)
-
-#ifndef Q_WS_WINCE
-            || (message >= WM_NCMOUSEMOVE && message <= WM_NCMBUTTONDBLCLK)
-#endif
-            ;
-}
-
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
-{
-    bool result = true;
-    QEvent::Type evt_type = QEvent::None;
-    QETWidget *widget = 0;
-
-        // there is no need to process pakcets from tablet unless
-        // it is actually on the tablet, a flag to let us know...
-        int nPackets;        // the number of packets we get from the queue
-
-    long res = 0;
-    if (!qApp)                                // unstable app state
-#ifndef QT_NO_IM
-        RETURN(QWinInputContext::DefWindowProc(hwnd,message,wParam,lParam))
-#else
-        return res;
-#endif // QT_NO_IM
-    QScopedLoopLevelCounter loopLevelCounter(QThreadData::get2(qApp->thread()));
-
-#if 0
-    // make sure we update widgets also when the user resizes
-    if (inLoop && qApp->loopLevel())
-        qApp->sendPostedEvents(0, QEvent::Paint);
-#endif
-
-    inLoop = true;
-
-    MSG msg;
-    msg.hwnd = hwnd;                                // create MSG structure
-    msg.message = message;                        // time and pt fields ignored
-    msg.wParam = wParam;
-    msg.lParam = lParam;
-    msg.pt.x = GET_X_LPARAM(lParam);
-    msg.pt.y = GET_Y_LPARAM(lParam);
-    // If it's a non-client-area message the coords are screen coords, otherwise they are
-    // client coords.
-#ifndef Q_WS_WINCE
-    if (message < WM_NCMOUSEMOVE || message > WM_NCMBUTTONDBLCLK)
-#endif
-        ClientToScreen(msg.hwnd, &msg.pt);
-
-    /*
-    // sometimes the autograb is not released, so the clickevent is sent
-    // to the wrong window. We ignore this for now, because it doesn't
-    // cause any problems.
-    if (msg.message == WM_LBUTTONDOWN || msg.message == WM_RBUTTONDOWN || msg.message == WM_MBUTTONDOWN) {
-        HWND handle = WindowFromPoint(msg.pt);
-        if (msg.hwnd != handle) {
-            msg.hwnd = handle;
-            hwnd = handle;
-        }
-    }
-    */
-
-#if defined(QT_NON_COMMERCIAL)
-    QT_NC_WNDPROC
-#endif
-
-    // send through app filter
-    if (qApp->filterEvent(&msg, &res))
-        return res;
-
-    // close any opened ime candidate window (enabled only on a popup widget)
-    if (imeParentWnd  && QApplication::activePopupWidget()
-        && (message == WM_MBUTTONDOWN || message == WM_XBUTTONDOWN
-        || message == WM_LBUTTONDOWN || message == WM_RBUTTONDOWN
-#ifndef Q_WS_WINCE
-        || message == WM_NCMBUTTONDOWN || message == WM_NCLBUTTONDOWN
-        || message == WM_NCRBUTTONDOWN)) {
-#else
-                                      )) {
-#endif
-            ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
-    }
-
-    switch (message) {
-#ifndef Q_WS_WINCE
-#ifndef QT_NO_SESSIONMANAGER
-    case WM_QUERYENDSESSION: {
-        if (sm_smActive) // bogus message from windows
-            RETURN(true);
-
-        sm_smActive = true;
-        sm_blockUserInput = true; // prevent user-interaction outside interaction windows
-        sm_cancel = false;
-        if (qt_session_manager_self)
-            qApp->commitData(*qt_session_manager_self);
-        if (lParam & ENDSESSION_LOGOFF) {
-            _flushall();
-        }
-        RETURN(!sm_cancel);
-    }
-    case WM_ENDSESSION: {
-        sm_smActive = false;
-        sm_blockUserInput = false;
-        bool endsession = (bool) wParam;
-
-        // we receive the message for each toplevel window included internal hidden ones,
-        // but the aboutToQuit signal should be emitted only once.
-        QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
-        if (endsession && !qAppPriv->aboutToQuitEmitted) {
-            qAppPriv->aboutToQuitEmitted = true;
-            int index = QApplication::staticMetaObject.indexOfSignal("aboutToQuit()");
-            qApp->qt_metacall(QMetaObject::InvokeMetaMethod, index,0);
-            // since the process will be killed immediately quit() has no real effect
-            QApplication::quit();
-        }
-
-        RETURN(0);
-    }
-#endif
-    case WM_DISPLAYCHANGE:
-        if (QApplication::type() == QApplication::Tty)
-            break;
-        if (qt_desktopWidget) {
-            qt_desktopWidget->move(GetSystemMetrics(76), GetSystemMetrics(77));
-            QSize sz(GetSystemMetrics(78), GetSystemMetrics(79));
-            if (sz == qt_desktopWidget->size()) {
-                 // a screen resized without changing size of the virtual desktop
-                QResizeEvent rs(sz, qt_desktopWidget->size());
-                QApplication::sendEvent(qt_desktopWidget, &rs);
-            } else {
-                qt_desktopWidget->resize(sz);
-            }
-        }
-        break;
-#endif
-
-    case WM_SETTINGCHANGE:
-#ifdef Q_WS_WINCE
-        // CE SIP hide/show
-        if (qt_desktopWidget && wParam == SPI_SETSIPINFO) {
-            QResizeEvent re(QSize(0, 0), QSize(0, 0)); // Calculated by QDesktopWidget
-            QApplication::sendEvent(qt_desktopWidget, &re);
-            break;
-        }
-#endif
-        // ignore spurious XP message when user logs in again after locking
-        if (QApplication::type() == QApplication::Tty)
-            break;
-        if (QApplication::desktopSettingsAware() && wParam != SPI_SETWORKAREA) {
-            widget = (QETWidget*)QWidget::find(hwnd);
-            if (widget) {
-                if (wParam == SPI_SETNONCLIENTMETRICS)
-                    widget->markFrameStrutDirty();
-            }
-        }
-        else if (qt_desktopWidget && wParam == SPI_SETWORKAREA) {
-            qt_desktopWidget->move(GetSystemMetrics(76), GetSystemMetrics(77));
-            QSize sz(GetSystemMetrics(78), GetSystemMetrics(79));
-            if (sz == qt_desktopWidget->size()) {
-                 // a screen resized without changing size of the virtual desktop
-                QResizeEvent rs(sz, qt_desktopWidget->size());
-                QApplication::sendEvent(qt_desktopWidget, &rs);
-            } else {
-                qt_desktopWidget->resize(sz);
-            }
-        }
-
-        if (wParam == SPI_SETFONTSMOOTHINGTYPE) {
-            qt_win_read_cleartype_settings();
-            foreach (QWidget *w, QApplication::topLevelWidgets()) {
-                if (!w->isVisible())
-                    continue;
-                ((QETWidget *) w)->forceUpdate();
-            }
-        }
-
-        break;
-    case WM_SYSCOLORCHANGE:
-        if (QApplication::type() == QApplication::Tty)
-            break;
-        if (QApplication::desktopSettingsAware()) {
-            widget = (QETWidget*)QWidget::find(hwnd);
-            if (widget && !widget->parentWidget())
-                qt_set_windows_color_resources();
-        }
-        break;
-
-    case WM_LBUTTONDOWN:
-    case WM_MBUTTONDOWN:
-    case WM_RBUTTONDOWN:
-    case WM_XBUTTONDOWN:
-    case WM_LBUTTONDBLCLK:
-    case WM_RBUTTONDBLCLK:
-    case WM_MBUTTONDBLCLK:
-    case WM_XBUTTONDBLCLK:
-        if (qt_win_ignoreNextMouseReleaseEvent)
-            qt_win_ignoreNextMouseReleaseEvent = false;
-        break;
-
-    case WM_LBUTTONUP:
-    case WM_MBUTTONUP:
-    case WM_RBUTTONUP:
-    case WM_XBUTTONUP:
-        if (qt_win_ignoreNextMouseReleaseEvent) {
-            qt_win_ignoreNextMouseReleaseEvent = false;
-            if (qt_button_down && qt_button_down->internalWinId() == autoCaptureWnd) {
-                releaseAutoCapture();
-                qt_button_down = 0;
-            }
-
-            RETURN(0);
-        }
-        break;
-
-    default:
-        break;
-    }
-
-    if (!widget)
-        widget = (QETWidget*)QWidget::find(hwnd);
-    if (!widget)                                // don't know this widget
-        goto do_default;
-
-    if (app_do_modal)        {                        // modal event handling
-        int ret = 0;
-        if (!qt_try_modal(widget, &msg, ret))
-            RETURN(ret);
-    }
-
-    res = 0;
-    if (widget->winEvent(&msg, &res))                // send through widget filter
-        RETURN(res);
-
-    if (qt_is_translatable_mouse_event(message)) {
-        if (QApplication::activePopupWidget() != 0) { // in popup mode
-            POINT curPos = msg.pt;
-            QWidget* w = QApplication::widgetAt(curPos.x, curPos.y);
-            if (w)
-                widget = (QETWidget*)w;
-        }
-
-        if (!qt_tabletChokeMouse) {
-            result = widget->translateMouseEvent(msg);        // mouse event
-#if defined(Q_WS_WINCE) && !defined(QT_NO_CONTEXTMENU)
-            if (message == WM_LBUTTONDOWN && widget != QApplication::activePopupWidget()) {
-                QWidget* alienWidget = widget;
-                if ((alienWidget != QApplication::activePopupWidget()) && (alienWidget->contextMenuPolicy() != Qt::PreventContextMenu)) {
-                    QPoint pos(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
-                    QPoint globalPos(msg.pt.x, msg.pt.y);
-                    // In case we are using Alien, then the widget to
-                    // send the context menu event is a different one
-                    if (!alienWidget->testAttribute(Qt::WA_NativeWindow) && !alienWidget->testAttribute(Qt::WA_PaintOnScreen)) {
-                        alienWidget = QApplication::widgetAt(globalPos);
-                        if (alienWidget)
-                            pos = alienWidget->mapFromGlobal(globalPos);
-                    }
-                    if (alienWidget) {
-                        SHRGINFO shrg;
-                        shrg.cbSize = sizeof(shrg);
-                        shrg.hwndClient = hwnd;
-                        shrg.ptDown.x = GET_X_LPARAM(lParam);
-                        shrg.ptDown.y = GET_Y_LPARAM(lParam);
-                        shrg.dwFlags = SHRG_RETURNCMD | SHRG_NOANIMATION;
-#ifndef QT_NO_GESTURES
-                        resolveAygLibs();
-                        if (ptrRecognizeGesture && (ptrRecognizeGesture(&shrg) == GN_CONTEXTMENU)) {
-                            if (QApplication::activePopupWidget())
-                                QApplication::activePopupWidget()->close();
-                            QContextMenuEvent e(QContextMenuEvent::Mouse, pos, globalPos);
-                            result = qt_sendSpontaneousEvent(alienWidget, &e);
-                        }
-#endif // QT_NO_GESTURES
-                    }
-                }
-            }
-#endif
-        } else {
-            // Sometimes we only get a WM_MOUSEMOVE message
-            // and sometimes we get both a WM_MOUSEMOVE and
-            // a WM_LBUTTONDOWN/UP, this creates a spurious mouse
-            // press/release event, using the PeekMessage
-            // will help us fix this.  This leaves us with a
-            // question:
-            //    This effectively kills using the mouse AND the
-            //    tablet simultaneously, well creates wacky input.
-            //    Is this going to be a problem? (probably not)
-            bool next_is_button = false;
-            bool is_mouse_move = (message == WM_MOUSEMOVE);
-            if (is_mouse_move) {
-                MSG msg1;
-                if (PeekMessage(&msg1, msg.hwnd, WM_MOUSEFIRST,
-                                WM_MOUSELAST, PM_NOREMOVE))
-                    next_is_button = (msg1.message == WM_LBUTTONUP
-                                       || msg1.message == WM_LBUTTONDOWN);
-            }
-            if (!is_mouse_move || (is_mouse_move && !next_is_button))
-                qt_tabletChokeMouse = false;
-        }
-    } else {
-        switch (message) {
-        case WM_TOUCH:
-            result = QApplicationPrivate::instance()->translateTouchEvent(msg);
-            break;
-        case WM_KEYDOWN:                        // keyboard event
-        case WM_SYSKEYDOWN:
-            qt_keymapper_private()->updateKeyMap(msg);
-            // fall-through intended
-        case WM_KEYUP:
-        case WM_SYSKEYUP:
-#if Q_OS_WINCE_WM
-        case WM_HOTKEY:
-            if(HIWORD(msg.lParam) == VK_TBACK) {
-                const bool hotKeyDown = !(LOWORD(msg.lParam) & MOD_KEYUP);
-                msg.lParam = 0x69 << 16;
-                msg.wParam = VK_BACK;
-                if (hotKeyDown) {
-                    msg.message = WM_KEYDOWN;
-                    qt_keymapper_private()->updateKeyMap(msg);
-                } else {
-                    msg.message = WM_KEYUP;
-                }
-            }
-            // fall-through intended
-#endif
-        case WM_IME_CHAR:
-        case WM_IME_KEYDOWN:
-        case WM_CHAR: {
-            MSG msg1;
-            bool anyMsg = PeekMessage(&msg1, msg.hwnd, 0, 0, PM_NOREMOVE);
-            if (anyMsg && msg1.message == WM_DEADCHAR) {
-                result = true; // consume event since there is a dead char next
-                break;
-            }
-            QWidget *g = QWidget::keyboardGrabber();
-            if (g && qt_get_tablet_widget() && hwnd == qt_get_tablet_widget()->winId()) {
-                // if we get an event for the internal tablet widget,
-                // then don't send it to the keyboard grabber, but
-                // send it to the widget itself (we don't use it right
-                // now, just in case).
-                g = 0;
-            }
-            if (g)
-                widget = (QETWidget*)g;
-            else if (QApplication::activePopupWidget())
-                widget = (QETWidget*)QApplication::activePopupWidget()->focusWidget()
-                       ? (QETWidget*)QApplication::activePopupWidget()->focusWidget()
-                       : (QETWidget*)QApplication::activePopupWidget();
-            else if (QApplication::focusWidget())
-                widget = (QETWidget*)QApplication::focusWidget();
-            else if (!widget || widget->internalWinId() == GetFocus()) // We faked the message to go to exactly that widget.
-                widget = (QETWidget*)widget->window();
-            if (widget->isEnabled())
-                result = sm_blockUserInput
-                            ? true
-                            : qt_keymapper_private()->translateKeyEvent(widget, msg, g != 0);
-            break;
-        }
-        case WM_SYSCHAR:
-            result = true;                        // consume event
-            break;
-
-        case WM_MOUSEWHEEL:
-        case WM_MOUSEHWHEEL:
-            result = widget->translateWheelEvent(msg);
-            break;
-
-        case WM_APPCOMMAND:
-            {
-                uint cmd = GET_APPCOMMAND_LPARAM(lParam);
-                uint uDevice = GET_DEVICE_LPARAM(lParam);
-                uint dwKeys = GET_KEYSTATE_LPARAM(lParam);
-
-                int state = translateButtonState(dwKeys, QEvent::KeyPress, 0);
-
-                switch (uDevice) {
-                case FAPPCOMMAND_KEY:
-                    {
-                        int key = 0;
-
-                        switch(cmd) {
-                        case APPCOMMAND_BASS_BOOST:
-                            key = Qt::Key_BassBoost;
-                            break;
-                        case APPCOMMAND_BASS_DOWN:
-                            key = Qt::Key_BassDown;
-                            break;
-                        case APPCOMMAND_BASS_UP:
-                            key = Qt::Key_BassUp;
-                            break;
-                        case APPCOMMAND_TREBLE_DOWN:
-                            key = Qt::Key_TrebleDown;
-                            break;
-                        case APPCOMMAND_TREBLE_UP:
-                            key = Qt::Key_TrebleUp;
-                            break;
-                        case APPCOMMAND_HELP:
-                            key = Qt::Key_Help;
-                            break;
-                        case APPCOMMAND_FIND:
-                            key = Qt::Key_Search;
-                            break;
-                        default:
-                            break;
-                        }
-                        if (key) {
-                            bool res = false;
-                            QWidget *g = QWidget::keyboardGrabber();
-                            if (g)
-                                widget = (QETWidget*)g;
-                            else if (QApplication::focusWidget())
-                                widget = (QETWidget*)QApplication::focusWidget();
-                            else
-                                widget = (QETWidget*)widget->window();
-                            if (widget->isEnabled()) {
-                                res = QKeyMapper::sendKeyEvent(widget, g != 0, QEvent::KeyPress, key,
-                                                               Qt::KeyboardModifier(state),
-                                                               QString(), false, 0, 0, 0, 0);
-                            }
-                            if (res)
-                                return true;
-                        }
-                    }
-                    break;
-
-                default:
-                    break;
-                }
-
-                result = false;
-            }
-            break;
-
-#ifndef Q_WS_WINCE
-        case WM_NCHITTEST:
-            if (widget->isWindow()) {
-                QPoint pos = widget->mapFromGlobal(QPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)));
-                // don't show resize-cursors for fixed-size widgets
-                QRect fs = widget->frameStrut();
-                if (!widget->isMinimized()) {
-                    if (widget->minimumHeight() == widget->maximumHeight()) {
-                        if (pos.y() < -(fs.top() - fs.left()))
-                            return HTCAPTION;
-                        if (pos.y() >= widget->height())
-                            return HTBORDER;
-                    }
-                    if (widget->minimumWidth() == widget->maximumWidth() && (pos.x() < 0 || pos.x() >= widget->width()))
-                        return HTBORDER;
-                }
-            }
-
-            result = false;
-            break;
-#endif
-
-        case WM_SYSCOMMAND: {
-#ifndef Q_WS_WINCE
-            bool window_state_change = false;
-            Qt::WindowStates oldstate = widget->dataPtr()->window_state;
-            // MSDN:In WM_SYSCOMMAND messages, the four low-order bits of the wParam parameter are
-            // used internally by the system. To obtain the correct result when testing the value of
-            // wParam, an application must combine the value 0xFFF0 with the wParam value by using
-            // the bitwise AND operator.
-            switch(0xfff0 & wParam) {
-            case SC_CONTEXTHELP:
-#ifndef QT_NO_WHATSTHIS
-                QWhatsThis::enterWhatsThisMode();
-#endif
-                DefWindowProc(hwnd, WM_NCPAINT, 1, 0);
-                break;
-#if defined(QT_NON_COMMERCIAL)
-                QT_NC_SYSCOMMAND
-#endif
-            case SC_MINIMIZE:
-                window_state_change = true;
-                widget->dataPtr()->window_state |= Qt::WindowMinimized;
-                if (widget->isVisible()) {
-                    QHideEvent e;
-                    qt_sendSpontaneousEvent(widget, &e);
-                    widget->hideChildren(true);
-                    const QString title = widget->windowIconText();
-                    if (!title.isEmpty())
-                        widget->setWindowTitle_helper(title);
-                }
-                result = false;
-                break;
-            case SC_MAXIMIZE:
-                if(widget->isWindow())
-                    widget->topData()->normalGeometry = widget->geometry();
-            case SC_RESTORE:
-                window_state_change = true;
-                if ((0xfff0 & wParam) == SC_MAXIMIZE)
-                    widget->dataPtr()->window_state |= Qt::WindowMaximized;
-                else if (!widget->isMinimized())
-                    widget->dataPtr()->window_state &= ~Qt::WindowMaximized;
-
-                if (widget->isMinimized()) {
-                    widget->dataPtr()->window_state &= ~Qt::WindowMinimized;
-                    widget->showChildren(true);
-                    QShowEvent e;
-                    qt_sendSpontaneousEvent(widget, &e);
-                    const QString title = widget->windowTitle();
-                    if (!title.isEmpty())
-                        widget->setWindowTitle_helper(title);
-                }
-                result = false;
-                break;
-            default:
-                result = false;
-                break;
-            }
-
-            if (window_state_change) {
-                QWindowStateChangeEvent e(oldstate);
-                qt_sendSpontaneousEvent(widget, &e);
-            }
-#endif // #ifndef Q_OS_WINCE
-
-            break;
-        }
-
-        case WM_SETTINGCHANGE:
-            if ( QApplication::type() == QApplication::Tty )
-                break;
-
-            if (!msg.wParam) {
-#ifdef Q_WS_WINCE
-                // On Windows CE, lParam parameter is a constant, not a char pointer.
-                if (msg.lParam == INI_INTL) {
-#else
-                QString area = QString::fromWCharArray((wchar_t*)msg.lParam);
-                if (area == QLatin1String("intl")) {
-#endif
-                    QLocalePrivate::updateSystemPrivate();
-                    if (!widget->testAttribute(Qt::WA_SetLocale))
-                        widget->dptr()->setLocale_helper(QLocale(), true);
-                    QEvent e(QEvent::LocaleChange);
-                    QApplication::sendEvent(qApp, &e);
-                }
-            }
-            else if (msg.wParam == SPI_SETICONTITLELOGFONT) {
-                if (QApplication::desktopSettingsAware()) {
-                    widget = (QETWidget*)QWidget::find(hwnd);
-                    if (widget && !widget->parentWidget()) {
-                        qt_set_windows_font_resources();
-                    }
-                }
-            }
-            else if (msg.wParam == SPI_SETNONCLIENTMETRICS) {
-                widget = (QETWidget*)QWidget::find(hwnd);
-                if (widget && !widget->parentWidget()) {
-                    qt_set_windows_updateScrollBar(widget);
-                    QEvent e(QEvent::LayoutRequest);
-                    QApplication::sendEvent(widget, &e);
-                }
-        }
-
-            break;
-
-        case WM_PAINT:                                // paint event
-        case WM_ERASEBKGND:                        // erase window background
-            result = widget->translatePaintEvent(msg);
-            break;
-
-#ifndef Q_WS_WINCE
-        case WM_ENTERSIZEMOVE:
-            autoCaptureWnd = hwnd;
-            break;
-        case WM_EXITSIZEMOVE:
-            autoCaptureWnd = 0;
-            break;
-#endif
-        case WM_MOVE:                                // move window
-        case WM_SIZE:                                // resize window
-            result = widget->translateConfigEvent(msg);
-            break;
-
-        case WM_ACTIVATEAPP:
-            if (wParam == FALSE) {
-                QApplication::setActiveWindow(0);
-                // Another application was activated while our popups are open,
-                // then close all popups.  In case some popup refuses to close,
-                // we give up after 1024 attempts (to avoid an infinite loop).
-                int maxiter = 1024;
-                QWidget *popup;
-                while ((popup=QApplication::activePopupWidget()) && maxiter--)
-                    popup->close();
-            }
-            break;
-
-        case WM_ACTIVATE:
-            if ( QApplication::type() == QApplication::Tty )
-                break;
-
-            if (ptrWTOverlap && ptrWTEnable) {
-                // cooperate with other tablet applications, but when
-                // we get focus, I want to use the tablet...
-                if (qt_tablet_context && GET_WM_ACTIVATE_STATE(wParam, lParam)) {
-                    if (ptrWTEnable(qt_tablet_context, true))
-                        ptrWTOverlap(qt_tablet_context, true);
-                }
-            }
-            if (QApplication::activePopupWidget() && LOWORD(wParam) == WA_INACTIVE &&
-                QWidget::find((HWND)lParam) == 0) {
-                // Another application was activated while our popups are open,
-                // then close all popups.  In case some popup refuses to close,
-                // we give up after 1024 attempts (to avoid an infinite loop).
-                int maxiter = 1024;
-                QWidget *popup;
-                while ((popup=QApplication::activePopupWidget()) && maxiter--)
-                    popup->close();
-            }
-
-            if (LOWORD(wParam) != WA_INACTIVE) {
-                // WM_ACTIVATEAPP handles the "true" false case, as this is only when the application
-                // loses focus. Doing it here would result in the widget getting focus to not know
-                // where it got it from; it would simply get a 0 value as the old focus widget.
-#ifdef Q_WS_WINCE
-                {
-#ifdef Q_WS_WINCE_WM
-                    // On Windows mobile we do not receive WM_SYSCOMMAND / SC_MINIMIZE messages.
-                    // Thus we have to unset the minimized state explicitly. We must do this for all
-                    // top-level widgets, because we get the HWND of a random widget here.
-                    foreach (QWidget* tlw, QApplication::topLevelWidgets()) {
-                        if (tlw->isMinimized())
-                            tlw->setWindowState(tlw->windowState() & ~Qt::WindowMinimized);
-                    }
-#else
-                    // On Windows CE we do not receive WM_SYSCOMMAND / SC_MINIMIZE messages.
-                    // Thus we have to unset the minimized state explicitly.
-                    if (widget->windowState() & Qt::WindowMinimized)
-                        widget->setWindowState(widget->windowState() & ~Qt::WindowMinimized);
-#endif  // Q_WS_WINCE_WM
-
-#else
-                if (!(widget->windowState() & Qt::WindowMinimized)) {
-#endif
-                    // Ignore the activate message send by WindowsXP to a minimized window
-#ifdef Q_WS_WINCE_WM
-                    if  (widget->windowState() & Qt::WindowFullScreen)
-                        qt_wince_hide_taskbar(widget->winId());
-#endif
-                    qApp->winFocus(widget, true);
-                    // reset any window alert flashes
-                    alert_widget(widget, -1);
-                }
-            }
-
-            // Windows tries to activate a modally blocked window.
-            // This happens when restoring an application after "Show Desktop"
-            if (app_do_modal && LOWORD(wParam) == WA_ACTIVE) {
-                QWidget *top = 0;
-                if (!QApplicationPrivate::tryModalHelper(widget, &top) && top && widget != top) {
-                    if (top->isVisible()) {
-                        top->activateWindow();
-                    } else {
-                        // This is the case when native file dialogs are shown
-                        QWidget *p = (top->parentWidget() ? top->parentWidget()->window() : 0);
-                        if (p && p->isVisible())
-                            p->activateWindow();
-                    }
-                }
-            }
-            break;
-
-#ifndef Q_WS_WINCE
-            case WM_MOUSEACTIVATE:
-                if (widget->window()->windowType() == Qt::Tool) {
-                    QWidget *w = widget;
-                    if (!w->window()->focusWidget()) {
-                        while (w && (w->focusPolicy() & Qt::ClickFocus) == 0) {
-                            if (w->isWindow()) {
-                                QWidget *fw = w;
-                                while ((fw = fw->nextInFocusChain()) != w && fw->focusPolicy() == Qt::NoFocus)
-                                    ;
-                                if (fw != w)
-                                   break;
-                                QWidget *pw = w->parentWidget();
-                                while (pw) {
-                                    pw = pw->window();
-                                    if (pw && pw->isVisible() && pw->focusWidget()) {
-                                        Q_ASSERT(pw->testAttribute(Qt::WA_WState_Created));
-                                        SetWindowPos(pw->internalWinId(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
-                                        break;
-                                    }
-                                    pw = pw->parentWidget();
-                                }
-                                RETURN(MA_NOACTIVATE);
-                            }
-                            w = w->parentWidget();
-                        }
-                    }
-                }
-                RETURN(MA_ACTIVATE);
-                break;
-#endif
-            case WM_SHOWWINDOW:
-                if (lParam == SW_PARENTOPENING) {
-                    if (widget->testAttribute(Qt::WA_WState_Hidden))
-                        RETURN(0);
-                }
-                if (widget->isWindow() && widget->testAttribute(Qt::WA_WState_Visible)
-                    && !widget->testWindowState(Qt::WindowMinimized)) {
-                    if (lParam == SW_PARENTOPENING) {
-                        QShowEvent e;
-                        qt_sendSpontaneousEvent(widget, &e);
-                        widget->showChildren(true);
-                    } else if (lParam == SW_PARENTCLOSING) {
-                        QHideEvent e;
-                        qt_sendSpontaneousEvent(widget, &e);
-                        widget->hideChildren(true);
-                    }
-                }
-                if  (!wParam && autoCaptureWnd == widget->internalWinId())
-                    releaseAutoCapture();
-                result = false;
-                break;
-
-        case WM_PALETTECHANGED:                        // our window changed palette
-            if (QColormap::hPal() && (WId)wParam == widget->internalWinId())
-                RETURN(0);                        // otherwise: FALL THROUGH!
-            // FALL THROUGH
-        case WM_QUERYNEWPALETTE:                // realize own palette
-            if (QColormap::hPal()) {
-                Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
-                HDC hdc = GetDC(widget->internalWinId());
-                HPALETTE hpalOld = SelectPalette(hdc, QColormap::hPal(), FALSE);
-                uint n = RealizePalette(hdc);
-                if (n)
-                    InvalidateRect(widget->internalWinId(), 0, TRUE);
-                SelectPalette(hdc, hpalOld, TRUE);
-                RealizePalette(hdc);
-                ReleaseDC(widget->internalWinId(), hdc);
-                RETURN(n);
-            }
-            break;
-        case WM_CLOSE:                                // close window
-            widget->translateCloseEvent(msg);
-            RETURN(0);                                // always handled
-
-        case WM_DESTROY:                        // destroy window
-            if (hwnd == curWin) {
-                QWidget *enter = QWidget::mouseGrabber();
-                if (enter == widget)
-                    enter = 0;
-                QApplicationPrivate::dispatchEnterLeave(enter, widget);
-                curWin = enter ? enter->effectiveWinId() : 0;
-                qt_last_mouse_receiver = enter;
-            }
-            if (widget == popupButtonFocus)
-                popupButtonFocus = 0;
-            result = false;
-            break;
-
-#ifndef Q_WS_WINCE
-        case WM_WINDOWPOSCHANGING:
-            {
-                result = false;
-                if (widget->isWindow()) {
-                    WINDOWPOS *winPos = (WINDOWPOS *)lParam;
-                    if (widget->layout() && widget->layout()->hasHeightForWidth()
-                        && !(winPos->flags & (SWP_NOCOPYBITS | SWP_NOSIZE))) {
-                        QRect fs = widget->frameStrut();
-                        QRect rect = widget->geometry();
-                        QRect newRect = QRect(winPos->x + fs.left(),
-                                              winPos->y + fs.top(),
-                                              winPos->cx - fs.left() - fs.right(),
-                                              winPos->cy - fs.top() - fs.bottom());
-
-                        QSize newSize = QLayout::closestAcceptableSize(widget, newRect.size());
-
-                        int dh = newSize.height() - newRect.height();
-                        int dw = newSize.width() - newRect.width();
-                        if (!dw && ! dh)
-                            break; // Size OK
-
-                        if (rect.y() != newRect.y()) {
-                            newRect.setTop(newRect.top() - dh);
-                        } else {
-                            newRect.setBottom(newRect.bottom() + dh);
-                        }
-
-                        if (rect.x() != newRect.x()) {
-                            newRect.setLeft(newRect.left() - dw);
-                        } else {
-                            newRect.setRight(newRect.right() + dw);
-                        }
-
-                        winPos->x = newRect.x() - fs.left();
-                        winPos->y = newRect.y() - fs.top();
-                        winPos->cx = newRect.width() + fs.left() + fs.right();
-                        winPos->cy = newRect.height() + fs.top() + fs.bottom();
-
-                        RETURN(0);
-                    }
-                    if (widget->windowFlags() & Qt::WindowStaysOnBottomHint) {
-                        winPos->hwndInsertAfter = HWND_BOTTOM;
-                    }
-                }
-            }
-            break;
-
-        case WM_GETMINMAXINFO:
-            if (widget->xtra()) {
-                MINMAXINFO *mmi = (MINMAXINFO *)lParam;
-                QWExtra *x = widget->xtra();
-                QRect fs = widget->frameStrut();
-                if ( x->minw > 0 )
-                    mmi->ptMinTrackSize.x = x->minw + fs.right() + fs.left();
-                if ( x->minh > 0 )
-                    mmi->ptMinTrackSize.y = x->minh + fs.top() + fs.bottom();
-                qint32 maxw = (x->maxw >= x->minw) ? x->maxw : x->minw;
-                qint32 maxh = (x->maxh >= x->minh) ? x->maxh : x->minh;
-                if ( maxw < QWIDGETSIZE_MAX ) {
-                    mmi->ptMaxTrackSize.x = maxw + fs.right() + fs.left();
-                    // windows with title bar have an implicit size limit of 112 pixels
-                    if (widget->windowFlags() & Qt::WindowTitleHint)
-                        mmi->ptMaxTrackSize.x = qMax<long>(mmi->ptMaxTrackSize.x, 112);
-                }
-                if ( maxh < QWIDGETSIZE_MAX )
-                    mmi->ptMaxTrackSize.y = maxh + fs.top() + fs.bottom();
-                RETURN(0);
-            }
-            break;
-
-#ifndef QT_NO_CONTEXTMENU
-            case WM_CONTEXTMENU:
-            {
-                // it's not VK_APPS or Shift+F10, but a click in the NC area
-                if (lParam != (int)0xffffffff) {
-                    result = false;
-                    break;
-                }
-
-                QWidget *fw = QWidget::keyboardGrabber();
-                if (!fw) {
-                    if (QApplication::activePopupWidget())
-                        fw = (QApplication::activePopupWidget()->focusWidget()
-                                                  ? QApplication::activePopupWidget()->focusWidget()
-                                                  : QApplication::activePopupWidget());
-                    else if (QApplication::focusWidget())
-                        fw = QApplication::focusWidget();
-                    else if (widget)
-                        fw = widget->window();
-                }
-                if (fw && fw->isEnabled()) {
-                    QPoint pos = fw->inputMethodQuery(Qt::ImMicroFocus).toRect().center();
-                    QContextMenuEvent e(QContextMenuEvent::Keyboard, pos, fw->mapToGlobal(pos),
-                                      qt_win_getKeyboardModifiers());
-                    result = qt_sendSpontaneousEvent(fw, &e);
-                }
-            }
-            break;
-#endif
-#endif
-
-#ifndef QT_NO_IM
-        case WM_IME_STARTCOMPOSITION:
-        case WM_IME_ENDCOMPOSITION:
-        case WM_IME_COMPOSITION: {
-            QWidget *fw = QApplication::focusWidget();
-            QWinInputContext *im = fw ? qobject_cast<QWinInputContext *>(fw->inputContext()) : 0;
-            if (fw && im) {
-                if(message == WM_IME_STARTCOMPOSITION)
-                    result = im->startComposition();
-                else if (message == WM_IME_ENDCOMPOSITION)
-                    result = im->endComposition();
-                else if (message == WM_IME_COMPOSITION)
-                    result = im->composition(lParam);
-            }
-            break;
-        }
-        case WM_IME_REQUEST: {
-            QWidget *fw = QApplication::focusWidget();
-            QWinInputContext *im = fw ? qobject_cast<QWinInputContext *>(fw->inputContext()) : 0;
-            if (fw && im) {
-                if(wParam == IMR_RECONVERTSTRING) {
-                    int ret = im->reconvertString((RECONVERTSTRING *)lParam);
-                    if (ret == -1) {
-                        result = false;
-                    } else {
-                        return ret;
-                    }
-                } else if (wParam == IMR_CONFIRMRECONVERTSTRING) {
-                    RETURN(TRUE);
-                } else {
-                    // in all other cases, call DefWindowProc()
-                    result = false;
-                }
-            }
-            break;
-        }
-#endif // QT_NO_IM
-#ifndef Q_WS_WINCE
-        case WM_CHANGECBCHAIN:
-        case WM_DRAWCLIPBOARD:
-#endif
-        case WM_RENDERFORMAT:
-        case WM_RENDERALLFORMATS:
-#ifndef QT_NO_CLIPBOARD
-        case WM_DESTROYCLIPBOARD:
-            if (qt_clipboard) {
-                QClipboardEvent e(reinterpret_cast<QEventPrivate *>(&msg));
-                qt_sendSpontaneousEvent(qt_clipboard, &e);
-                RETURN(0);
-            }
-            result = false;
-            break;
-#endif //QT_NO_CLIPBOARD
-#ifndef QT_NO_ACCESSIBILITY
-        case WM_GETOBJECT:
-            {
-#if !defined(Q_OS_WINCE)
-                /* On Win64, lParam can be 0x00000000fffffffc or 0xfffffffffffffffc (!),
-                   but MSDN says that lParam should be converted to a DWORD
-                   before its compared against OBJID_CLIENT
-                */
-                const DWORD dwObjId = (DWORD)lParam;
-                // Ignoring all requests while starting up
-                if (QApplication::startingUp() || QApplication::closingDown() || dwObjId != OBJID_CLIENT) {
-                    result = false;
-                    break;
-                }
-
-                typedef LRESULT (WINAPI *PtrLresultFromObject)(REFIID, WPARAM, LPUNKNOWN);
-                static PtrLresultFromObject ptrLresultFromObject = 0;
-                static bool oleaccChecked = false;
-                if (!oleaccChecked) {
-                    QSystemLibrary oleacclib(QLatin1String("oleacc"));
-                    ptrLresultFromObject = (PtrLresultFromObject)oleacclib.resolve("LresultFromObject");
-                    oleaccChecked = true;
-                }
-                if (ptrLresultFromObject) {
-                    QAccessibleInterface *acc = QAccessible::queryAccessibleInterface(widget);
-                    if (!acc) {
-                        result = false;
-                        break;
-                    }
-
-                    // and get an instance of the IAccessibile implementation
-                    IAccessible *iface = qt_createWindowsAccessible(acc);
-                    res = ptrLresultFromObject(IID_IAccessible, wParam, iface);  // ref == 2
-                    iface->Release(); // the client will release the object again, and then it will destroy itself
-
-                    if (res > 0)
-                        RETURN(res);
-                }
-#endif
-            }
-            result = false;
-            break;
-        case WM_GETTEXT:
-            if (!widget->isWindow()) {
-                int ret = 0;
-                QAccessibleInterface *acc = QAccessible::queryAccessibleInterface(widget);
-                if (acc) {
-                    QString text = acc->text(QAccessible::Name, 0);
-                    if (text.isEmpty())
-                        text = widget->objectName();
-                    ret = qMin<int>(wParam - 1, text.size());
-                    text.resize(ret);
-                    memcpy((void *)lParam, text.utf16(), (text.size() + 1) * sizeof(ushort));
-                    delete acc;
-                }
-                if (!ret) {
-                    result = false;
-                    break;
-                }
-                RETURN(ret);
-            }
-            result = false;
-            break;
-#endif
-        case WT_PACKET:
-            if (ptrWTPacketsGet) {
-                if ((nPackets = ptrWTPacketsGet(qt_tablet_context, QT_TABLET_NPACKETQSIZE, &localPacketBuf))) {
-                    result = widget->translateTabletEvent(msg, localPacketBuf, nPackets);
-                }
-            }
-            break;
-        case WT_PROXIMITY:
-
-            #ifndef QT_NO_TABLETEVENT
-            if (ptrWTPacketsGet && ptrWTInfo) {
-                const bool enteredProximity = LOWORD(lParam) != 0;
-                PACKET proximityBuffer[1]; // we are only interested in the first packet in this case
-                const int totalPacks = ptrWTPacketsGet(qt_tablet_context, 1, proximityBuffer);
-                if (totalPacks > 0) {
-                    const UINT currentCursor = proximityBuffer[0].pkCursor;
-
-                    UINT csr_physid;
-                    ptrWTInfo(WTI_CURSORS + currentCursor, CSR_PHYSID, &csr_physid);
-                    UINT csr_type;
-                    ptrWTInfo(WTI_CURSORS + currentCursor, CSR_TYPE, &csr_type);
-                    const UINT deviceIdMask = 0xFF6; // device type mask && device color mask
-                    quint64 uniqueId = (csr_type & deviceIdMask);
-                    uniqueId = (uniqueId << 32) | csr_physid;
-
-                    // initialising and updating the cursor should be done in response to
-                    // WT_CSRCHANGE. We do it in WT_PROXIMITY because some wintab never send
-                    // the event WT_CSRCHANGE even if asked with CXO_CSRMESSAGES
-                    const QTabletCursorInfo *const globalCursorInfo = tCursorInfo();
-                    if (!globalCursorInfo->contains(uniqueId))
-                        tabletInit(uniqueId, csr_type, qt_tablet_context);
-
-                    currentTabletPointer = globalCursorInfo->value(uniqueId);
-                    tabletUpdateCursor(currentTabletPointer, currentCursor);
-                }
-                qt_tabletChokeMouse = false;
-
-                QTabletEvent tabletProximity(enteredProximity ? QEvent::TabletEnterProximity
-                                                              : QEvent::TabletLeaveProximity,
-                                             QPoint(), QPoint(), QPointF(), currentTabletPointer.currentDevice, currentTabletPointer.currentPointerType, 0, 0,
-                                             0, 0, 0, 0, 0, currentTabletPointer.llId);
-                QApplication::sendEvent(qApp, &tabletProximity);
-            }
-            #endif // QT_NO_TABLETEVENT
-
-            break;
-#ifdef Q_WS_WINCE_WM
-        case WM_SETFOCUS: {
-            HIMC hC;
-            hC = ImmGetContext(hwnd);
-            ImmSetOpenStatus(hC, TRUE);
-            ImmEscape(NULL, hC, IME_ESC_SET_MODE, (LPVOID)IM_SPELL);
-            result = false;
-        }
-        break;
-#endif
-        case WM_KILLFOCUS:
-            if (!QWidget::find((HWND)wParam)) { // we don't get focus, so unset it now
-                if (!widget->hasFocus()) // work around Windows bug after minimizing/restoring
-                    widget = (QETWidget*)QApplication::focusWidget();
-                HWND focus = ::GetFocus();
-                //if there is a current widget and the new widget belongs to the same toplevel window
-                //or if the current widget was embedded into non-qt window (i.e. we won't get WM_ACTIVATEAPP)
-                //then we clear the focus on the widget
-                //in case the new widget belongs to a different widget hierarchy, clearing the focus
-                //will be handled because the active window will change
-                const bool embedded = widget && ((QETWidget*)widget->window())->topData()->embedded;
-                if (widget && (embedded || ::IsChild(widget->window()->internalWinId(), focus))) {
-                    widget->clearFocus();
-                    result = true;
-                } else {
-                    result = false;
-                }
-            } else {
-                result = false;
-            }
-            break;
-        case WM_THEMECHANGED:
-            if ((widget->windowType() == Qt::Desktop) || !qApp || QApplication::closingDown()
-                                                         || QApplication::type() == QApplication::Tty)
-                break;
-
-            if (widget->testAttribute(Qt::WA_WState_Polished))
-                QApplication::style()->unpolish(widget);
-
-            if (widget->testAttribute(Qt::WA_WState_Polished))
-                QApplication::style()->polish(widget);
-            widget->repolishStyle(*QApplication::style());
-            if (widget->isVisible())
-                widget->update();
-            break;
-
-#ifndef Q_WS_WINCE
-        case WM_INPUTLANGCHANGE: {
-            wchar_t info[7];
-            if (!GetLocaleInfo(MAKELCID(lParam, SORT_DEFAULT), LOCALE_IDEFAULTANSICODEPAGE, info, 6)) {
-                inputcharset = CP_ACP;
-            } else {
-                inputcharset = QString::fromWCharArray(info).toInt();
-            }
-            QKeyMapper::changeKeyboard();
-            break;
-        }
-#else
-        case WM_COMMAND: {
-            bool OkCommand = (LOWORD(wParam) == 0x1);
-            bool CancelCommand = (LOWORD(wParam) == 0x2);
-            if (OkCommand)
-                QApplication::postEvent(widget, new QEvent(QEvent::OkRequest));
-            if (CancelCommand)
-                widget->showMinimized();
-            else
-#ifndef QT_NO_MENUBAR
-                QMenuBar::wceCommands(LOWORD(wParam));
-#endif
-            result = true;
-        }
-            break;
-        case WM_HELP:
-            QApplication::postEvent(widget, new QEvent(QEvent::HelpRequest));
-            result = true;
-            break;
-#endif
-
-        case WM_MOUSELEAVE:
-            // We receive a mouse leave for curWin, meaning
-            // the mouse was moved outside our widgets
-            if (widget->internalWinId() == curWin) {
-                bool dispatch = !widget->underMouse();
-                // hasMouse is updated when dispatching enter/leave,
-                // so test if it is actually up-to-date
-                if (!dispatch) {
-                    QRect geom = widget->geometry();
-                    if (widget->parentWidget() && !widget->isWindow()) {
-                        QPoint gp = widget->parentWidget()->mapToGlobal(widget->pos());
-                        geom.setX(gp.x());
-                        geom.setY(gp.y());
-                    }
-                    QPoint cpos = QCursor::pos();
-                    dispatch = !geom.contains(cpos);
-                    if ( !dispatch && !QWidget::mouseGrabber()) {
-                        QWidget *hittest = QApplication::widgetAt(cpos);
-                        dispatch = !hittest || hittest->internalWinId() != curWin;
-                    }
-                    if (!dispatch) {
-                        HRGN hrgn = qt_tryCreateRegion(QRegion::Rectangle, 0,0,0,0);
-                        if (GetWindowRgn(curWin, hrgn) != ERROR) {
-                            QPoint lcpos = widget->mapFromGlobal(cpos);
-                            dispatch = !PtInRegion(hrgn, lcpos.x(), lcpos.y());
-                        }
-                        DeleteObject(hrgn);
-                    }
-                }
-                if (dispatch) {
-                    if (qt_last_mouse_receiver && !qt_last_mouse_receiver->internalWinId())
-                        QApplicationPrivate::dispatchEnterLeave(0, qt_last_mouse_receiver);
-                    else
-                        QApplicationPrivate::dispatchEnterLeave(0, QWidget::find((WId)curWin));
-                    curWin = 0;
-                    qt_last_mouse_receiver = 0;
-                }
-            }
-            break;
-
-        case WM_CANCELMODE:
-            {
-                // this goes through QMenuBar's event filter
-                QEvent e(QEvent::ActivationChange);
-                QApplication::sendEvent(qApp, &e);
-            }
-            break;
-
-        case WM_IME_NOTIFY:
-            // special handling for ime, only for widgets in a popup
-            if (wParam  == IMN_OPENCANDIDATE) {
-                imeParentWnd = hwnd;
-                if (QApplication::activePopupWidget()) {
-                    // temporarily disable the mouse grab to allow mouse input in
-                    // the ime candidate window. The actual handle is untouched
-                    if (autoCaptureWnd)
-                        ReleaseCapture();
-                }
-            } else if (wParam  == IMN_CLOSECANDIDATE) {
-                imeParentWnd = 0;
-                if (QApplication::activePopupWidget()) {
-                    // undo the action above, when candidate window is closed
-                    if (autoCaptureWnd)
-                        SetCapture(autoCaptureWnd);
-                }
-            }
-            result = false;
-            break;
-#ifndef QT_NO_GESTURES
-#if !defined(Q_WS_WINCE) || defined(QT_WINCE_GESTURES)
-        case WM_GESTURE: {
-            GESTUREINFO gi;
-            memset(&gi, 0, sizeof(GESTUREINFO));
-            gi.cbSize = sizeof(GESTUREINFO);
-
-            QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
-            BOOL bResult = false;
-            if (qAppPriv->GetGestureInfo)
-                bResult = qAppPriv->GetGestureInfo((HANDLE)msg.lParam, &gi);
-            if (bResult) {
-                if (gi.dwID == GID_BEGIN) {
-                    // find the alien widget for the gesture position.
-                    // This might not be accurate as the position is the center
-                    // point of two fingers for multi-finger gestures.
-                    QPoint pt(gi.ptsLocation.x, gi.ptsLocation.y);
-                    QWidget *w = widget->childAt(widget->mapFromGlobal(pt));
-                    qAppPriv->gestureWidget = w ? w : widget;
-                }
-                if (qAppPriv->gestureWidget)
-                    static_cast<QETWidget*>(qAppPriv->gestureWidget)->translateGestureEvent(msg, gi);
-                if (qAppPriv->CloseGestureInfoHandle)
-                    qAppPriv->CloseGestureInfoHandle((HANDLE)msg.lParam);
-                if (gi.dwID == GID_END)
-                    qAppPriv->gestureWidget = 0;
-            } else {
-                DWORD dwErr = GetLastError();
-                if (dwErr > 0)
-                    qWarning() << "translateGestureEvent: error = " << dwErr;
-            }
-            result = true;
-            break;
-        }
-#endif // !defined(Q_WS_WINCE) || defined(QT_WINCE_GESTURES)
-#endif // QT_NO_GESTURES
-#ifndef QT_NO_CURSOR
-        case WM_SETCURSOR: {
-            QCursor *ovr = QApplication::overrideCursor();
-            if (ovr) {
-                SetCursor(ovr->handle());
-                RETURN(TRUE);
-            }
-            result = false;
-            break;
-        }
-#endif
-        default:
-            result = false;                        // event was not processed
-            break;
-        }
-    }
-
-    if (evt_type != QEvent::None) {                // simple event
-        QEvent e(evt_type);
-        result = qt_sendSpontaneousEvent(widget, &e);
-    }
-
-    if (result)
-        RETURN(false);
-
-do_default:
-#ifndef QT_NO_IM
-    RETURN(QWinInputContext::DefWindowProc(hwnd,message,wParam,lParam))
-#else
-    RETURN(TRUE);
-#endif
-}
-
-
-/*****************************************************************************
-  Modal widgets; We have implemented our own modal widget mechanism
-  to get total control.
-  A modal widget without a parent becomes application-modal.
-  A modal widget with a parent becomes modal to its parent and grandparents..
-
-  QApplicationPrivate::enterModal()
-        Enters modal state
-        Arguments:
-            QWidget *widget        A modal widget
-
-  QApplicationPrivate::leaveModal()
-        Leaves modal state for a widget
-        Arguments:
-            QWidget *widget        A modal widget
- *****************************************************************************/
-
-bool QApplicationPrivate::modalState()
-{
-    return app_do_modal;
-}
-
-void QApplicationPrivate::enterModal_sys(QWidget *widget)
-{
-    if (!qt_modal_stack)
-        qt_modal_stack = new QWidgetList;
-
-    releaseAutoCapture();
-    ClipCursor(0);
-    QWidget *leave = qt_last_mouse_receiver;
-    if (!leave)
-        leave = QWidget::find((WId)curWin);
-    QApplicationPrivate::dispatchEnterLeave(0, leave);
-    qt_modal_stack->insert(0, widget);
-    app_do_modal = true;
-    curWin = 0;
-    qt_last_mouse_receiver = 0;
-    qt_win_ignoreNextMouseReleaseEvent = false;
-}
-
-void QApplicationPrivate::leaveModal_sys(QWidget *widget)
-{
-    if (qt_modal_stack && qt_modal_stack->removeAll(widget)) {
-        if (qt_modal_stack->isEmpty()) {
-            delete qt_modal_stack;
-            qt_modal_stack = 0;
-            QPoint p(QCursor::pos());
-            app_do_modal = false; // necessary, we may get recursively into qt_try_modal below
-            QWidget* w = QApplication::widgetAt(p.x(), p.y());
-            QWidget *leave = qt_last_mouse_receiver;
-            if (!leave)
-                leave = QWidget::find((WId)curWin);
-            if (QWidget *grabber = QWidget::mouseGrabber()) {
-                w = grabber;
-                if (leave == w)
-                    leave = 0;
-            }
-            QApplicationPrivate::dispatchEnterLeave(w, leave); // send synthetic enter event
-            curWin = w ? w->effectiveWinId() : 0;
-            qt_last_mouse_receiver = w;
-        }
-        qt_win_ignoreNextMouseReleaseEvent = true;
-    }
-    app_do_modal = qt_modal_stack != 0;
-}
-
-bool qt_try_modal(QWidget *widget, MSG *msg, int& ret)
-{
-#if defined(Q_OS_WINCE)
-    Q_UNUSED(ret);
-#endif
-    QWidget * top = 0;
-
-    if (QApplicationPrivate::tryModalHelper(widget, &top))
-        return true;
-
-    int type = msg->message;
-
-    bool block_event = false;
-#ifndef Q_WS_WINCE
-    if (type != WM_NCHITTEST) {
-#endif
-        if ((type >= WM_MOUSEFIRST && type <= WM_MOUSELAST) ||
-             type == WM_MOUSEWHEEL || type == WM_MOUSEHWHEEL ||
-             type == WM_MOUSELEAVE ||
-             (type >= WM_KEYFIRST && type <= WM_KEYLAST)
-#ifndef Q_WS_WINCE
-            || type == WM_NCMOUSEMOVE
-#endif
-         ) {
-            if (type == WM_MOUSEMOVE
-#ifndef Q_WS_WINCE
-                 || type == WM_NCMOUSEMOVE
-#endif
-            ) {
-#ifndef QT_NO_CURSOR
-                QCursor *c = qt_grab_cursor();
-                if (!c)
-                    c = QApplication::overrideCursor();
-                if (c)                                // application cursor defined
-                    SetCursor(c->handle());
-                else
-                    SetCursor(QCursor(Qt::ArrowCursor).handle());
-#endif // QT_NO_CURSOR
-            }
-            block_event = true;
-        } else if (type == WM_CLOSE) {
-            block_event = true;
-        }
-#ifndef Q_WS_WINCE
-        else if (type == WM_MOUSEACTIVATE || type == WM_NCLBUTTONDOWN){
-            if (!top->isActiveWindow()) {
-                top->activateWindow();
-            } else {
-                QApplication::beep();
-            }
-            block_event = true;
-            ret = MA_NOACTIVATEANDEAT;
-        } else if (type == WM_SYSCOMMAND) {
-            if (!(msg->wParam == SC_RESTORE && widget->isMinimized()))
-                block_event = true;
-        }
-    }
-#endif
-
-    return !block_event;
-}
-
-
-/*****************************************************************************
-  Popup widget mechanism
-
-  openPopup()
-        Adds a widget to the list of popup widgets
-        Arguments:
-            QWidget *widget        The popup widget to be added
-
-  closePopup()
-        Removes a widget from the list of popup widgets
-        Arguments:
-            QWidget *widget        The popup widget to be removed
- *****************************************************************************/
-
-void QApplicationPrivate::openPopup(QWidget *popup)
-{
-    if (!QApplicationPrivate::popupWidgets)
-        QApplicationPrivate::popupWidgets = new QWidgetList;
-    QApplicationPrivate::popupWidgets->append(popup);
-    if (!popup->isEnabled())
-        return;
-
-    // close any opened 'ime candidate window'
-    if (imeParentWnd)
-        ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
-
-    if (QApplicationPrivate::popupWidgets->count() == 1 && !qt_nograb()) {
-        Q_ASSERT(popup->testAttribute(Qt::WA_WState_Created));
-        setAutoCapture(popup->internalWinId());        // grab mouse/keyboard
-    }
-    // Popups are not focus-handled by the window system (the first
-    // popup grabbed the keyboard), so we have to do that manually: A
-    // new popup gets the focus
-    if (popup->focusWidget()) {
-        popup->focusWidget()->setFocus(Qt::PopupFocusReason);
-    } else if (QApplicationPrivate::popupWidgets->count() == 1) { // this was the first popup
-        if (QWidget *fw = QApplication::focusWidget()) {
-            QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
-            QApplication::sendEvent(fw, &e);
-        }
-    }
-}
-
-void QApplicationPrivate::closePopup(QWidget *popup)
-{
-    if (!QApplicationPrivate::popupWidgets)
-        return;
-    QApplicationPrivate::popupWidgets->removeAll(popup);
-    POINT curPos;
-    GetCursorPos(&curPos);
-
-    // close any opened 'ime candidate window'
-    if (imeParentWnd)
-        ::SendMessage(imeParentWnd, WM_IME_ENDCOMPOSITION, 0, 0);
-
-    if (QApplicationPrivate::popupWidgets->isEmpty()) { // this was the last popup
-        delete QApplicationPrivate::popupWidgets;
-        QApplicationPrivate::popupWidgets = 0;
-        replayPopupMouseEvent = (!popup->geometry().contains(QPoint(curPos.x, curPos.y))
-                                && !popup->testAttribute(Qt::WA_NoMouseReplay));
-        if (!popup->isEnabled())
-            return;
-        if (!qt_nograb())                        // grabbing not disabled
-            releaseAutoCapture();
-        QWidget *fw = QApplicationPrivate::active_window ? QApplicationPrivate::active_window->focusWidget()
-            : QApplication::focusWidget();
-        if (fw) {
-            if (fw != QApplication::focusWidget()) {
-                fw->setFocus(Qt::PopupFocusReason);
-            } else {
-                QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
-                QApplication::sendEvent(fw, &e);
-            }
-        }
-    } else {
-        // Popups are not focus-handled by the window system (the
-        // first popup grabbed the keyboard), so we have to do that
-        // manually: A popup was closed, so the previous popup gets
-        // the focus.
-        QWidget* aw = QApplicationPrivate::popupWidgets->last();
-        if (QApplicationPrivate::popupWidgets->count() == 1) {
-            Q_ASSERT(aw->testAttribute(Qt::WA_WState_Created));
-            setAutoCapture(aw->internalWinId());
-        }
-        if (QWidget *fw = aw->focusWidget())
-            fw->setFocus(Qt::PopupFocusReason);
-    }
-}
-
-
-
-
-/*****************************************************************************
-  Event translation; translates Windows events to Qt events
- *****************************************************************************/
-
-//
-// Auto-capturing for mouse press and mouse release
-//
-
-static void setAutoCapture(HWND h)
-{
-    if (autoCaptureWnd)
-        releaseAutoCapture();
-    autoCaptureWnd = h;
-    SetCapture(h);
-}
-
-static void releaseAutoCapture()
-{
-    if (autoCaptureWnd) {
-        ReleaseCapture();
-        autoCaptureWnd = 0;
-    }
-}
-
-
-//
-// Mouse event translation
-//
-// Non-client mouse messages are not translated
-//
-
-static const ushort mouseTbl[] = {
-    WM_MOUSEMOVE,        QEvent::MouseMove,               0,
-    WM_LBUTTONDOWN,      QEvent::MouseButtonPress,        Qt::LeftButton,
-    WM_LBUTTONUP,        QEvent::MouseButtonRelease,      Qt::LeftButton,
-    WM_LBUTTONDBLCLK,    QEvent::MouseButtonDblClick,     Qt::LeftButton,
-    WM_RBUTTONDOWN,      QEvent::MouseButtonPress,        Qt::RightButton,
-    WM_RBUTTONUP,        QEvent::MouseButtonRelease,      Qt::RightButton,
-    WM_RBUTTONDBLCLK,    QEvent::MouseButtonDblClick,     Qt::RightButton,
-    WM_MBUTTONDOWN,      QEvent::MouseButtonPress,        Qt::MidButton,
-    WM_MBUTTONUP,        QEvent::MouseButtonRelease,      Qt::MidButton,
-    WM_MBUTTONDBLCLK,    QEvent::MouseButtonDblClick,     Qt::MidButton,
-    // use XButton1 for now, the real X button is decided later
-    WM_XBUTTONDOWN,      QEvent::MouseButtonPress,        Qt::XButton1,
-    WM_XBUTTONUP,        QEvent::MouseButtonRelease,      Qt::XButton1,
-    WM_XBUTTONDBLCLK,    QEvent::MouseButtonDblClick,     Qt::XButton1,
-
-#ifndef Q_WS_WINCE
-    WM_NCMOUSEMOVE,      QEvent::NonClientAreaMouseMove,           0,
-    WM_NCLBUTTONDOWN,    QEvent::NonClientAreaMouseButtonPress,    Qt::LeftButton,
-    WM_NCLBUTTONUP,      QEvent::NonClientAreaMouseButtonRelease,  Qt::LeftButton,
-    WM_NCLBUTTONDBLCLK,  QEvent::NonClientAreaMouseButtonDblClick, Qt::LeftButton,
-    WM_NCRBUTTONDOWN,    QEvent::NonClientAreaMouseButtonPress,    Qt::RightButton,
-    WM_NCRBUTTONUP,      QEvent::NonClientAreaMouseButtonRelease,  Qt::RightButton,
-    WM_NCRBUTTONDBLCLK,  QEvent::NonClientAreaMouseButtonDblClick, Qt::RightButton,
-    WM_NCMBUTTONDOWN,    QEvent::NonClientAreaMouseButtonPress,    Qt::MidButton,
-    WM_NCMBUTTONUP,      QEvent::NonClientAreaMouseButtonRelease,  Qt::MidButton,
-    WM_NCMBUTTONDBLCLK,  QEvent::NonClientAreaMouseButtonDblClick, Qt::MidButton,
-#endif
-
-    0,                        0,                                0
-};
-
-static int translateButtonState(int s, int type, int button)
-{
-    Q_UNUSED(type);
-    Q_UNUSED(button);
-    int bst = 0;
-    if (s & MK_LBUTTON)
-        bst |= Qt::LeftButton;
-    if (s & MK_MBUTTON)
-        bst |= Qt::MidButton;
-    if (s & MK_RBUTTON)
-        bst |= Qt::RightButton;
-    if (s & MK_SHIFT)
-        bst |= Qt::ShiftModifier;
-    if (s & MK_CONTROL)
-        bst |= Qt::ControlModifier;
-
-    if (s & MK_XBUTTON1)
-        bst |= Qt::XButton1;
-    if (s & MK_XBUTTON2)
-        bst |= Qt::XButton2;
-
-    if (GetKeyState(VK_MENU) < 0)
-        bst |= Qt::AltModifier;
-
-    if ((GetKeyState(VK_LWIN) < 0) ||
-         (GetKeyState(VK_RWIN) < 0))
-        bst |= Qt::MetaModifier;
-
-    return bst;
-}
-
-void qt_win_eatMouseMove()
-{
-    // after closing a windows dialog with a double click (i.e. open a file)
-    // the message queue still contains a dubious WM_MOUSEMOVE message where
-    // the left button is reported to be down (wParam != 0).
-    // remove all those messages (usually 1) and post the last one with a
-    // reset button state
-
-    MSG msg = {0, 0, 0, 0, 0, {0, 0} };
-    while (PeekMessage(&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE))
-        ;
-    if (msg.message == WM_MOUSEMOVE)
-        PostMessage(msg.hwnd, msg.message, 0, msg.lParam);
-}
-
-// In DnD, the mouse release event never appears, so the
-// mouse button state machine must be manually reset
-void QApplication::winMouseButtonUp()
-{
-    qt_button_down = 0;
-    releaseAutoCapture();
-}
-
-void QETWidget::repolishStyle(QStyle &)
-{
-    QEvent e(QEvent::StyleChange);
-    QApplication::sendEvent(this, &e);
-}
-
-bool QETWidget::translateMouseEvent(const MSG &msg)
-{
-    if (!isWindow() && testAttribute(Qt::WA_NativeWindow))
-        Q_ASSERT(internalWinId());
-
-    static QPoint pos;
-    static POINT gpos={-1,-1};
-    QEvent::Type type;                                // event parameters
-    int           button;
-    int           state;
-    int           i;
-
-    if (sm_blockUserInput) //block user interaction during session management
-        return true;
-
-    // Compress mouse move events
-    if (msg.message == WM_MOUSEMOVE) {
-        MSG mouseMsg;
-        while (PeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEFIRST,
-               WM_MOUSELAST, PM_NOREMOVE)) {
-            if (mouseMsg.message == WM_MOUSEMOVE) {
-#define PEEKMESSAGE_IS_BROKEN 1
-#ifdef PEEKMESSAGE_IS_BROKEN
-                // Since the Windows PeekMessage() function doesn't
-                // correctly return the wParam for WM_MOUSEMOVE events
-                // if there is a key release event in the queue
-                // _before_ the mouse event, we have to also consider
-                // key release events (kls 2003-05-13):
-                MSG keyMsg;
-                bool done = false;
-                while (PeekMessage(&keyMsg, 0, WM_KEYFIRST, WM_KEYLAST,
-                       PM_NOREMOVE)) {
-                    if (keyMsg.time < mouseMsg.time) {
-                        if ((keyMsg.lParam & 0xC0000000) == 0x40000000) {
-                            PeekMessage(&keyMsg, 0, keyMsg.message,
-                                        keyMsg.message, PM_REMOVE);
-                        } else {
-                            done = true;
-                            break;
-                        }
-                    } else {
-                        break; // no key event before the WM_MOUSEMOVE event
-                    }
-                }
-                if (done)
-                    break;
-#else
-                // Actually the following 'if' should work instead of
-                // the above key event checking, but apparently
-                // PeekMessage() is broken :-(
-                if (mouseMsg.wParam != msg.wParam)
-                    break; // leave the message in the queue because
-                           // the key state has changed
-#endif
-                MSG *msgPtr = (MSG *)(&msg);
-                // Update the passed in MSG structure with the
-                // most recent one.
-                msgPtr->lParam = mouseMsg.lParam;
-                msgPtr->wParam = mouseMsg.wParam;
-                // Extract the x,y coordinates from the lParam as we do in the WndProc
-                msgPtr->pt.x = GET_X_LPARAM(mouseMsg.lParam);
-                msgPtr->pt.y = GET_Y_LPARAM(mouseMsg.lParam);
-                ClientToScreen(msg.hwnd, &(msgPtr->pt));
-                // Remove the mouse move message
-                PeekMessage(&mouseMsg, msg.hwnd, WM_MOUSEMOVE,
-                            WM_MOUSEMOVE, PM_REMOVE);
-            } else {
-                break; // there was no more WM_MOUSEMOVE event
-            }
-        }
-    }
-
-    for (i=0; (UINT)mouseTbl[i] != msg.message && mouseTbl[i]; i += 3)
-        ;
-    if (!mouseTbl[i])
-        return false;
-    type   = (QEvent::Type)mouseTbl[++i];        // event type
-    button = mouseTbl[++i];                        // which button
-    if (button == Qt::XButton1) {
-        switch(GET_XBUTTON_WPARAM(msg.wParam)) {
-        case XBUTTON1:
-            button = Qt::XButton1;
-            break;
-        case XBUTTON2:
-            button = Qt::XButton2;
-            break;
-        }
-    }
-#ifndef Q_OS_WINCE
-    static bool trackMouseEventLookup = false;
-    typedef BOOL (WINAPI *PtrTrackMouseEvent)(LPTRACKMOUSEEVENT);
-    static PtrTrackMouseEvent ptrTrackMouseEvent = 0;
-#endif
-    state  = translateButtonState(msg.wParam, type, button); // button state
-    const QPoint widgetPos = mapFromGlobal(QPoint(msg.pt.x, msg.pt.y));
-    QWidget *alienWidget = !internalWinId() ? this : childAt(widgetPos);
-    if (alienWidget && alienWidget->internalWinId())
-        alienWidget = 0;
-
-    if (type == QEvent::MouseMove || type == QEvent::NonClientAreaMouseMove
-            || type == QEvent::TabletMove) {
-
-        if (!(state & Qt::MouseButtonMask))
-            qt_button_down = 0;
-#ifndef QT_NO_CURSOR
-        QCursor *c = qt_grab_cursor();
-        if (!c)
-            c = QApplication::overrideCursor();
-        if (c)                                // application cursor defined
-            SetCursor(c->handle());
-        else if (type != QEvent::NonClientAreaMouseMove && !qt_button_down) {
-            // use  widget cursor if widget is enabled
-            QWidget *w = alienWidget ? alienWidget : this;
-            while (!w->isWindow() && !w->isEnabled())
-                w = w->parentWidget();
-            SetCursor(w->cursor().handle());
-        }
-#endif // QT_NO_CURSOR
-
-        HWND id = effectiveWinId();
-        QWidget *mouseGrabber = QWidget::mouseGrabber();
-        QWidget *activePopupWidget = QApplication::activePopupWidget();
-        if (mouseGrabber) {
-            if (!activePopupWidget || (activePopupWidget == this && !rect().contains(widgetPos)))
-                id = mouseGrabber->effectiveWinId();
-        } else if (type == QEvent::NonClientAreaMouseMove) {
-            id = 0;
-        }
-
-        if (curWin != id) {                // new current window
-            if (id == 0) {
-                QWidget *leave = qt_last_mouse_receiver;
-                if (!leave)
-                    leave = QWidget::find(curWin);
-                QApplicationPrivate::dispatchEnterLeave(0, leave);
-                qt_last_mouse_receiver = 0;
-                curWin = 0;
-            } else {
-                QWidget *leave = 0;
-                if (curWin && qt_last_mouse_receiver)
-                    leave = qt_last_mouse_receiver;
-                else
-                    leave = QWidget::find(curWin);
-                QWidget *enter = alienWidget ? alienWidget : this;
-                if (mouseGrabber && activePopupWidget) {
-                    if (leave != mouseGrabber)
-                        enter = mouseGrabber;
-                    else
-                        enter = activePopupWidget == this ? this : mouseGrabber;
-                }
-                QApplicationPrivate::dispatchEnterLeave(enter, leave);
-                qt_last_mouse_receiver = enter;
-                curWin = enter ? enter->effectiveWinId() : 0;
-            }
-#ifndef Q_OS_WINCE
-
-            if (curWin != 0) {
-                if (!trackMouseEventLookup) {
-                    ptrTrackMouseEvent = (PtrTrackMouseEvent)QSystemLibrary::resolve(QLatin1String("comctl32"), "_TrackMouseEvent");
-                    trackMouseEventLookup = true;
-                }
-                if (ptrTrackMouseEvent && !qApp->d_func()->inPopupMode()) {
-                    // We always have to set the tracking, since
-                    // Windows detects more leaves than we do..
-                    TRACKMOUSEEVENT tme;
-                    tme.cbSize = sizeof(TRACKMOUSEEVENT);
-                    tme.dwFlags = 0x00000002;    // TME_LEAVE
-                    tme.hwndTrack = curWin;      // Track on window receiving msgs
-                    tme.dwHoverTime = (DWORD)-1; // HOVER_DEFAULT
-                    ptrTrackMouseEvent(&tme);
-                }
-            }
-#endif // Q_OS_WINCE
-        }
-
-        POINT curPos = msg.pt;
-        if (curPos.x == gpos.x && curPos.y == gpos.y)
-            return true;                        // same global position
-        gpos = curPos;
-
-        Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-        ScreenToClient(internalWinId(), &curPos);
-
-        pos.rx() = curPos.x;
-        pos.ry() = curPos.y;
-        pos = d_func()->mapFromWS(pos);
-    } else {
-        gpos = msg.pt;
-        pos = mapFromGlobal(QPoint(gpos.x, gpos.y));
-
-        // mouse button pressed
-        if (!qt_button_down && (type == QEvent::MouseButtonPress || type == QEvent::MouseButtonDblClick)) {
-            QWidget *tlw = window();
-            if (QWidget *child = tlw->childAt(mapTo(tlw, pos)))
-                qt_button_down = child;
-            else
-                qt_button_down = this;
-        }
-    }
-
-    bool res = false;
-
-    bool nonClientAreaEvent = type >= QEvent::NonClientAreaMouseMove
-                                && type <= QEvent::NonClientAreaMouseButtonDblClick;
-
-    if (qApp->d_func()->inPopupMode()) {                        // in popup mode
-
-        if (nonClientAreaEvent)
-            return false;
-
-        replayPopupMouseEvent = false;
-        QWidget* activePopupWidget = QApplication::activePopupWidget();
-        QWidget *target = activePopupWidget;
-        const QPoint globalPos(gpos.x, gpos.y);
-
-        if (target != this) {
-            if ((windowType() == Qt::Popup) && rect().contains(pos) && 0)
-                target = this;
-            else                                // send to last popup
-                pos = target->mapFromGlobal(globalPos);
-        }
-        QWidget *popupChild = target->childAt(pos);
-        bool releaseAfter = false;
-        switch (type) {
-            case QEvent::MouseButtonPress:
-            case QEvent::MouseButtonDblClick:
-                popupButtonFocus = popupChild;
-                break;
-            case QEvent::MouseButtonRelease:
-            case QEvent::TabletRelease:
-
-                releaseAfter = true;
-                break;
-            default:
-                break;                                // nothing for mouse move
-        }
-
-        if (target->isEnabled()) {
-            if (popupButtonFocus) {
-                target = popupButtonFocus;
-            } else if (popupChild) {
-                target = popupChild;
-            }
-
-            pos = target->mapFromGlobal(globalPos);
-                QMouseEvent e(type, pos, globalPos,
-                            Qt::MouseButton(button),
-                            Qt::MouseButtons(state & Qt::MouseButtonMask),
-                            Qt::KeyboardModifiers(state & Qt::KeyboardModifierMask));
-                res = QApplicationPrivate::sendMouseEvent(target, &e, alienWidget, this, &qt_button_down,
-                                                          qt_last_mouse_receiver);
-            res = res && e.isAccepted();
-        } else {
-            // close disabled popups when a mouse button is pressed or released
-            switch (type) {
-            case QEvent::MouseButtonPress:
-            case QEvent::MouseButtonDblClick:
-            case QEvent::MouseButtonRelease:
-                target->close();
-                break;
-            default:
-                break;
-            }
-        }
-
-        if (releaseAfter) {
-            popupButtonFocus = 0;
-            qt_button_down = 0;
-        }
-
-#ifndef Q_OS_WINCE
-        if (type == QEvent::MouseButtonPress
-            && QApplication::activePopupWidget() != activePopupWidget
-            && ptrTrackMouseEvent
-            && curWin) {
-            // Since curWin is already the window we clicked on,
-            // we have to setup the mouse tracking here.
-            TRACKMOUSEEVENT tme;
-            tme.cbSize = sizeof(TRACKMOUSEEVENT);
-            tme.dwFlags = 0x00000002;    // TME_LEAVE
-            tme.hwndTrack = curWin;      // Track on window receiving msgs
-            tme.dwHoverTime = (DWORD)-1; // HOVER_DEFAULT
-            ptrTrackMouseEvent(&tme);
-        }
-#endif
-        if (type == QEvent::MouseButtonPress
-            && QApplication::activePopupWidget() != activePopupWidget
-            && replayPopupMouseEvent) {
-            // the popup disappeared. Replay the event
-            QWidget* w = QApplication::widgetAt(gpos.x, gpos.y);
-            if (w && !QApplicationPrivate::isBlockedByModal(w)) {
-                Q_ASSERT(w->testAttribute(Qt::WA_WState_Created));
-                HWND hwndTarget = w->effectiveWinId();
-                if (QWidget::mouseGrabber() == 0)
-                    setAutoCapture(hwndTarget);
-                if (!w->isActiveWindow())
-                    w->activateWindow();
-                POINT widgetpt = gpos;
-                ScreenToClient(hwndTarget, &widgetpt);
-                LPARAM lParam = MAKELPARAM(widgetpt.x, widgetpt.y);
-                PostMessage(hwndTarget, msg.message, msg.wParam, lParam);
-            }
-        } else if (type == QEvent::MouseButtonRelease && button == Qt::RightButton
-                && QApplication::activePopupWidget() == activePopupWidget) {
-            // popup still alive and received right-button-release
-#if !defined(QT_NO_CONTEXTMENU)
-            QContextMenuEvent e2(QContextMenuEvent::Mouse, pos, globalPos,
-                              qt_win_getKeyboardModifiers());
-            bool res2 = QApplication::sendSpontaneousEvent( target, &e2 );
-            if (!res) // RMB not accepted
-                res = res2 && e2.isAccepted();
-#endif
-        }
-    } else {                                        // not popup mode
-        int bs = state & Qt::MouseButtonMask;
-        if ((type == QEvent::MouseButtonPress ||
-              type == QEvent::MouseButtonDblClick) && bs == button) {
-            Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-            if (QWidget::mouseGrabber() == 0)
-                setAutoCapture(internalWinId());
-        } else if (type == QEvent::MouseButtonRelease && bs == 0) {
-            if (QWidget::mouseGrabber() == 0)
-                releaseAutoCapture();
-        }
-
-        const QPoint globalPos(gpos.x,gpos.y);
-        QWidget *widget = QApplicationPrivate::pickMouseReceiver(this, globalPos, pos, type,
-                                                                 Qt::MouseButtons(bs),
-                                                                 qt_button_down, alienWidget);
-        if (!widget)
-            return false; // don't send event
-
-        QMouseEvent e(type, pos, globalPos, Qt::MouseButton(button),
-                      Qt::MouseButtons(state & Qt::MouseButtonMask),
-                      Qt::KeyboardModifiers(state & Qt::KeyboardModifierMask));
-
-        res = QApplicationPrivate::sendMouseEvent(widget, &e, alienWidget, this, &qt_button_down,
-                                                  qt_last_mouse_receiver);
-
-        // non client area events are only informational, you cannot "handle" them
-        res = res && e.isAccepted() && !nonClientAreaEvent;
-#if !defined(QT_NO_CONTEXTMENU)
-        if (type == QEvent::MouseButtonRelease && button == Qt::RightButton) {
-            QContextMenuEvent e2(QContextMenuEvent::Mouse, pos, globalPos,
-                              qt_win_getKeyboardModifiers());
-            bool res2 = QApplication::sendSpontaneousEvent(widget, &e2);
-            if (!res)
-                res = res2 && e2.isAccepted();
-        }
-#endif
-
-        if (type != QEvent::MouseMove)
-            pos.rx() = pos.ry() = -9999;        // init for move compression
-    }
-    return res;
-}
-
-bool QETWidget::translateWheelEvent(const MSG &msg)
-{
-    int  state = 0;
-
-    if (sm_blockUserInput) // block user interaction during session management
-        return true;
-
-    state = translateButtonState(GET_KEYSTATE_WPARAM(msg.wParam), 0, 0);
-
-    int delta;
-    if (msg.message == WM_MOUSEWHEEL || msg.message == WM_MOUSEHWHEEL)
-        delta = (short) HIWORD (msg.wParam);
-    else
-        delta = (int) msg.wParam;
-
-    Qt::Orientation orient = (msg.message == WM_MOUSEHWHEEL || state&Qt::AltModifier
-#if 0
-    // disabled for now - Trenton's one-wheel mouse makes trouble...
-    // "delta" for usual wheels is +-120. +-240 seems to indicate
-    // the second wheel see more recent MSDN for WM_MOUSEWHEEL
-
-    ( // <- parantheses added to make update happy, remove if the
-      // #if 0 is removed
-        || delta == 240 || delta == -240)?Qt::Horizontal:Vertical;
-    if (delta == 240 || delta == -240)
-        delta /= 2;
-#endif
-       ) ? Qt::Horizontal : Qt::Vertical;
-
-    // according to the MSDN documentation on WM_MOUSEHWHEEL:
-    // a positive value indicates that the wheel was rotated to the right;
-    // a negative value indicates that the wheel was rotated to the left.
-    // Qt defines this value as the exact opposite, so we have to flip the value!
-    if (msg.message == WM_MOUSEHWHEEL)
-        delta = -delta;
-
-    QPoint globalPos;
-
-    globalPos.rx() = (short)LOWORD (msg.lParam);
-    globalPos.ry() = (short)HIWORD (msg.lParam);
-
-
-    // if there is a widget under the mouse and it is not shadowed
-    // by modality, we send the event to it first
-    int ret = 0;
-    QWidget* w = QApplication::widgetAt(globalPos);
-    if (!w || !qt_try_modal(w, (MSG*)&msg, ret)) {
-        //synaptics touchpad shows its own widget at this position
-        //so widgetAt() will fail with that HWND, try child of this widget
-        w = this->childAt(this->mapFromGlobal(globalPos));
-        if (!w)
-            w = this;
-    }
-
-    // send the event to the widget or its ancestors
-    {
-        QWidget* popup = QApplication::activePopupWidget();
-        if (popup && w->window() != popup)
-            popup->close();
-#ifndef QT_NO_WHEELEVENT
-        QWheelEvent e(w->mapFromGlobal(globalPos), globalPos, delta,
-                      Qt::MouseButtons(state & Qt::MouseButtonMask),
-                      Qt::KeyboardModifier(state & Qt::KeyboardModifierMask), orient);
-
-        if (QApplication::sendSpontaneousEvent(w, &e))
-#else
-        Q_UNUSED(orient);
-#endif //QT_NO_WHEELEVENT
-            return true;
-    }
-
-    // send the event to the widget that has the focus or its ancestors, if different
-    if (w != QApplication::focusWidget() && (w = QApplication::focusWidget())) {
-        QWidget* popup = QApplication::activePopupWidget();
-        if (popup && w->window() != popup)
-            popup->close();
-#ifndef QT_NO_WHEELEVENT
-        QWheelEvent e(w->mapFromGlobal(globalPos), globalPos, delta,
-                      Qt::MouseButtons(state & Qt::MouseButtonMask),
-                      Qt::KeyboardModifier(state & Qt::KeyboardModifierMask), orient);
-        if (QApplication::sendSpontaneousEvent(w, &e))
-#endif //QT_NO_WHEELEVENT
-            return true;
-    }
-    return false;
-}
-
-
-//
-// Windows Wintab to QTabletEvent translation
-//
-
-// the following is adapted from the wintab syspress example (public domain)
-/* -------------------------------------------------------------------------- */
-// Initialize the "static" information of a cursor device (pen, airbrush, etc).
-// The QTabletDeviceData is initialized with the data that do not change in time
-// (number of button, type of device, etc) but do not initialize the variable data
-// (e.g.: pen or eraser)
-#ifndef QT_NO_TABLETEVENT
-
-static void tabletInit(const quint64 uniqueId, const UINT csr_type, HCTX hTab)
-{
-    Q_ASSERT(ptrWTInfo);
-    Q_ASSERT(ptrWTGet);
-
-    Q_ASSERT(!tCursorInfo()->contains(uniqueId));
-
-    /* browse WinTab's many info items to discover pressure handling. */
-    AXIS np;
-    LOGCONTEXT lc;
-
-    /* get the current context for its device variable. */
-    ptrWTGet(hTab, &lc);
-
-    /* get the size of the pressure axis. */
-    QTabletDeviceData tdd;
-    tdd.llId = uniqueId;
-
-    ptrWTInfo(WTI_DEVICES + lc.lcDevice, DVC_NPRESSURE, &np);
-    tdd.minPressure = int(np.axMin);
-    tdd.maxPressure = int(np.axMax);
-
-    ptrWTInfo(WTI_DEVICES + lc.lcDevice, DVC_TPRESSURE, &np);
-    tdd.minTanPressure = int(np.axMin);
-    tdd.maxTanPressure = int(np.axMax);
-
-    LOGCONTEXT lcMine;
-
-    /* get default region */
-    ptrWTInfo(WTI_DEFCONTEXT, 0, &lcMine);
-
-    tdd.minX = 0;
-    tdd.maxX = int(lcMine.lcInExtX) - int(lcMine.lcInOrgX);
-
-    tdd.minY = 0;
-    tdd.maxY = int(lcMine.lcInExtY) - int(lcMine.lcInOrgY);
-
-    tdd.minZ = 0;
-    tdd.maxZ = int(lcMine.lcInExtZ) - int(lcMine.lcInOrgZ);
-
-    const uint cursorTypeBitMask = 0x0F06; // bitmask to find the specific cursor type (see Wacom FAQ)
-    if (((csr_type & 0x0006) == 0x0002) && ((csr_type & cursorTypeBitMask) != 0x0902)) {
-        tdd.currentDevice = QTabletEvent::Stylus;
-    } else {
-        switch (csr_type & cursorTypeBitMask) {
-            case 0x0802:
-                tdd.currentDevice = QTabletEvent::Stylus;
-                break;
-            case 0x0902:
-                tdd.currentDevice = QTabletEvent::Airbrush;
-                break;
-            case 0x0004:
-                tdd.currentDevice = QTabletEvent::FourDMouse;
-                break;
-            case 0x0006:
-                tdd.currentDevice = QTabletEvent::Puck;
-                break;
-            case 0x0804:
-                tdd.currentDevice = QTabletEvent::RotationStylus;
-                break;
-            default:
-                tdd.currentDevice = QTabletEvent::NoDevice;
-        }
-    }
-    tCursorInfo()->insert(uniqueId, tdd);
-}
-#endif // QT_NO_TABLETEVENT
-
-// Update the "dynamic" information of a cursor device (pen, airbrush, etc).
-// The dynamic information is the information of QTabletDeviceData that can change
-// in time (eraser or pen if a device is turned around).
-#ifndef QT_NO_TABLETEVENT
-
-static void tabletUpdateCursor(QTabletDeviceData &tdd, const UINT currentCursor)
-{
-    switch (currentCursor % 3) { // %3 for dual track
-    case 0:
-        tdd.currentPointerType = QTabletEvent::Cursor;
-        break;
-    case 1:
-        tdd.currentPointerType = QTabletEvent::Pen;
-        break;
-    case 2:
-        tdd.currentPointerType = QTabletEvent::Eraser;
-        break;
-    default:
-        tdd.currentPointerType = QTabletEvent::UnknownPointer;
-    }
-}
-#endif // QT_NO_TABLETEVENT
-
-bool QETWidget::translateTabletEvent(const MSG &msg, PACKET *localPacketBuf,
-                                      int numPackets)
-{
-    Q_UNUSED(msg);
-    POINT ptNew;
-    static DWORD btnNew, btnOld, btnChange;
-    qreal prsNew;
-    ORIENTATION ort;
-    static bool button_pressed = false;
-    int i,
-        tiltX,
-        tiltY;
-    bool sendEvent = false;
-    QEvent::Type t;
-    int z = 0;
-    qreal rotation = 0.0;
-    qreal tangentialPressure;
-    // The tablet can be used in 2 different modes, depending on it settings:
-    // 1) Absolute (pen) mode:
-    //    The coordinates are scaled to the virtual desktop (by default). The user
-    //    can also choose to scale to the monitor or a region of the screen.
-    //    When entering proximity, the tablet driver snaps the mouse pointer to the
-    //    tablet position scaled to that area and keeps it in sync.
-    // 2) Relative (mouse) mode:
-    //    The pen follows the mouse. The constant 'absoluteRange' specifies the
-    //    manhattanLength difference for detecting if a tablet input device is in this mode,
-    //    in which case we snap the position to the mouse position.
-    // It seems there is no way to find out the mode programmatically, the LOGCONTEXT orgX/Y/Ext
-    // area is always the virtual desktop.
-    enum { absoluteRange = 20 };
-
-    // the most common event that we get...
-    t = QEvent::TabletMove;
-    for (i = 0; i < numPackets; i++) {
-        // get the unique ID of the device...
-        btnOld = btnNew;
-        btnNew = localPacketBuf[i].pkButtons;
-        btnChange = btnOld ^ btnNew;
-
-        if (btnNew & btnChange) {
-            button_pressed = true;
-            t = QEvent::TabletPress;
-        }
-        ptNew.x = UINT(localPacketBuf[i].pkX);
-        ptNew.y = UINT(localPacketBuf[i].pkY);
-#ifndef QT_NO_TABLETEVENT
-        z = (currentTabletPointer.currentDevice == QTabletEvent::FourDMouse) ? UINT(localPacketBuf[i].pkZ) : 0;
-#else
-        Q_UNUSED(z);
-#endif // QT_NO_TABLETEVENT
-        prsNew = 0.0;
-        QRect desktopArea = QApplication::desktop()->geometry();
-
-        // This code is to delay the tablet data one cycle to sync with the mouse location.
-        QPointF hiResTabletGlobalPosF = oldHiResTabletGlobalPosF;
-        oldHiResTabletGlobalPosF =
-            currentTabletPointer.scaleCoord(ptNew.x, ptNew.y, desktopArea.left(),
-                                            desktopArea.width(), desktopArea.top(),
-                                            desktopArea.height());
-
-        if (btnNew) {
-#ifndef QT_NO_TABLETEVENT
-            if (currentTabletPointer.currentPointerType == QTabletEvent::Pen || currentTabletPointer.currentPointerType == QTabletEvent::Eraser)
-                prsNew = localPacketBuf[i].pkNormalPressure
-                            / qreal(currentTabletPointer.maxPressure
-                                    - currentTabletPointer.minPressure);
-            else
-#endif // QT_NO_TABLETEVENT
-                prsNew = 0;
-        } else if (button_pressed) {
-            // One button press, should only give one button release
-            t = QEvent::TabletRelease;
-            button_pressed = false;
-        }
-        QPoint globalPos = hiResTabletGlobalPosF.toPoint();
-
-        // Get Mouse Position and compare to tablet info
-        // Positions should be almost the same if we are in absolute
-        //  mode. If they are not, use the mouse location.
-#ifndef Q_WS_WINCE
-        POINT mouseLocationP;
-        if (GetCursorPos(&mouseLocationP)) {
-            const QPoint mouseLocation(mouseLocationP.x, mouseLocationP.y);
-            if ((mouseLocation - globalPos).manhattanLength() > absoluteRange) {
-                globalPos = mouseLocation;
-                hiResTabletGlobalPosF = globalPos;
-            }
-        }
-#endif // !Q_WS_WINCE
-
-        if (t == QEvent::TabletPress)
-        {
-            qt_button_down = QApplication::widgetAt(globalPos);
-        }
-
-        // make sure the tablet event get's sent to the proper widget...
-        QWidget *w = 0;
-
-        if (qt_button_down)
-            w = qt_button_down; // Pass it to the thing that's grabbed it.
-        else
-            w = QApplication::widgetAt(globalPos);
-
-        if (!w)
-            w = this;
-
-        if (t == QEvent::TabletRelease)
-        {
-            if (qt_win_ignoreNextMouseReleaseEvent) {
-                qt_win_ignoreNextMouseReleaseEvent = false;
-                if (qt_button_down && qt_button_down->internalWinId() == autoCaptureWnd) {
-                    releaseAutoCapture();
-                    qt_button_down = 0;
-                }
-            }
-
-        }
-
-        QPoint localPos = w->mapFromGlobal(globalPos);
-#ifndef QT_NO_TABLETEVENT
-        if (currentTabletPointer.currentDevice == QTabletEvent::Airbrush) {
-            tangentialPressure = localPacketBuf[i].pkTangentPressure
-                                / qreal(currentTabletPointer.maxTanPressure
-                                        - currentTabletPointer.minTanPressure);
-        } else {
-            tangentialPressure = 0.0;
-        }
-#else
-        tangentialPressure = 0.0;
-#endif // QT_NO_TABLETEVENT
-
-        if (!qt_tablet_tilt_support) {
-            tiltX = tiltY = 0;
-            rotation = 0.0;
-        } else {
-            ort = localPacketBuf[i].pkOrientation;
-            // convert from azimuth and altitude to x tilt and y tilt
-            // what follows is the optimized version.  Here are the equations
-            // I used to get to this point (in case things change :)
-            // X = sin(azimuth) * cos(altitude)
-            // Y = cos(azimuth) * cos(altitude)
-            // Z = sin(altitude)
-            // X Tilt = arctan(X / Z)
-            // Y Tilt = arctan(Y / Z)
-            double radAzim = (ort.orAzimuth / 10) * (Q_PI / 180);
-            //double radAlt = abs(ort.orAltitude / 10) * (Q_PI / 180);
-            double tanAlt = tan((abs(ort.orAltitude / 10)) * (Q_PI / 180));
-
-            double degX = atan(sin(radAzim) / tanAlt);
-            double degY = atan(cos(radAzim) / tanAlt);
-            tiltX = int(degX * (180 / Q_PI));
-            tiltY = int(-degY * (180 / Q_PI));
-            rotation = ort.orTwist;
-        }
-#ifndef QT_NO_TABLETEVENT
-        QTabletEvent e(t, localPos, globalPos, hiResTabletGlobalPosF, currentTabletPointer.currentDevice,
-                       currentTabletPointer.currentPointerType, prsNew, tiltX, tiltY,
-                       tangentialPressure, rotation, z, QApplication::keyboardModifiers(), currentTabletPointer.llId);
-        sendEvent = QApplication::sendSpontaneousEvent(w, &e);
-#endif // QT_NO_TABLETEVENT
-    }
-    return sendEvent;
-}
-
-extern bool qt_is_gui_used;
-
-
-#ifndef QT_NO_TABLETEVENT
-
-static void initWinTabFunctions()
-{
-#if defined(Q_OS_WINCE)
-    return;
-#else
-    if (!qt_is_gui_used)
-        return;
-
-    QSystemLibrary library(QLatin1String("wintab32"));
-    ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW");
-    ptrWTGet = (PtrWTGet)library.resolve("WTGetW");
-    ptrWTEnable = (PtrWTEnable)library.resolve("WTEnable");
-    ptrWTOverlap = (PtrWTEnable)library.resolve("WTOverlap");
-    ptrWTPacketsGet = (PtrWTPacketsGet)library.resolve("WTPacketsGet");
-#endif // Q_OS_WINCE
-}
-#endif // QT_NO_TABLETEVENT
-
-
-//
-// Paint event translation
-//
-bool QETWidget::translatePaintEvent(const MSG &msg)
-{
-    if (!isWindow() && testAttribute(Qt::WA_NativeWindow))
-        Q_ASSERT(internalWinId());
-
-    Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-    if (!GetUpdateRect(internalWinId(), 0, FALSE)) { // The update bounding rect is invalid
-        d_func()->hd = 0;
-        setAttribute(Qt::WA_PendingUpdate, false);
-        return false;
-    }
-
-    if (msg.message == WM_ERASEBKGND)
-        return true;
-
-    setAttribute(Qt::WA_PendingUpdate, false);
-
-    if (d_func()->isGLWidget) {
-        if (d_func()->usesDoubleBufferedGLContext)
-            InvalidateRect(internalWinId(), 0, false);
-    } else {
-        const QRegion dirtyInBackingStore(qt_dirtyRegion(this));
-        // Make sure the invalidated region contains the region we're about to repaint.
-        // BeginPaint will set the clip to the invalidated region and it is impossible
-        // to enlarge it afterwards (only shrink it). Using GetDCEx is not suffient
-        // as it may return an invalid context (especially on Windows Vista).
-        if (!dirtyInBackingStore.isEmpty())
-            InvalidateRgn(internalWinId(), dirtyInBackingStore.handle(), false);
-    }
-    PAINTSTRUCT ps;
-    d_func()->hd = BeginPaint(internalWinId(), &ps);
-
-    const QRect updateRect(QPoint(ps.rcPaint.left, ps.rcPaint.top),
-                           QPoint(ps.rcPaint.right, ps.rcPaint.bottom));
-
-    // Mapping region from system to qt (32 bit) coordinate system.
-    d_func()->syncBackingStore(updateRect.translated(data->wrect.topLeft()));
-
-    d_func()->hd = 0;
-    EndPaint(internalWinId(), &ps);
-
-    return true;
-}
-
-//
-// Window move and resize (configure) events
-//
-
-bool QETWidget::translateConfigEvent(const MSG &msg)
-{
-    if (!testAttribute(Qt::WA_WState_Created))                // in QWidget::create()
-        return true;
-    if (testAttribute(Qt::WA_WState_ConfigPending))
-        return true;
-    if (testAttribute(Qt::WA_DontShowOnScreen))
-        return true;
-    if (!isWindow())
-        return true;
-    setAttribute(Qt::WA_WState_ConfigPending);                // set config flag
-    QRect cr = geometry();
-    if (msg.message == WM_SIZE) {                // resize event
-        WORD a = LOWORD(msg.lParam);
-        WORD b = HIWORD(msg.lParam);
-        QSize oldSize = size();
-        QSize newSize(a, b);
-#ifdef Q_WS_WINCE_WM
-        if (isFullScreen() && (oldSize.width() == newSize.height()) && (oldSize.height() == newSize.width()))
-            qt_wince_hide_taskbar(internalWinId());
-#endif
-        cr.setSize(newSize);
-        if (msg.wParam != SIZE_MINIMIZED)
-            data->crect = cr;
-        if (isWindow()) {                        // update title/icon text
-            d_func()->createTLExtra();
-            // Capture SIZE_MINIMIZED without preceding WM_SYSCOMMAND
-            // (like Windows+M)
-            if (msg.wParam == SIZE_MINIMIZED && !isMinimized()) {
-#ifndef Q_WS_WINCE
-                const QString title = windowIconText();
-                if (!title.isEmpty())
-                    d_func()->setWindowTitle_helper(title);
-#endif
-                data->window_state |= Qt::WindowMinimized;
-                if (isVisible()) {
-                    QHideEvent e;
-                    QApplication::sendSpontaneousEvent(this, &e);
-                    hideChildren(true);
-                }
-            } else if (msg.wParam != SIZE_MINIMIZED) {
-                bool window_state_changed = false;
-                Qt::WindowStates oldstate = dataPtr()->window_state;
-                if (isMinimized()) {
-#ifndef Q_WS_WINCE
-                    const QString title = windowTitle();
-                    if (!title.isEmpty())
-                        d_func()->setWindowTitle_helper(title);
-#endif
-                    data->window_state &= ~Qt::WindowMinimized;
-                    showChildren(true);
-                    QShowEvent e;
-                    QApplication::sendSpontaneousEvent(this, &e);
-                // Capture SIZE_MAXIMIZED and SIZE_RESTORED without preceding WM_SYSCOMMAND
-                // (Aero Snap on Win7)
-                } else if (msg.wParam == SIZE_MAXIMIZED && !isMaximized()) {
-                    data->window_state |= Qt::WindowMaximized;
-                    window_state_changed = true;
-                } else if (msg.wParam == SIZE_RESTORED && isMaximized()) {
-                    data->window_state &= ~(Qt::WindowMaximized);
-                    window_state_changed = true;
-                }
-                if (window_state_changed) {
-                    QWindowStateChangeEvent e(oldstate);
-                    QApplication::sendSpontaneousEvent(this, &e);
-                }
-            }
-        }
-        if (msg.wParam != SIZE_MINIMIZED && oldSize != newSize) {
-            if (isVisible()) {
-                QTLWExtra *tlwExtra = maybeTopData();
-                static bool slowResize = qgetenv("QT_SLOW_TOPLEVEL_RESIZE").toInt();
-                const bool hasStaticContents = tlwExtra && tlwExtra->backingStore
-                                               && tlwExtra->backingStore->hasStaticContents();
-                // If we have a backing store with static contents, we have to disable the top-level
-                // resize optimization in order to get invalidated regions for resized widgets.
-                // The optimization discards all invalidateBuffer() calls since we're going to
-                // repaint everything anyways, but that's not the case with static contents.
-                if (!slowResize && tlwExtra && !hasStaticContents)
-                    tlwExtra->inTopLevelResize = true;
-                QResizeEvent e(newSize, oldSize);
-                QApplication::sendSpontaneousEvent(this, &e);
-                if (d_func()->paintOnScreen()) {
-                    QRegion updateRegion(rect());
-                    if (testAttribute(Qt::WA_StaticContents))
-                        updateRegion -= QRect(0, 0, oldSize.width(), oldSize.height());
-                    d_func()->syncBackingStore(updateRegion);
-                } else {
-                    d_func()->syncBackingStore();
-                }
-                if (!slowResize && tlwExtra)
-                    tlwExtra->inTopLevelResize = false;
-            } else {
-                QResizeEvent *e = new QResizeEvent(newSize, oldSize);
-                QApplication::postEvent(this, e);
-            }
-        }
-    } else if (msg.message == WM_MOVE) {        // move event
-        int a = (int) (short) LOWORD(msg.lParam);
-        int b = (int) (short) HIWORD(msg.lParam);
-        QPoint oldPos = geometry().topLeft();
-        QPoint newCPos(a, b);
-        // Ignore silly Windows move event to wild pos after iconify.
-#if !defined(Q_WS_WINCE)
-        if (!IsIconic(internalWinId()) && newCPos != oldPos) {
-#endif
-            cr.moveTopLeft(newCPos);
-            data->crect = cr;
-            if (isVisible()) {
-                QMoveEvent e(newCPos, oldPos);  // cpos (client position)
-                QApplication::sendSpontaneousEvent(this, &e);
-            } else {
-                QMoveEvent * e = new QMoveEvent(newCPos, oldPos);
-                QApplication::postEvent(this, e);
-            }
-#if !defined(Q_WS_WINCE)
-        }
-#endif
-    }
-    setAttribute(Qt::WA_WState_ConfigPending, false);                // clear config flag
-    return true;
-}
-
-
-//
-// Close window event translation.
-//
-// This class is a friend of QApplication because it needs to emit the
-// lastWindowClosed() signal when the last top level widget is closed.
-//
-
-bool QETWidget::translateCloseEvent(const MSG &)
-{
-    return d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
-}
-
-#ifndef QT_NO_GESTURES
-bool QETWidget::translateGestureEvent(const MSG &, const GESTUREINFO &gi)
-{
-    const QPoint widgetPos = QPoint(gi.ptsLocation.x, gi.ptsLocation.y);
-    QWidget *alienWidget = !internalWinId() ? this : childAt(widgetPos);
-    if (alienWidget && alienWidget->internalWinId())
-        alienWidget = 0;
-    QWidget *widget = alienWidget ? alienWidget : this;
-
-    QNativeGestureEvent event;
-    event.sequenceId = gi.dwSequenceID;
-    event.position = QPoint(gi.ptsLocation.x, gi.ptsLocation.y);
-    event.argument = gi.ullArguments;
-
-    switch (gi.dwID) {
-    case GID_BEGIN:
-        event.gestureType = QNativeGestureEvent::GestureBegin;
-        break;
-    case GID_END:
-        event.gestureType = QNativeGestureEvent::GestureEnd;
-        break;
-    case GID_ZOOM:
-        event.gestureType = QNativeGestureEvent::Zoom;
-        break;
-    case GID_PAN:
-        event.gestureType = QNativeGestureEvent::Pan;
-        break;
-    case GID_ROTATE:
-        event.gestureType = QNativeGestureEvent::Rotate;
-        break;
-    case GID_TWOFINGERTAP:
-    case GID_ROLLOVER:
-    default:
-        break;
-    }
-    if (event.gestureType != QNativeGestureEvent::None)
-        qt_sendSpontaneousEvent(widget, &event);
-    return true;
-}
-#endif // QT_NO_GESTURES
-
-void  QApplication::setCursorFlashTime(int msecs)
-{
-    SetCaretBlinkTime(msecs / 2);
-    QApplicationPrivate::cursor_flash_time = msecs;
-}
-
-
-int QApplication::cursorFlashTime()
-{
-    int blink = (int)GetCaretBlinkTime();
-    if (!blink)
-        return QApplicationPrivate::cursor_flash_time;
-    if (blink > 0)
-        return 2*blink;
-    return 0;
-}
-
-
-void QApplication::setDoubleClickInterval(int ms)
-{
-#ifndef Q_WS_WINCE
-    SetDoubleClickTime(ms);
-#endif
-    QApplicationPrivate::mouse_double_click_time = ms;
-}
-
-int QApplication::doubleClickInterval()
-{
-    int ms = GetDoubleClickTime();
-    if (ms != 0)
-        return ms;
-    return QApplicationPrivate::mouse_double_click_time;
-}
-
-
-void QApplication::setKeyboardInputInterval(int ms)
-{
-    QApplicationPrivate::keyboard_input_time = ms;
-}
-
-int QApplication::keyboardInputInterval()
-{
-    // FIXME: get from the system
-    return QApplicationPrivate::keyboard_input_time;
-}
-
-#ifndef QT_NO_WHEELEVENT
-void QApplication::setWheelScrollLines(int n)
-{
-#ifdef SPI_SETWHEELSCROLLLINES
-    if (n < 0)
-        n = 0;
-    SystemParametersInfo(SPI_SETWHEELSCROLLLINES, (uint)n, 0, 0);
-#else
-    QApplicationPrivate::wheel_scroll_lines = n;
-#endif
-}
-
-int QApplication::wheelScrollLines()
-{
-#ifdef SPI_GETWHEELSCROLLLINES
-    uint i = 3;
-    SystemParametersInfo(SPI_GETWHEELSCROLLLINES, sizeof(uint), &i, 0);
-    if (i > INT_MAX)
-        i = INT_MAX;
-    return i;
-#else
-    return QApplicationPrivate::wheel_scroll_lines;
-#endif
-}
-#endif //QT_NO_WHEELEVENT
-
-static bool effect_override = false;
-
-void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
-{
-    effect_override = true;
-    switch (effect) {
-    case Qt::UI_AnimateMenu:
-        QApplicationPrivate::animate_menu = enable;
-        break;
-    case Qt::UI_FadeMenu:
-        QApplicationPrivate::fade_menu = enable;
-        break;
-    case Qt::UI_AnimateCombo:
-        QApplicationPrivate::animate_combo = enable;
-        break;
-    case Qt::UI_AnimateTooltip:
-        QApplicationPrivate::animate_tooltip = enable;
-        break;
-    case Qt::UI_FadeTooltip:
-        QApplicationPrivate::fade_tooltip = enable;
-        break;
-    case Qt::UI_AnimateToolBox:
-        QApplicationPrivate::animate_toolbox = enable;
-        break;
-    default:
-        QApplicationPrivate::animate_ui = enable;
-        break;
-    }
-}
-
-bool QApplication::isEffectEnabled(Qt::UIEffect effect)
-{
-    if (QColormap::instance().depth() < 16)
-        return false;
-
-    if (!effect_override && desktopSettingsAware()) {
-        // we know that they can be used when we are here
-        BOOL enabled = false;
-        UINT api;
-        switch (effect) {
-        case Qt::UI_AnimateMenu:
-            api = SPI_GETMENUANIMATION;
-            break;
-        case Qt::UI_FadeMenu:
-            api = SPI_GETMENUFADE;
-            break;
-        case Qt::UI_AnimateCombo:
-            api = SPI_GETCOMBOBOXANIMATION;
-            break;
-        case Qt::UI_AnimateTooltip:
-            api = SPI_GETTOOLTIPANIMATION;
-            break;
-        case Qt::UI_FadeTooltip:
-            api = SPI_GETTOOLTIPFADE;
-            break;
-        default:
-            api = SPI_GETUIEFFECTS;
-            break;
-        }
-        SystemParametersInfo(api, 0, &enabled, 0);
-        return enabled;
-    }
-
-    switch(effect) {
-    case Qt::UI_AnimateMenu:
-        return QApplicationPrivate::animate_menu;
-    case Qt::UI_FadeMenu:
-        return QApplicationPrivate::fade_menu;
-    case Qt::UI_AnimateCombo:
-        return QApplicationPrivate::animate_combo;
-    case Qt::UI_AnimateTooltip:
-        return QApplicationPrivate::animate_tooltip;
-    case Qt::UI_FadeTooltip:
-        return QApplicationPrivate::fade_tooltip;
-    case Qt::UI_AnimateToolBox:
-        return QApplicationPrivate::animate_toolbox;
-    default:
-        return QApplicationPrivate::animate_ui;
-    }
-}
-
-#ifndef QT_NO_SESSIONMANAGER
-
-bool QSessionManager::allowsInteraction()
-{
-    sm_blockUserInput = false;
-    return true;
-}
-
-bool QSessionManager::allowsErrorInteraction()
-{
-    sm_blockUserInput = false;
-    return true;
-}
-
-void QSessionManager::release()
-{
-    if (sm_smActive)
-        sm_blockUserInput = true;
-}
-
-void QSessionManager::cancel()
-{
-    sm_cancel = true;
-}
-
-#endif //QT_NO_SESSIONMANAGER
-
-
-bool QApplicationPrivate::HasTouchSupport = false;
-PtrRegisterTouchWindow QApplicationPrivate::RegisterTouchWindow = 0;
-PtrGetTouchInputInfo QApplicationPrivate::GetTouchInputInfo = 0;
-PtrCloseTouchInputHandle QApplicationPrivate::CloseTouchInputHandle = 0;
-
-void QApplicationPrivate::initializeMultitouch_sys()
-{
-    if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS7
-        && (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based)) {
-        static const int QT_SM_DIGITIZER = 94;
-        int value = GetSystemMetrics(QT_SM_DIGITIZER);
-        static const int QT_NID_INTEGRATED_TOUCH = 0x01;
-        static const int QT_NID_EXTERNAL_TOUCH   = 0x02;
-        static const int QT_NID_MULTI_INPUT      = 0x40;
-        QApplicationPrivate::HasTouchSupport =
-                value & (QT_NID_INTEGRATED_TOUCH | QT_NID_EXTERNAL_TOUCH | QT_NID_MULTI_INPUT);
-    }
-
-    QSystemLibrary library(QLatin1String("user32"));
-    // MinGW (g++ 3.4.5) accepts only C casts.
-    RegisterTouchWindow = (PtrRegisterTouchWindow)(library.resolve("RegisterTouchWindow"));
-    GetTouchInputInfo = (PtrGetTouchInputInfo)(library.resolve("GetTouchInputInfo"));
-    CloseTouchInputHandle = (PtrCloseTouchInputHandle)(library.resolve("CloseTouchInputHandle"));
-
-    touchInputIDToTouchPointID.clear();
-}
-
-void QApplicationPrivate::cleanupMultitouch_sys()
-{
-    touchInputIDToTouchPointID.clear();
-}
-
-bool QApplicationPrivate::translateTouchEvent(const MSG &msg)
-{
-    QWidget *widgetForHwnd = QWidget::find(msg.hwnd);
-    if (!widgetForHwnd)
-        return false;
-
-    QRect screenGeometry = QApplication::desktop()->screenGeometry(widgetForHwnd);
-
-    QList<QTouchEvent::TouchPoint> touchPoints;
-
-    QVector<TOUCHINPUT> winTouchInputs(msg.wParam);
-    memset(winTouchInputs.data(), 0, sizeof(TOUCHINPUT) * winTouchInputs.count());
-    Qt::TouchPointStates allStates = 0;
-    QApplicationPrivate::GetTouchInputInfo((HANDLE) msg.lParam, msg.wParam, winTouchInputs.data(), sizeof(TOUCHINPUT));
-    for (int i = 0; i < winTouchInputs.count(); ++i) {
-        const TOUCHINPUT &touchInput = winTouchInputs.at(i);
-
-        int touchPointID = touchInputIDToTouchPointID.value(touchInput.dwID, -1);
-        if (touchPointID == -1) {
-            touchPointID = touchInputIDToTouchPointID.count();
-            touchInputIDToTouchPointID.insert(touchInput.dwID, touchPointID);
-        }
-
-        QTouchEvent::TouchPoint touchPoint(touchPointID);
-
-        // update state
-        QPointF screenPos(qreal(touchInput.x) / qreal(100.), qreal(touchInput.y) / qreal(100.));
-        QRectF screenRect;
-        if (touchInput.dwMask & TOUCHINPUTMASKF_CONTACTAREA)
-            screenRect.setSize(QSizeF(qreal(touchInput.cxContact) / qreal(100.),
-                                      qreal(touchInput.cyContact) / qreal(100.)));
-        screenRect.moveCenter(screenPos);
-
-        Qt::TouchPointStates state;
-        if (touchInput.dwFlags & TOUCHEVENTF_DOWN) {
-            state = Qt::TouchPointPressed;
-        } else if (touchInput.dwFlags & TOUCHEVENTF_UP) {
-            state = Qt::TouchPointReleased;
-        } else {
-            state = (screenPos == touchPoint.screenPos()
-                     ? Qt::TouchPointStationary
-                     : Qt::TouchPointMoved);
-        }
-        if (touchInput.dwFlags & TOUCHEVENTF_PRIMARY)
-            state |= Qt::TouchPointPrimary;
-        touchPoint.setState(state);
-        touchPoint.setScreenRect(screenRect);
-        touchPoint.setNormalizedPos(QPointF(screenPos.x() / screenGeometry.width(),
-                                            screenPos.y() / screenGeometry.height()));
-
-        allStates |= state;
-
-        touchPoints.append(touchPoint);
-    }
-    QApplicationPrivate::CloseTouchInputHandle((HANDLE) msg.lParam);
-
-    if ((allStates & Qt::TouchPointStateMask) == Qt::TouchPointReleased) {
-        // all touch points released, forget the ids we've seen, they may not be reused
-        touchInputIDToTouchPointID.clear();
-    }
-
-    translateRawTouchEvent(widgetForHwnd, QTouchEvent::TouchScreen, touchPoints);
-    return true;
-}
-
-#include "moc_qsessionmanager.h"
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qclipboard_mac.cpp b/src/gui/kernel/qclipboard_mac.cpp
deleted file mode 100644 (file)
index 787894e..0000000
+++ /dev/null
@@ -1,629 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qclipboard.h"
-#include "qapplication.h"
-#include "qbitmap.h"
-#include "qdatetime.h"
-#include "qdebug.h"
-#include "qapplication_p.h"
-#include <qt_mac_p.h>
-#include "qevent.h"
-#include "qurl.h"
-#include <stdlib.h>
-#include <string.h>
-#include "qt_cocoa_helpers_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-/*****************************************************************************
-  QClipboard debug facilities
- *****************************************************************************/
-//#define DEBUG_PASTEBOARD
-
-#ifndef QT_NO_CLIPBOARD
-
-/*****************************************************************************
-  QClipboard member functions for mac.
- *****************************************************************************/
-
-static QMacPasteboard *qt_mac_pasteboards[2] = {0, 0};
-
-static inline QMacPasteboard *qt_mac_pasteboard(QClipboard::Mode mode)
-{
-    Q_ASSERT(mode == QClipboard::Clipboard || mode == QClipboard::FindBuffer);
-    if (mode == QClipboard::Clipboard)
-        return qt_mac_pasteboards[0];
-    else
-        return qt_mac_pasteboards[1];
-}
-
-static void qt_mac_cleanupPasteboard() {
-    delete qt_mac_pasteboards[0];
-    delete qt_mac_pasteboards[1];
-    qt_mac_pasteboards[0] = 0;
-    qt_mac_pasteboards[1] = 0;
-}
-
-static bool qt_mac_updateScrap(QClipboard::Mode mode)
-{
-    if(!qt_mac_pasteboards[0]) {
-        qt_mac_pasteboards[0] = new QMacPasteboard(kPasteboardClipboard, QMacPasteboardMime::MIME_CLIP);
-        qt_mac_pasteboards[1] = new QMacPasteboard(kPasteboardFind, QMacPasteboardMime::MIME_CLIP);
-        qAddPostRoutine(qt_mac_cleanupPasteboard);
-        return true;
-    }
-    return qt_mac_pasteboard(mode)->sync();
-}
-
-void QClipboard::clear(Mode mode)
-{
-    if (!supportsMode(mode))
-        return;
-    qt_mac_updateScrap(mode);
-    qt_mac_pasteboard(mode)->clear();
-    setMimeData(0, mode);
-}
-
-void QClipboard::connectNotify(const char *signal)
-{
-    Q_UNUSED(signal);
-}
-
-bool QClipboard::event(QEvent *e)
-{
-    if(e->type() != QEvent::Clipboard)
-        return QObject::event(e);
-
-    if (qt_mac_updateScrap(QClipboard::Clipboard)) {
-        emitChanged(QClipboard::Clipboard);
-    }
-
-    if (qt_mac_updateScrap(QClipboard::FindBuffer)) {
-        emitChanged(QClipboard::FindBuffer);
-    }
-
-    return QObject::event(e);
-}
-
-const QMimeData *QClipboard::mimeData(Mode mode) const
-{
-    if (!supportsMode(mode))
-        return 0;
-    qt_mac_updateScrap(mode);
-    return qt_mac_pasteboard(mode)->mimeData();
-}
-
-void QClipboard::setMimeData(QMimeData *src, Mode mode)
-{
-    if (!supportsMode(mode))
-        return;
-    qt_mac_updateScrap(mode);
-    qt_mac_pasteboard(mode)->setMimeData(src);
-    emitChanged(mode);
-}
-
-bool QClipboard::supportsMode(Mode mode) const
-{
-    return (mode == Clipboard || mode == FindBuffer);
-}
-
-bool QClipboard::ownsMode(Mode mode) const
-{
-    Q_UNUSED(mode);
-    return false;
-}
-
-#endif // QT_NO_CLIPBOARD
-
-/*****************************************************************************
-   QMacPasteboard code
-*****************************************************************************/
-
-QMacPasteboard::QMacPasteboard(PasteboardRef p, uchar mt)
-{
-    mac_mime_source = false;
-    mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
-    paste = p;
-    CFRetain(paste);
-}
-
-QMacPasteboard::QMacPasteboard(uchar mt)
-{
-    mac_mime_source = false;
-    mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
-    paste = 0;
-    OSStatus err = PasteboardCreate(0, &paste);
-    if(err == noErr) {
-        PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
-    } else {
-        qDebug("PasteBoard: Error creating pasteboard: [%d]", (int)err);
-    }
-}
-
-QMacPasteboard::QMacPasteboard(CFStringRef name, uchar mt)
-{
-    mac_mime_source = false;
-    mime_type = mt ? mt : uchar(QMacPasteboardMime::MIME_ALL);
-    paste = 0;
-    OSStatus err = PasteboardCreate(name, &paste);
-    if(err == noErr) {
-        PasteboardSetPromiseKeeper(paste, promiseKeeper, this);
-    } else {
-        qDebug("PasteBoard: Error creating pasteboard: %s [%d]", QCFString::toQString(name).toLatin1().constData(), (int)err);
-    }
-}
-
-QMacPasteboard::~QMacPasteboard()
-{
-    // commit all promises for paste after exit close
-    for (int i = 0; i < promises.count(); ++i) {
-        const Promise &promise = promises.at(i);
-        QCFString flavor = QCFString(promise.convertor->flavorFor(promise.mime));
-        promiseKeeper(paste, (PasteboardItemID)promise.itemId, flavor, this);
-    }
-
-    if(paste)
-        CFRelease(paste);
-}
-
-PasteboardRef
-QMacPasteboard::pasteBoard() const
-{
-    return paste;
-}
-
-OSStatus QMacPasteboard::promiseKeeper(PasteboardRef paste, PasteboardItemID id, CFStringRef flavor, void *_qpaste)
-{
-    QMacPasteboard *qpaste = (QMacPasteboard*)_qpaste;
-    const long promise_id = (long)id;
-
-    // Find the kept promise
-    const QString flavorAsQString = QCFString::toQString(flavor);
-    QMacPasteboard::Promise promise;
-    for (int i = 0; i < qpaste->promises.size(); i++){
-        QMacPasteboard::Promise tmp = qpaste->promises[i];
-        if (tmp.itemId == promise_id && tmp.convertor->canConvert(tmp.mime, flavorAsQString)){
-            promise = tmp;
-            break;
-        }
-    }
-    
-    if (!promise.itemId && flavorAsQString == QLatin1String("com.trolltech.qt.MimeTypeName")) {
-        // we have promised this data, but wont be able to convert, so return null data.
-        // This helps in making the application/x-qt-mime-type-name hidden from normal use.
-        QByteArray ba;
-        QCFType<CFDataRef> data = CFDataCreate(0, (UInt8*)ba.constData(), ba.size());
-        PasteboardPutItemFlavor(paste, id, flavor, data, kPasteboardFlavorNoFlags);
-        return noErr;
-    }
-    
-    if (!promise.itemId) {
-        // There was no promise that could deliver data for the
-        // given id and flavor. This should not happend.
-        qDebug("Pasteboard: %d: Request for %ld, %s, but no promise found!", __LINE__, promise_id, qPrintable(flavorAsQString));
-        return cantGetFlavorErr;
-    }
-
-#ifdef DEBUG_PASTEBOARD
-    qDebug("PasteBoard: Calling in promise for %s[%ld] [%s] (%s) [%d]", qPrintable(promise.mime), promise_id,
-           qPrintable(flavorAsQString), qPrintable(promise.convertor->convertorName()), promise.offset);
-#endif
-
-    QList<QByteArray> md = promise.convertor->convertFromMime(promise.mime, promise.data, flavorAsQString);
-    if (md.size() <= promise.offset)
-        return cantGetFlavorErr;
-    const QByteArray &ba = md[promise.offset];
-    QCFType<CFDataRef> data = CFDataCreate(0, (UInt8*)ba.constData(), ba.size());
-    PasteboardPutItemFlavor(paste, id, flavor, data, kPasteboardFlavorNoFlags);
-    return noErr;
-}
-
-bool
-QMacPasteboard::hasOSType(int c_flavor) const
-{
-    if (!paste)
-        return false;
-
-    sync();
-
-    ItemCount cnt = 0;
-    if(PasteboardGetItemCount(paste, &cnt) || !cnt)
-        return false;
-
-#ifdef DEBUG_PASTEBOARD
-    qDebug("PasteBoard: hasOSType [%c%c%c%c]", (c_flavor>>24)&0xFF, (c_flavor>>16)&0xFF,
-           (c_flavor>>8)&0xFF, (c_flavor>>0)&0xFF);
-#endif
-    for(uint index = 1; index <= cnt; ++index) {
-
-        PasteboardItemID id;
-        if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
-            return false;
-
-        QCFType<CFArrayRef> types;
-        if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
-            return false;
-
-        const int type_count = CFArrayGetCount(types);
-        for(int i = 0; i < type_count; ++i) {
-            CFStringRef flavor = (CFStringRef)CFArrayGetValueAtIndex(types, i);
-            const int os_flavor = UTGetOSTypeFromString(UTTypeCopyPreferredTagWithClass(flavor, kUTTagClassOSType));
-            if(os_flavor == c_flavor) {
-#ifdef DEBUG_PASTEBOARD
-                qDebug("  - Found!");
-#endif
-                return true;
-            }
-        }
-    }
-#ifdef DEBUG_PASTEBOARD
-    qDebug("  - NotFound!");
-#endif
-    return false;
-}
-
-bool
-QMacPasteboard::hasFlavor(QString c_flavor) const
-{
-    if (!paste)
-        return false;
-
-    sync();
-
-    ItemCount cnt = 0;
-    if(PasteboardGetItemCount(paste, &cnt) || !cnt)
-        return false;
-
-#ifdef DEBUG_PASTEBOARD
-    qDebug("PasteBoard: hasFlavor [%s]", qPrintable(c_flavor));
-#endif
-    for(uint index = 1; index <= cnt; ++index) {
-
-        PasteboardItemID id;
-        if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
-            return false;
-
-        PasteboardFlavorFlags flags;
-        if(PasteboardGetItemFlavorFlags(paste, id, QCFString(c_flavor), &flags) == noErr) {
-#ifdef DEBUG_PASTEBOARD
-            qDebug("  - Found!");
-#endif
-            return true;
-        }
-    }
-#ifdef DEBUG_PASTEBOARD
-    qDebug("  - NotFound!");
-#endif
-    return false;
-}
-
-class QMacPasteboardMimeSource : public QMimeData {
-    const QMacPasteboard *paste;
-public:
-    QMacPasteboardMimeSource(const QMacPasteboard *p) : QMimeData(), paste(p) { }
-    ~QMacPasteboardMimeSource() { }
-    virtual QStringList formats() const { return paste->formats(); }
-    virtual QVariant retrieveData(const QString &format, QVariant::Type type) const { return paste->retrieveData(format, type); }
-};
-
-QMimeData
-*QMacPasteboard::mimeData() const
-{
-    if(!mime) {
-        mac_mime_source = true;
-        mime = new QMacPasteboardMimeSource(this);
-
-    }
-    return mime;
-}
-
-class QMacMimeData : public QMimeData
-{
-public:
-    QVariant variantData(const QString &mime) { return retrieveData(mime, QVariant::Invalid); }
-private:
-    QMacMimeData();
-};
-
-void
-QMacPasteboard::setMimeData(QMimeData *mime_src)
-{
-    if (!paste)
-        return;
-
-    if (mime == mime_src || (!mime_src && mime && mac_mime_source))
-        return;
-    mac_mime_source = false;
-    delete mime;
-    mime = mime_src;
-
-    QList<QMacPasteboardMime*> availableConverters = QMacPasteboardMime::all(mime_type);
-    if (mime != 0) {
-        clear_helper();
-        QStringList formats = mime_src->formats();
-
-#ifdef QT_MAC_USE_COCOA
-        // QMimeData sub classes reimplementing the formats() might not expose the
-        // temporary "application/x-qt-mime-type-name" mimetype. So check the existence
-        // of this mime type while doing drag and drop.
-        QString dummyMimeType(QLatin1String("application/x-qt-mime-type-name"));
-        if (!formats.contains(dummyMimeType)) {
-            QByteArray dummyType = mime_src->data(dummyMimeType);
-            if (!dummyType.isEmpty()) {
-                formats.append(dummyMimeType);
-            }
-        }
-#endif
-        for(int f = 0; f < formats.size(); ++f) {
-            QString mimeType = formats.at(f);
-            for (QList<QMacPasteboardMime *>::Iterator it = availableConverters.begin(); it != availableConverters.end(); ++it) {
-                QMacPasteboardMime *c = (*it);
-                QString flavor(c->flavorFor(mimeType));
-                if(!flavor.isEmpty()) {
-                    QVariant mimeData = static_cast<QMacMimeData*>(mime_src)->variantData(mimeType);
-#if 0
-                    //### Grrr, why didn't I put in a virtual int QMacPasteboardMime::count()? --Sam
-                    const int numItems = c->convertFromMime(mimeType, mimeData, flavor).size();
-#else
-                    int numItems = 1; //this is a hack but it is much faster than allowing conversion above
-                    if(c->convertorName() == QLatin1String("FileURL"))
-                        numItems = mime_src->urls().count();
-#endif
-                    for(int item = 0; item < numItems; ++item) {
-                        const int itemID = item+1; //id starts at 1
-                        promises.append(QMacPasteboard::Promise(itemID, c, mimeType, mimeData, item));
-                        PasteboardPutItemFlavor(paste, (PasteboardItemID)itemID, QCFString(flavor), 0, kPasteboardFlavorNoFlags);
-#ifdef DEBUG_PASTEBOARD
-                        qDebug(" -  adding %d %s [%s] <%s> [%d]",
-                               itemID, qPrintable(mimeType), qPrintable(flavor), qPrintable(c->convertorName()), item);
-#endif
-                    }
-                }
-            }
-        }
-    }
-}
-
-QStringList
-QMacPasteboard::formats() const
-{
-    if (!paste)
-        return QStringList();
-
-    sync();
-
-    QStringList ret;
-    ItemCount cnt = 0;
-    if(PasteboardGetItemCount(paste, &cnt) || !cnt)
-        return ret;
-
-#ifdef DEBUG_PASTEBOARD
-    qDebug("PasteBoard: Formats [%d]", (int)cnt);
-#endif
-    for(uint index = 1; index <= cnt; ++index) {
-
-        PasteboardItemID id;
-        if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
-            continue;
-
-        QCFType<CFArrayRef> types;
-        if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
-            continue;
-
-        const int type_count = CFArrayGetCount(types);
-        for(int i = 0; i < type_count; ++i) {
-            const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
-#ifdef DEBUG_PASTEBOARD
-            qDebug(" -%s", qPrintable(QString(flavor)));
-#endif
-            QString mimeType = QMacPasteboardMime::flavorToMime(mime_type, flavor);
-            if(!mimeType.isEmpty() && !ret.contains(mimeType)) {
-#ifdef DEBUG_PASTEBOARD
-                qDebug("   -<%d> %s [%s]", ret.size(), qPrintable(mimeType), qPrintable(QString(flavor)));
-#endif
-                ret << mimeType;
-            }
-        }
-    }
-    return ret;
-}
-
-bool
-QMacPasteboard::hasFormat(const QString &format) const
-{
-    if (!paste)
-        return false;
-
-    sync();
-
-    ItemCount cnt = 0;
-    if(PasteboardGetItemCount(paste, &cnt) || !cnt)
-        return false;
-
-#ifdef DEBUG_PASTEBOARD
-    qDebug("PasteBoard: hasFormat [%s]", qPrintable(format));
-#endif
-    for(uint index = 1; index <= cnt; ++index) {
-
-        PasteboardItemID id;
-        if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
-            continue;
-
-        QCFType<CFArrayRef> types;
-        if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
-            continue;
-
-        const int type_count = CFArrayGetCount(types);
-        for(int i = 0; i < type_count; ++i) {
-            const QString flavor = QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(types, i));
-#ifdef DEBUG_PASTEBOARD
-            qDebug(" -%s [0x%x]", qPrintable(QString(flavor)), mime_type);
-#endif
-            QString mimeType = QMacPasteboardMime::flavorToMime(mime_type, flavor);
-#ifdef DEBUG_PASTEBOARD
-            if(!mimeType.isEmpty())
-                qDebug("   - %s", qPrintable(mimeType));
-#endif
-            if(mimeType == format)
-                return true;
-        }
-    }
-    return false;
-}
-
-QVariant
-QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const
-{
-    if (!paste)
-        return QVariant();
-
-    sync();
-
-    ItemCount cnt = 0;
-    if(PasteboardGetItemCount(paste, &cnt) || !cnt)
-        return QByteArray();
-
-#ifdef DEBUG_PASTEBOARD
-    qDebug("Pasteboard: retrieveData [%s]", qPrintable(format));
-#endif
-    const QList<QMacPasteboardMime *> mimes = QMacPasteboardMime::all(mime_type);
-    for(int mime = 0; mime < mimes.size(); ++mime) {
-        QMacPasteboardMime *c = mimes.at(mime);
-        QString c_flavor = c->flavorFor(format);
-        if(!c_flavor.isEmpty()) {
-            // Handle text/plain a little differently. Try handling Unicode first.
-            bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text")
-                                  || c_flavor == QLatin1String("public.utf8-plain-text"));
-            if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) {
-                // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped
-                // correctly (as '\n') in this data. The 'public.utf16-plain-text' type
-                // usually maps newlines to '\r' instead.
-                QString str = qt_mac_get_pasteboardString(paste);
-                if (!str.isEmpty())
-                    return str;
-            }
-            if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text")))
-                c_flavor = QLatin1String("public.utf16-plain-text");
-
-            QVariant ret;
-            QList<QByteArray> retList;
-            for(uint index = 1; index <= cnt; ++index) {
-                PasteboardItemID id;
-                if(PasteboardGetItemIdentifier(paste, index, &id) != noErr)
-                    continue;
-
-                QCFType<CFArrayRef> types;
-                if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr)
-                    continue;
-
-                const int type_count = CFArrayGetCount(types);
-                for(int i = 0; i < type_count; ++i) {
-                    CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i));
-                    if(c_flavor == QCFString::toQString(flavor)) {
-                        QCFType<CFDataRef> macBuffer;
-                        if(PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) {
-                            QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer));
-                            if(!buffer.isEmpty()) {
-#ifdef DEBUG_PASTEBOARD
-                                qDebug("  - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
-#endif
-                                buffer.detach(); //detach since we release the macBuffer
-                                retList.append(buffer);
-                                break; //skip to next element
-                            }
-                        }
-                    } else {
-#ifdef DEBUG_PASTEBOARD
-                        qDebug("  - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName()));
-#endif
-                    }
-                }
-            }
-
-            if (!retList.isEmpty()) {
-                ret = c->convertToMime(format, retList, c_flavor);
-                return ret;
-            }
-        }
-    }
-    return QVariant();
-}
-
-void QMacPasteboard::clear_helper()
-{
-    if (paste)
-        PasteboardClear(paste);
-    promises.clear();
-}
-
-void
-QMacPasteboard::clear()
-{
-#ifdef DEBUG_PASTEBOARD
-    qDebug("PasteBoard: clear!");
-#endif
-    clear_helper();
-}
-
-bool
-QMacPasteboard::sync() const
-{
-    if (!paste)
-        return false;
-    const bool fromGlobal = PasteboardSynchronize(paste) & kPasteboardModified;
-    
-    if (fromGlobal)
-        const_cast<QMacPasteboard *>(this)->setMimeData(0);
-
-#ifdef DEBUG_PASTEBOARD
-    if(fromGlobal)
-        qDebug("Pasteboard: Synchronize!");
-#endif
-    return fromGlobal;
-}
-
-
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qclipboard_win.cpp b/src/gui/kernel/qclipboard_win.cpp
deleted file mode 100644 (file)
index 3a20009..0000000
+++ /dev/null
@@ -1,416 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qclipboard.h"
-
-#ifndef QT_NO_CLIPBOARD
-
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include "qeventloop.h"
-#include "qwidget.h"
-#include "qevent.h"
-#include "qmime.h"
-#include "qt_windows.h"
-#include "qdnd_p.h"
-#include <qwidget_p.h>
-#include <qsystemlibrary_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#if defined(Q_OS_WINCE)
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "qguifunctions_wince.h"
-QT_END_INCLUDE_NAMESPACE
-
-HRESULT QtCeGetClipboard(IDataObject** obj);
-HRESULT QtCeSetClipboard(IDataObject* obj);
-void QtCeFlushClipboard();
-
-#define OleGetClipboard QtCeGetClipboard
-#define OleSetClipboard QtCeSetClipboard
-#define OleFlushClipboard QtCeFlushClipboard
-
-#endif
-
-typedef BOOL (WINAPI *PtrIsHungAppWindow)(HWND);
-
-static PtrIsHungAppWindow ptrIsHungAppWindow = 0;
-
-class QClipboardWatcher : public QInternalMimeData {
-public:
-    QClipboardWatcher()
-        : QInternalMimeData()
-    {
-    }
-
-    bool hasFormat_sys(const QString &mimetype) const;
-    QStringList formats_sys() const;
-    QVariant retrieveData_sys(const QString &mimetype, QVariant::Type preferredType) const;
-};
-
-
-bool QClipboardWatcher::hasFormat_sys(const QString &mime) const
-{
-    IDataObject * pDataObj = 0;
-
-    if (OleGetClipboard(&pDataObj) != S_OK && !pDataObj) // Sanity
-        return false;
-
-    bool has = QWindowsMime::converterToMime(mime, pDataObj) != 0;
-
-    pDataObj->Release();
-
-    return has;
-}
-
-QStringList QClipboardWatcher::formats_sys() const
-{
-    QStringList fmts;
-    IDataObject * pDataObj = 0;
-
-    if (OleGetClipboard(&pDataObj) != S_OK && !pDataObj) // Sanity
-        return QStringList();
-
-    fmts = QWindowsMime::allMimesForFormats(pDataObj);
-
-    pDataObj->Release();
-
-    return fmts;
-}
-
-QVariant QClipboardWatcher::retrieveData_sys(const QString &mimeType, QVariant::Type type) const
-{
-    QVariant result;
-    IDataObject * pDataObj = 0;
-
-    if (OleGetClipboard(&pDataObj) != S_OK && !pDataObj) // Sanity
-        return result;
-
-    QWindowsMime *converter = QWindowsMime::converterToMime(mimeType, pDataObj);
-
-    if (converter)
-        result = converter->convertToMime(mimeType, pDataObj, type);
-
-    pDataObj->Release();
-
-    return result;
-}
-
-class QClipboardData
-{
-public:
-    QClipboardData()
-        : iData(0)
-        , nextClipboardViewer(0)
-    {
-        clipBoardViewer = new QWidget();
-        clipBoardViewer->createWinId();
-        clipBoardViewer->setObjectName(QLatin1String("internal clipboard owner"));
-        // We don't need this internal widget to appear in QApplication::topLevelWidgets()
-        if (QWidgetPrivate::allWidgets)
-            QWidgetPrivate::allWidgets->remove(clipBoardViewer);
-    }
-
-    ~QClipboardData()
-    {
-        Q_ASSERT(clipBoardViewer->testAttribute(Qt::WA_WState_Created));
-        ChangeClipboardChain(clipBoardViewer->internalWinId(), nextClipboardViewer);
-        delete clipBoardViewer;
-        releaseIData();
-    }
-
-    void releaseIData()
-    {
-        if (iData) {
-            delete iData->mimeData();
-            iData->releaseQt();
-            iData->Release();
-            iData = 0;
-        }
-    }
-
-    QOleDataObject * iData;
-    QWidget *clipBoardViewer;
-    HWND nextClipboardViewer;
-    QClipboardWatcher watcher;
-};
-
-static QClipboardData *ptrClipboardData = 0;
-
-static QClipboardData *clipboardData()
-{
-    if (ptrClipboardData == 0) {
-        ptrClipboardData = new QClipboardData;
-        // this needs to be done here to avoid recursion
-        Q_ASSERT(ptrClipboardData->clipBoardViewer->testAttribute(Qt::WA_WState_Created));
-        ptrClipboardData->nextClipboardViewer = SetClipboardViewer(ptrClipboardData->clipBoardViewer->internalWinId());
-    }
-    return ptrClipboardData;
-}
-
-static void cleanupClipboardData()
-{
-    delete ptrClipboardData;
-    ptrClipboardData = 0;
-}
-
-#if defined(Q_OS_WINCE)
-HRESULT QtCeGetClipboard(IDataObject** obj)
-{
-    HWND owner = ptrClipboardData->clipBoardViewer->internalWinId();
-    if (!OpenClipboard(owner))
-        return !S_OK;
-
-    if (!IsClipboardFormatAvailable(CF_TEXT) && !IsClipboardFormatAvailable(CF_UNICODETEXT))
-        return !S_OK;
-
-    HANDLE clipData = GetClipboardData(CF_TEXT);
-    QString clipText;
-    if (clipData == 0) {
-        clipData = GetClipboardData(CF_UNICODETEXT);
-        if (clipData != 0)
-            clipText = QString::fromWCharArray((wchar_t *)clipData);
-    } else {
-        clipText = QString::fromLatin1((const char*)clipData);
-    }
-
-    QMimeData *mimeData = new QMimeData();
-    mimeData->setText(clipText);
-    QOleDataObject* data = new QOleDataObject(mimeData);
-    *obj = data;
-    CloseClipboard();
-    return S_OK;
-}
-
-HRESULT QtCeSetClipboard(IDataObject* obj)
-{
-    HWND owner = ptrClipboardData->clipBoardViewer->internalWinId();
-    if (!OpenClipboard(owner))
-        return !S_OK;
-
-    bool result = false;
-    if (obj == 0) {
-        result = true;
-        EmptyClipboard();
-        CloseClipboard();
-    } else {
-        QOleDataObject* qobj = static_cast<QOleDataObject*>(obj);
-
-        const QMimeData* data = qobj->mimeData();
-        if (data->hasText()) {
-            EmptyClipboard();
-            result = SetClipboardData(CF_UNICODETEXT, wcsdup(reinterpret_cast<const wchar_t *> (data->text().utf16()))) != NULL;
-            CloseClipboard();
-            result = true;
-        }
-    }
-    return result ? S_OK : !S_OK;
-}
-
-void QtCeFlushClipboard() { }
-#endif
-
-
-
-QClipboard::~QClipboard()
-{
-    cleanupClipboardData();
-}
-
-void QClipboard::setMimeData(QMimeData *src, Mode mode)
-{
-    if (mode != Clipboard)
-        return;
-    QClipboardData *d = clipboardData();
-
-    if (!(d->iData && d->iData->mimeData() == src)) {
-        d->releaseIData();
-        d->iData = new QOleDataObject(src);
-    }
-
-    if (OleSetClipboard(d->iData) != S_OK) {
-        d->releaseIData();
-        qErrnoWarning("QClipboard::setMimeData: Failed to set data on clipboard");
-        return;
-    }
-#if defined(Q_OS_WINCE)
-    // As WinCE does not support notifications we send the signal here
-    // We will get no event when the clipboard changes outside...
-    emit dataChanged();
-    emit changed(Clipboard);
-#endif
-}
-
-void QClipboard::clear(Mode mode)
-{
-    if (mode != Clipboard) return;
-
-    QClipboardData *d = clipboardData();
-
-    d->releaseIData();
-
-    if (OleSetClipboard(0) != S_OK) {
-        qErrnoWarning("QClipboard::clear: Failed to clear data on clipboard");
-        return;
-    }
-#if defined(Q_OS_WINCE)
-    // As WinCE does not support notifications we send the signal here
-    // We will get no event when the clipboard changes outside...
-    emit dataChanged();
-    emit changed(Clipboard);
-#endif
-}
-
-#if !defined(Q_OS_WINCE) && defined(Q_CC_MSVC) && WINVER > 0x0501
-static bool isProcessBeingDebugged(HWND hwnd)
-{
-    DWORD pid = 0;
-    if (!GetWindowThreadProcessId(hwnd, &pid) || !pid)
-        return false;
-    const HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
-    if (!processHandle)
-       return false;
-    BOOL debugged = FALSE;
-    CheckRemoteDebuggerPresent(processHandle, &debugged);
-    CloseHandle(processHandle);
-    return debugged != FALSE;
-}
-#else // !defined(Q_OS_WINCE) && defined(Q_CC_MSVC) && WINVER > 0x0501
-static bool isProcessBeingDebugged(HWND) { return false; }
-#endif // defined(Q_OS_WINCE) || !defined(Q_CC_MSVC) && WINVER > 0x0501
-
-bool QClipboard::event(QEvent *e)
-{
-    if (e->type() != QEvent::Clipboard)
-        return QObject::event(e);
-
-    QClipboardData *d = clipboardData();
-
-    MSG *m = (MSG *)((QClipboardEvent*)e)->data();
-    if (!m) {
-        // this is sent to render all formats at app shut down
-        if (ownsClipboard()) {
-            OleFlushClipboard();
-            d->releaseIData();
-        }
-        return true;
-    }
-
-    bool propagate = false;
-
-    if (m->message == WM_CHANGECBCHAIN) {
-        if ((HWND)m->wParam == d->nextClipboardViewer)
-            d->nextClipboardViewer = (HWND)m->lParam;
-        else
-            propagate = true;
-    } else if (m->message == WM_DRAWCLIPBOARD) {
-        emitChanged(QClipboard::Clipboard);
-        if (!ownsClipboard() && d->iData)
-            // clean up the clipboard object if we no longer own the clipboard
-            d->releaseIData();
-        propagate = true;
-    }
-    if (propagate && d->nextClipboardViewer) {
-        if (ptrIsHungAppWindow == 0) {
-            QSystemLibrary library(QLatin1String("User32"));
-            ptrIsHungAppWindow = (PtrIsHungAppWindow)library.resolve("IsHungAppWindow");
-        }
-        if (ptrIsHungAppWindow && ptrIsHungAppWindow(d->nextClipboardViewer)) {
-            qWarning("%s: Cowardly refusing to send clipboard message to hung application...", Q_FUNC_INFO);
-        } else if (isProcessBeingDebugged(d->nextClipboardViewer)) {
-            // Also refuse if the process is being debugged, specifically, if it is
-            // displaying a runtime assert, which is not caught by isHungAppWindow().
-            qWarning("%s: Cowardly refusing to send clipboard message to application under debugger...", Q_FUNC_INFO);
-        } else {
-            SendMessage(d->nextClipboardViewer, m->message, m->wParam, m->lParam);
-        }
-    }
-
-    return true;
-}
-
-void QClipboard::connectNotify(const char *signal)
-{
-    if (qstrcmp(signal,SIGNAL(dataChanged())) == 0) {
-        // ensure we are up and running but block signals so the dataChange signal
-        // is not emitted while being connected to.
-        bool blocked = blockSignals(true);
-        QClipboardData *d = clipboardData();
-        blockSignals(blocked);
-        Q_UNUSED(d);
-    }
-}
-
-const QMimeData *QClipboard::mimeData(Mode mode) const
-{
-    if (mode != Clipboard)
-        return 0;
-
-    QClipboardData *data = clipboardData();
-    // sort cut for local copy / paste
-    if (ownsClipboard() && data->iData->mimeData())
-        return data->iData->mimeData();
-    return &data->watcher;
-}
-
-bool QClipboard::supportsMode(Mode mode) const
-{
-    return (mode == Clipboard);
-}
-
-bool QClipboard::ownsMode(Mode mode) const
-{
-    if (mode == Clipboard) {
-        QClipboardData *d = clipboardData();
-#if !defined(Q_OS_WINCE)
-        return d->iData && OleIsCurrentClipboard(d->iData) == S_OK;
-#else
-        return d->iData && GetClipboardOwner() == d->clipBoardViewer->internalWinId();
-#endif
-    } else {
-        return false;
-    }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_CLIPBOARD
diff --git a/src/gui/kernel/qcocoaapplication_mac.mm b/src/gui/kernel/qcocoaapplication_mac.mm
deleted file mode 100644 (file)
index cd0d0ac..0000000
+++ /dev/null
@@ -1,232 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#include <qglobal.h>
-#ifdef QT_MAC_USE_COCOA
-#include <qcocoaapplication_mac_p.h>
-#include <qcocoaapplicationdelegate_mac_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qcocoaintrospection_p.h>
-
-QT_USE_NAMESPACE
-
-@implementation NSApplication (QT_MANGLE_NAMESPACE(QApplicationIntegration))
-
-- (void)QT_MANGLE_NAMESPACE(qt_setDockMenu):(NSMenu *)newMenu
-{
-    [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] setDockMenu:newMenu];
-}
-
-- (QApplicationPrivate *)QT_MANGLE_NAMESPACE(qt_qappPrivate)
-{
-    return [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] qAppPrivate];
-}
-
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)
-{
-    return [[QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) sharedDelegate] menuLoader];
-}
-
-- (int)QT_MANGLE_NAMESPACE(qt_validModesForFontPanel):(NSFontPanel *)fontPanel
-{
-    Q_UNUSED(fontPanel);
-    // only display those things that QFont can handle
-    return NSFontPanelFaceModeMask
-            | NSFontPanelSizeModeMask
-            | NSFontPanelCollectionModeMask
-            | NSFontPanelUnderlineEffectModeMask
-            | NSFontPanelStrikethroughEffectModeMask;
-}
-
-- (void)QT_MANGLE_NAMESPACE(qt_sendPostedMessage):(NSEvent *)event
-{
-    // WARNING: data1 and data2 is truncated to from 64-bit to 32-bit on OS 10.5! 
-    // That is why we need to split the address in two parts:
-    quint64 lower = [event data1];
-    quint64 upper = [event data2];
-    QCocoaPostMessageArgs *args = reinterpret_cast<QCocoaPostMessageArgs *>(lower | (upper << 32));
-    // Special case for convenience: if the argument is an NSNumber, we unbox it directly.
-    // Use NSValue instead if this behaviour is unwanted.
-    id a1 = ([args->arg1 isKindOfClass:[NSNumber class]]) ? (id)[args->arg1 intValue] : args->arg1;
-    id a2 = ([args->arg2 isKindOfClass:[NSNumber class]]) ? (id)[args->arg2 intValue] : args->arg2;
-    switch (args->argCount) {
-    case 0:
-        [args->target performSelector:args->selector];
-        break;
-    case 1:
-        [args->target performSelector:args->selector withObject:a1];
-        break;
-    case 3:
-        [args->target performSelector:args->selector withObject:a1 withObject:a2];
-        break;
-    }
-
-    delete args;
-}
-
-- (BOOL)QT_MANGLE_NAMESPACE(qt_filterEvent):(NSEvent *)event
-{
-    if (!qApp)
-        return false;
-
-    if (qApp->macEventFilter(0, reinterpret_cast<EventRef>(event)))
-        return true;
-
-    if ([event type] == NSApplicationDefined) {
-        switch ([event subtype]) {
-            case QtCocoaEventSubTypePostMessage:
-                [[NSApplication sharedApplication] QT_MANGLE_NAMESPACE(qt_sendPostedMessage):event];
-                return true;
-            default:
-                break;
-        }
-    }
-    return false;
-}
-
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSApplication)
-
-- (void)QT_MANGLE_NAMESPACE(qt_sendEvent_original):(NSEvent *)event
-{
-    Q_UNUSED(event);
-    // This method will only be used as a signature
-    // template for the method we add into NSApplication
-    // containing the original [NSApplication sendEvent:] implementation
-}
-
-- (void)QT_MANGLE_NAMESPACE(qt_sendEvent_replacement):(NSEvent *)event
-{
-    // This method (or its implementation to be precise) will
-    // be called instead of sendEvent if redirection occurs.
-    // 'self' will then be an instance of NSApplication
-    // (and not QNSApplication)
-    if (![[NSApplication sharedApplication] QT_MANGLE_NAMESPACE(qt_filterEvent):event])
-        [self QT_MANGLE_NAMESPACE(qt_sendEvent_original):event];
-}
-
-- (void)sendEvent:(NSEvent *)event
-{
-    // This method will be called if
-    // no redirection occurs
-    if (![[NSApplication sharedApplication] QT_MANGLE_NAMESPACE(qt_filterEvent):event])
-        [super sendEvent:event];
-}
-
-- (void)qtDispatcherToQAction:(id)sender
-{
-    // Forward actions sendt from the menu bar (e.g. quit) to the menu loader.
-    // Having this method here means that we are the last stop in the responder
-    // chain, and that we are able to handle menu actions even when no window is
-    // visible on screen. Note: If Qt is used as a plugin, Qt will not use a 
-    // native menu bar. Hence, we will also not need to do any redirection etc. as 
-    // we do with sendEvent.
-    [[[NSApplication sharedApplication] QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)] qtDispatcherToQAction:sender];
-}
-
-@end
-
-QT_BEGIN_NAMESPACE
-
-void qt_redirectNSApplicationSendEvent()
-{
-    if ([[NSApplication sharedApplication] isMemberOfClass:[QT_MANGLE_NAMESPACE(QNSApplication) class]]) {
-        // No need to change implementation since Qt
-        // already controls a subclass of NSApplication
-        return;
-    }
-
-    // Change the implementation of [NSApplication sendEvent] to the
-    // implementation of qt_sendEvent_replacement found in QNSApplication.
-    // And keep the old implementation that gets overwritten inside a new
-    // method 'qt_sendEvent_original' that we add to NSApplication
-    qt_cocoa_change_implementation(
-            [NSApplication class],
-            @selector(sendEvent:),
-            [QT_MANGLE_NAMESPACE(QNSApplication) class],
-            @selector(QT_MANGLE_NAMESPACE(qt_sendEvent_replacement):),
-            @selector(QT_MANGLE_NAMESPACE(qt_sendEvent_original):));
- }
-
-void qt_resetNSApplicationSendEvent()
-{
-    qt_cocoa_change_back_implementation([NSApplication class],
-                                         @selector(sendEvent:),
-                                         @selector(QT_MANGLE_NAMESPACE(qt_sendEvent_original):));
-}
-
-QT_END_NAMESPACE
-#endif
diff --git a/src/gui/kernel/qcocoaapplication_mac_p.h b/src/gui/kernel/qcocoaapplication_mac_p.h
deleted file mode 100644 (file)
index 3794e1d..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-//
-//  W A R N I N G
-//  -------------
-//
-// This file is not part of the Qt API.  It exists for the convenience
-// of qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
-// and many other.  This header file may change from version to version
-// without notice, or even be removed.
-//
-// We mean it.
-//
-
-/*
-       Cocoa Application Categories
-*/
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <AppKit/AppKit.h>
-QT_FORWARD_DECLARE_CLASS(QApplicationPrivate)
-@class QT_MANGLE_NAMESPACE(QCocoaMenuLoader);
-
-@interface NSApplication (QT_MANGLE_NAMESPACE(QApplicationIntegration))
-- (void)QT_MANGLE_NAMESPACE(qt_setDockMenu):(NSMenu *)newMenu;
-- (QApplicationPrivate *)QT_MANGLE_NAMESPACE(qt_qappPrivate);
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader);
-- (int)QT_MANGLE_NAMESPACE(qt_validModesForFontPanel):(NSFontPanel *)fontPanel;
-
-- (void)QT_MANGLE_NAMESPACE(qt_sendPostedMessage):(NSEvent *)event;
-- (BOOL)QT_MANGLE_NAMESPACE(qt_filterEvent):(NSEvent *)event;
-@end
-
-@interface QT_MANGLE_NAMESPACE(QNSApplication) : NSApplication {
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-void qt_redirectNSApplicationSendEvent();
-void qt_resetNSApplicationSendEvent();
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/kernel/qcocoaapplicationdelegate_mac.mm b/src/gui/kernel/qcocoaapplicationdelegate_mac.mm
deleted file mode 100644 (file)
index da3a03b..0000000
+++ /dev/null
@@ -1,367 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
- **
- ** Copyright (c) 2007-2008, Apple, Inc.
- **
- ** All rights reserved.
- **
- ** Redistribution and use in source and binary forms, with or without
- ** modification, are permitted provided that the following conditions are met:
- **
- **   * Redistributions of source code must retain the above copyright notice,
- **     this list of conditions and the following disclaimer.
- **
- **   * Redistributions in binary form must reproduce the above copyright notice,
- **     this list of conditions and the following disclaimer in the documentation
- **     and/or other materials provided with the distribution.
- **
- **   * Neither the name of Apple, Inc. nor the names of its contributors
- **     may be used to endorse or promote products derived from this software
- **     without specific prior written permission.
- **
- ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- ** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- ** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- **
- ****************************************************************************/
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-
-#import <qcocoaapplicationdelegate_mac_p.h>
-#import <qcocoamenuloader_mac_p.h>
-#import <qcocoaapplication_mac_p.h>
-#include <qapplication_p.h>
-#include <qt_mac_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qdesktopwidget_mac_p.h>
-#include <qevent.h>
-#include <qurl.h>
-#include <qapplication.h>
-
-QT_BEGIN_NAMESPACE
-extern void onApplicationChangedActivation(bool); // qapplication_mac.mm
-extern void qt_release_apple_event_handler(); //qapplication_mac.mm
-extern QPointer<QWidget> qt_last_mouse_receiver; // qapplication_mac.cpp
-extern QPointer<QWidget> qt_last_native_mouse_receiver; // qt_cocoa_helpers_mac.mm
-extern QPointer<QWidget> qt_button_down; // qapplication_mac.cpp
-
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QDesktopWidgetImplementation)
-QT_USE_NAMESPACE
-
-static QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) *sharedCocoaApplicationDelegate = nil;
-
-static void cleanupCocoaApplicationDelegate()
-{
-    [sharedCocoaApplicationDelegate release];
-}
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate)
-
-- (id)init
-{
-    self = [super init];
-    if (self)
-        inLaunch = true;
-    return self;
-}
-
-- (void)dealloc
-{
-    sharedCocoaApplicationDelegate = nil;
-    [dockMenu release];
-    [qtMenuLoader release];
-    if (reflectionDelegate) {
-        [[NSApplication sharedApplication] setDelegate:reflectionDelegate];
-        [reflectionDelegate release];
-    }
-    [super dealloc];
-}
-
-+ (id)allocWithZone:(NSZone *)zone
-{
-    @synchronized(self) {
-        if (sharedCocoaApplicationDelegate == nil) {
-            sharedCocoaApplicationDelegate = [super allocWithZone:zone];
-            return sharedCocoaApplicationDelegate;
-            qAddPostRoutine(cleanupCocoaApplicationDelegate);
-        }
-    }
-    return nil;
-}
-
-+ (QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate)*)sharedDelegate
-{
-    @synchronized(self) {
-        if (sharedCocoaApplicationDelegate == nil)
-            [[self alloc] init];
-    }
-    return [[sharedCocoaApplicationDelegate retain] autorelease];
-}
-
-- (void)setDockMenu:(NSMenu*)newMenu
-{
-    [newMenu retain];
-    [dockMenu release];
-    dockMenu = newMenu;
-}
-
-- (NSMenu *)applicationDockMenu
-{
-    return [[dockMenu retain] autorelease];
-}
-
-- (QApplicationPrivate *)qAppPrivate
-{
-    return qtPrivate;
-}
-
-- (void)setQtPrivate:(QApplicationPrivate *)value
-{
-    qtPrivate = value;
-}
-
-- (void)setMenuLoader:(QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)menuLoader
-{
-    [menuLoader retain];
-    [qtMenuLoader release];
-    qtMenuLoader = menuLoader;
-}
-
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)menuLoader
-{
-    return [[qtMenuLoader retain] autorelease];
-}
-
-// This function will only be called when NSApplication is actually running. Before
-// that, the kAEQuitApplication Apple event will be sent to
-// QApplicationPrivate::globalAppleEventProcessor in qapplication_mac.mm
-- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
-{
-    Q_UNUSED(sender);
-    // The reflection delegate gets precedence
-    if (reflectionDelegate
-        && [reflectionDelegate respondsToSelector:@selector(applicationShouldTerminate:)]) {
-        return [reflectionDelegate applicationShouldTerminate:sender];
-    }
-
-    if (qtPrivate->canQuit()) {
-        if (!startedQuit) {
-            startedQuit = true;
-            qAppInstance()->quit();
-            startedQuit = false;
-        }
-    }
-
-    if (qtPrivate->threadData->eventLoops.size() == 0) {
-        // INVARIANT: No event loop is executing. This probably
-        // means that Qt is used as a plugin, or as a part of a native
-        // Cocoa application. In any case it should be fine to
-        // terminate now:
-        return NSTerminateNow;
-    }
-
-    return NSTerminateCancel;
-}
-
-- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
-{
-    Q_UNUSED(aNotification);
-    inLaunch = false;
-    qt_release_apple_event_handler();
-}
-
-- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames
-{
-    for (NSString *fileName in filenames) {
-        QString qtFileName = qt_mac_NSStringToQString(fileName);
-        if (inLaunch) {
-            // We need to be careful because Cocoa will be nice enough to take
-            // command line arguments and send them to us as events. Given the history
-            // of Qt Applications, this will result in behavior people don't want, as
-            // they might be doing the opening themselves with the command line parsing.
-            if (qApp->arguments().contains(qtFileName))
-                continue;
-        }
-        QFileOpenEvent foe(qtFileName);
-        qt_sendSpontaneousEvent(qAppInstance(), &foe);
-    }
-
-    if (reflectionDelegate &&
-        [reflectionDelegate respondsToSelector:@selector(application:openFiles:)])
-        [reflectionDelegate application:sender openFiles:filenames];
-}
-
-- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
-{
-    // If we have a reflection delegate, that will get to call the shots.
-    if (reflectionDelegate
-        && [reflectionDelegate respondsToSelector:
-                            @selector(applicationShouldTerminateAfterLastWindowClosed:)])
-        return [reflectionDelegate applicationShouldTerminateAfterLastWindowClosed:sender];
-    return NO; // Someday qApp->quitOnLastWindowClosed(); when qApp and NSApplication work closer together.
-}
-
-
-- (void)applicationDidBecomeActive:(NSNotification *)notification
-{
-    if (reflectionDelegate
-        && [reflectionDelegate respondsToSelector:@selector(applicationDidBecomeActive:)])
-        [reflectionDelegate applicationDidBecomeActive:notification];
-
-    onApplicationChangedActivation(true);
-
-    if (!QWidget::mouseGrabber()){
-        // Update enter/leave immidiatly, don't wait for a move event. But only
-        // if no grab exists (even if the grab points to this widget, it seems, ref X11)
-        QPoint qlocal, qglobal;
-        QWidget *widgetUnderMouse = 0;
-        qt_mac_getTargetForMouseEvent(0, QEvent::Enter, qlocal, qglobal, 0, &widgetUnderMouse);
-        QApplicationPrivate::dispatchEnterLeave(widgetUnderMouse, 0);
-        qt_last_mouse_receiver = widgetUnderMouse;
-        qt_last_native_mouse_receiver = widgetUnderMouse ?
-            (widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget()) : 0;
-    }
-}
-
-- (void)applicationDidResignActive:(NSNotification *)notification
-{
-    if (reflectionDelegate
-        && [reflectionDelegate respondsToSelector:@selector(applicationDidResignActive:)])
-        [reflectionDelegate applicationDidResignActive:notification];
-
-    onApplicationChangedActivation(false);
-
-    if (!QWidget::mouseGrabber())
-        QApplicationPrivate::dispatchEnterLeave(0, qt_last_mouse_receiver);
-    qt_last_mouse_receiver = 0;
-    qt_last_native_mouse_receiver = 0;
-    qt_button_down = 0;
-}
-
-- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
-{
-    Q_UNUSED(theApplication);
-    Q_UNUSED(flag);
-    // The reflection delegate gets precedence
-    if (reflectionDelegate
-        && [reflectionDelegate respondsToSelector:@selector(applicationShouldHandleReopen:hasVisibleWindows:)])
-        return [reflectionDelegate applicationShouldHandleReopen:theApplication hasVisibleWindows:flag];
-
-    onApplicationChangedActivation(true);
-    return NO;
-}
-
-- (void)applicationDidChangeScreenParameters:(NSNotification *)notification
-{
-    Q_UNUSED(notification);
-    QDesktopWidgetImplementation::instance()->onResize();
-}
-
-- (void)setReflectionDelegate:(id <NSApplicationDelegate>)oldDelegate
-{
-    [oldDelegate retain];
-    [reflectionDelegate release];
-    reflectionDelegate = oldDelegate;
-}
-
-- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
-{
-    NSMethodSignature *result = [super methodSignatureForSelector:aSelector];
-    if (!result && reflectionDelegate) {
-        result = [reflectionDelegate methodSignatureForSelector:aSelector];
-    }
-    return result;
-}
-
-- (BOOL)respondsToSelector:(SEL)aSelector
-{
-    BOOL result = [super respondsToSelector:aSelector];
-    if (!result && reflectionDelegate)
-        result = [reflectionDelegate respondsToSelector:aSelector];
-    return result;
-}
-
-- (void)forwardInvocation:(NSInvocation *)invocation
-{
-    SEL invocationSelector = [invocation selector];
-    if (reflectionDelegate && [reflectionDelegate respondsToSelector:invocationSelector])
-        [invocation invokeWithTarget:reflectionDelegate];
-    else
-        [self doesNotRecognizeSelector:invocationSelector];
-}
-
-- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
-{
-    Q_UNUSED(replyEvent);
-
-    NSString *urlString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
-    QUrl url(qt_mac_NSStringToQString(urlString));
-    QFileOpenEvent qtEvent(url);
-    qt_sendSpontaneousEvent(qAppInstance(), &qtEvent);
-}
-
-- (void)appleEventQuit:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
-{
-    Q_UNUSED(event);
-    Q_UNUSED(replyEvent);
-    [[NSApplication sharedApplication] terminate:self];
-}
-
-- (void)qtDispatcherToQAction:(id)sender
-{
-    [[[NSApplication sharedApplication] QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)] qtDispatcherToQAction:sender];
-}
-
-@end
-#endif
diff --git a/src/gui/kernel/qcocoaapplicationdelegate_mac_p.h b/src/gui/kernel/qcocoaapplicationdelegate_mac_p.h
deleted file mode 100644 (file)
index 2a38de4..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-/****************************************************************************
- **
- ** Copyright (c) 2007-2008, Apple, Inc.
- **
- ** All rights reserved.
- **
- ** Redistribution and use in source and binary forms, with or without
- ** modification, are permitted provided that the following conditions are met:
- **
- **   * Redistributions of source code must retain the above copyright notice,
- **     this list of conditions and the following disclaimer.
- **
- **   * Redistributions in binary form must reproduce the above copyright notice,
- **     this list of conditions and the following disclaimer in the documentation
- **     and/or other materials provided with the distribution.
- **
- **   * Neither the name of Apple, Inc. nor the names of its contributors
- **     may be used to endorse or promote products derived from this software
- **     without specific prior written permission.
- **
- ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- ** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- ** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- **
- ****************************************************************************/
-
-//
-//  W A R N I N G
-//  -------------
-//
-// This file is not part of the Qt API.  It exists for the convenience
-// of qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
-// and many other.  This header file may change from version to version
-// without notice, or even be removed.
-//
-// We mean it.
-//
-
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_FORWARD_DECLARE_CLASS(QApplicationPrivate);
-
-@class QT_MANGLE_NAMESPACE(QCocoaMenuLoader);
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-
-@protocol NSApplicationDelegate <NSObject>
-- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
-- (void)applicationDidFinishLaunching:(NSNotification *)aNotification;
-- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames;
-- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender;
-- (void)applicationDidBecomeActive:(NSNotification *)notification;
-- (void)applicationDidResignActive:(NSNotification *)notification;
-@end
-
-#endif
-
-@interface QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate) : NSObject <NSApplicationDelegate> {
-    bool startedQuit;
-    QApplicationPrivate *qtPrivate;
-    NSMenu *dockMenu;
-    QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *qtMenuLoader;
-    id <NSApplicationDelegate> reflectionDelegate;
-    bool inLaunch;
-}
-+ (QT_MANGLE_NAMESPACE(QCocoaApplicationDelegate)*)sharedDelegate;
-- (void)setDockMenu:(NSMenu *)newMenu;
-- (void)setQtPrivate:(QApplicationPrivate *)value;
-- (QApplicationPrivate *)qAppPrivate;
-- (void)setMenuLoader:(QT_MANGLE_NAMESPACE(QCocoaMenuLoader)*)menuLoader;
-- (QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *)menuLoader;
-- (void)setReflectionDelegate:(id <NSApplicationDelegate>)oldDelegate;
-- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent;
-@end
-#endif
diff --git a/src/gui/kernel/qcocoaintrospection_mac.mm b/src/gui/kernel/qcocoaintrospection_mac.mm
deleted file mode 100644 (file)
index 54512f1..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#include <qcocoaintrospection_p.h>
-
-QT_BEGIN_NAMESPACE
-
-void qt_cocoa_change_implementation(Class baseClass, SEL originalSel, Class proxyClass, SEL replacementSel, SEL backupSel)
-{
-#ifndef QT_MAC_USE_COCOA
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5)
-#endif
-    {
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-        // The following code replaces the _implementation_ for the selector we want to hack
-        // (originalSel) with the implementation found in proxyClass. Then it creates
-        // a new 'backup' method inside baseClass containing the old, original,
-        // implementation (fakeSel). You can let the proxy implementation of originalSel
-        // call fakeSel if needed (similar approach to calling a super class implementation).
-        // fakeSel must also be implemented in proxyClass, as the signature is used
-        // as template for the method one we add into baseClass.
-        // NB: You will typically never create any instances of proxyClass; we use it
-        // only for stealing its contents and put it into baseClass.
-        if (!replacementSel)
-            replacementSel = originalSel;
-
-        Method originalMethod = class_getInstanceMethod(baseClass, originalSel);
-        Method replacementMethod = class_getInstanceMethod(proxyClass, replacementSel);
-        IMP originalImp = method_setImplementation(originalMethod, method_getImplementation(replacementMethod));
-
-        if (backupSel) {
-            Method backupMethod = class_getInstanceMethod(proxyClass, backupSel);
-            class_addMethod(baseClass, backupSel, originalImp, method_getTypeEncoding(backupMethod));
-        }
-#endif
-    }
-}
-
-void qt_cocoa_change_back_implementation(Class baseClass, SEL originalSel, SEL backupSel)
-{
-#ifndef QT_MAC_USE_COCOA
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5)
-#endif
-    {
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-        Method originalMethod = class_getInstanceMethod(baseClass, originalSel);
-        Method backupMethodInBaseClass = class_getInstanceMethod(baseClass, backupSel);
-        method_setImplementation(originalMethod, method_getImplementation(backupMethodInBaseClass));
-#endif
-    }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qcocoamenuloader_mac.mm b/src/gui/kernel/qcocoamenuloader_mac.mm
deleted file mode 100644 (file)
index 0a19e8f..0000000
+++ /dev/null
@@ -1,276 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#include <qaction.h>
-#include <qcoreapplication.h>
-#include <qcocoamenuloader_mac_p.h>
-#include <qapplication_p.h>
-#include <qt_mac_p.h>
-#include <qmenubar_p.h>
-#include <qmenubar.h>
-#include <qt_cocoa_helpers_mac_p.h>
-
-QT_FORWARD_DECLARE_CLASS(QCFString)
-QT_FORWARD_DECLARE_CLASS(QString)
-
-#ifndef QT_NO_TRANSLATION
-    QT_BEGIN_NAMESPACE
-    extern QString qt_mac_applicationmenu_string(int type);
-    QT_END_NAMESPACE
-#endif
-
-QT_USE_NAMESPACE
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaMenuLoader)
-
-- (void)awakeFromNib
-{
-    servicesItem = [[appMenu itemWithTitle:@"Services"] retain];
-    hideAllOthersItem = [[appMenu itemWithTitle:@"Hide Others"] retain];
-    showAllItem = [[appMenu itemWithTitle:@"Show All"] retain];
-
-    // Get the names in the nib to match the app name set by Qt.
-    const NSString *appName = reinterpret_cast<const NSString*>(QCFString::toCFStringRef(qAppName()));
-    [quitItem setTitle:[[quitItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
-                                                                   withString:const_cast<NSString *>(appName)]];
-    [hideItem setTitle:[[hideItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
-                                                                   withString:const_cast<NSString *>(appName)]];
-    [aboutItem setTitle:[[aboutItem title] stringByReplacingOccurrencesOfString:@"NewApplication"
-                                                                   withString:const_cast<NSString *>(appName)]];
-    [appName release];
-    // Disable the items that don't do anything. If someone associates a QAction with them
-    // They should get synced back in.
-    [preferencesItem setEnabled:NO];
-    [preferencesItem setHidden:YES];
-    [aboutItem setEnabled:NO];
-    [aboutItem setHidden:YES];
-}
-
-- (void)ensureAppMenuInMenu:(NSMenu *)menu
-{
-    // The application menu is the menu in the menu bar that contains the
-    // 'Quit' item. When changing menu bar (e.g when switching between
-    // windows with different menu bars), we never recreate this menu, but
-    // instead pull it out the current menu bar and place into the new one:
-    NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
-    if ([[NSApplication sharedApplication] mainMenu] == menu)
-        return; // nothing to do (menu is the current menu bar)!
-
-#ifndef QT_NAMESPACE
-    Q_ASSERT(mainMenu);
-#endif
-    // Grab the app menu out of the current menu.
-    int numItems = [mainMenu numberOfItems];
-    NSMenuItem *oldAppMenuItem = 0;
-    for (int i = 0; i < numItems; ++i) {
-        NSMenuItem *item = [mainMenu itemAtIndex:i];
-        if ([item submenu] == appMenu) {
-            oldAppMenuItem = item;
-            [oldAppMenuItem retain];
-            [mainMenu removeItemAtIndex:i];
-            break;
-        }
-    }
-
-    if (oldAppMenuItem) {
-        [oldAppMenuItem setSubmenu:nil];
-        [oldAppMenuItem release];
-        NSMenuItem *appMenuItem = [[NSMenuItem alloc] initWithTitle:@"Apple"
-            action:nil keyEquivalent:@""];
-        [appMenuItem setSubmenu:appMenu];
-        [menu insertItem:appMenuItem atIndex:0];
-    }
-}
-
-- (void)removeActionsFromAppMenu
-{
-    for (NSMenuItem *item in [appMenu itemArray])
-        [item setTag:nil];
-}
-
-- (void)dealloc
-{
-    [servicesItem release];
-    [hideAllOthersItem release];
-    [showAllItem release];
-
-    [lastAppSpecificItem release];
-    [theMenu release];
-    [appMenu release];
-    [super dealloc];
-}
-
-- (NSMenu *)menu
-{
-    return [[theMenu retain] autorelease];
-}
-
-- (NSMenu *)applicationMenu
-{
-    return [[appMenu retain] autorelease];
-}
-
-- (NSMenuItem *)quitMenuItem
-{
-    return [[quitItem retain] autorelease];
-}
-
-- (NSMenuItem *)preferencesMenuItem
-{
-    return [[preferencesItem retain] autorelease];
-}
-
-- (NSMenuItem *)aboutMenuItem
-{
-    return [[aboutItem retain] autorelease];
-}
-
-- (NSMenuItem *)aboutQtMenuItem
-{
-    return [[aboutQtItem retain] autorelease];
-}
-
-- (NSMenuItem *)hideMenuItem
-{
-    return [[hideItem retain] autorelease];
-}
-
-- (NSMenuItem *)appSpecificMenuItem
-{
-    // Create an App-Specific menu item, insert it into the menu and return
-    // it as an autorelease item.
-    NSMenuItem *item = [[NSMenuItem alloc] init];
-
-    NSInteger location;
-    if (lastAppSpecificItem == nil) {
-        location = [appMenu indexOfItem:aboutQtItem];
-    } else {
-        location = [appMenu indexOfItem:lastAppSpecificItem];
-        [lastAppSpecificItem release];
-    }
-    lastAppSpecificItem = item;  // Keep track of this for later (i.e., don't release it)
-    [appMenu insertItem:item atIndex:location + 1];
-
-    return [[item retain] autorelease];
-}
-
-- (BOOL) acceptsFirstResponder
-{
-    return YES;
-}
-
-- (void)terminate:(id)sender
-{
-    [[NSApplication sharedApplication] terminate:sender];
-}
-
-- (void)orderFrontStandardAboutPanel:(id)sender
-{
-    [[NSApplication sharedApplication] orderFrontStandardAboutPanel:sender];
-}
-
-- (void)hideOtherApplications:(id)sender
-{
-    [[NSApplication sharedApplication] hideOtherApplications:sender];
-}
-
-- (void)unhideAllApplications:(id)sender
-{
-    [[NSApplication sharedApplication] unhideAllApplications:sender];
-}
-
-- (void)hide:(id)sender
-{
-    [[NSApplication sharedApplication] hide:sender];
-}
-
-- (void)qtUpdateMenubar
-{
-    QMenuBarPrivate::macUpdateMenuBarImmediatly();
-}
-
-- (void)qtTranslateApplicationMenu
-{
-#ifndef QT_NO_TRANSLATION
-    [servicesItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(0))];
-    [hideItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(1).arg(qAppName()))];
-    [hideAllOthersItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(2))];
-    [showAllItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(3))];
-    [preferencesItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(4))];
-    [quitItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(5).arg(qAppName()))];
-    [aboutItem setTitle: qt_mac_QStringToNSString(qt_mac_applicationmenu_string(6).arg(qAppName()))];
-#endif
-}
-
-- (IBAction)qtDispatcherToQAction:(id)sender
-{
-    QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);
-    NSMenuItem *item = static_cast<NSMenuItem *>(sender);
-    if (QAction *action = reinterpret_cast<QAction *>([item tag])) {
-        action->trigger();
-    } else if (item == quitItem) {
-        // We got here because someone was once the quitItem, but it has been
-        // abandoned (e.g., the menubar was deleted). In the meantime, just do
-        // normal QApplication::quit().
-        qApp->quit();
-    }
-}
-
- - (void)orderFrontCharacterPalette:(id)sender
- {
-     [[NSApplication sharedApplication] orderFrontCharacterPalette:sender];
- }
-
-- (BOOL)validateMenuItem:(NSMenuItem*)menuItem
-{
-    if ([menuItem action] == @selector(hide:)
-        || [menuItem action] == @selector(hideOtherApplications:)
-        || [menuItem action] == @selector(unhideAllApplications:)) {
-        return [[NSApplication sharedApplication] validateMenuItem:menuItem];
-    } else {
-        return [menuItem isEnabled];
-    }
-}
-
-@end
-#endif // QT_MAC_USE_COCOA
diff --git a/src/gui/kernel/qcocoamenuloader_mac_p.h b/src/gui/kernel/qcocoamenuloader_mac_p.h
deleted file mode 100644 (file)
index 0b55f1d..0000000
+++ /dev/null
@@ -1,96 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QCOCOAMENULOADER_P_H
-#define QCOCOAMENULOADER_P_H
-
-//
-//  W A R N I N G
-//  -------------
-//
-// This file is not part of the Qt API.  It exists for the convenience
-// of qapplication_*.cpp, qwidget*.cpp and qfiledialog.cpp.  This header
-// file may change from version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-@interface QT_MANGLE_NAMESPACE(QCocoaMenuLoader) : NSResponder
-{
-    IBOutlet NSMenu *theMenu;
-    IBOutlet NSMenu *appMenu;
-    IBOutlet NSMenuItem *quitItem;
-    IBOutlet NSMenuItem *preferencesItem;
-    IBOutlet NSMenuItem *aboutItem;
-    IBOutlet NSMenuItem *aboutQtItem;
-    IBOutlet NSMenuItem *hideItem;
-    NSMenuItem *lastAppSpecificItem;
-    NSMenuItem *servicesItem;
-    NSMenuItem *hideAllOthersItem;
-    NSMenuItem *showAllItem;
-}
-- (void)ensureAppMenuInMenu:(NSMenu *)menu;
-- (void)removeActionsFromAppMenu;
-- (NSMenu *)applicationMenu;
-- (NSMenu *)menu;
-- (NSMenuItem *)quitMenuItem;
-- (NSMenuItem *)preferencesMenuItem;
-- (NSMenuItem *)aboutMenuItem;
-- (NSMenuItem *)aboutQtMenuItem;
-- (NSMenuItem *)hideMenuItem;
-- (NSMenuItem *)appSpecificMenuItem;
-- (IBAction)terminate:(id)sender;
-- (IBAction)orderFrontStandardAboutPanel:(id)sender;
-- (IBAction)hideOtherApplications:(id)sender;
-- (IBAction)unhideAllApplications:(id)sender;
-- (IBAction)hide:(id)sender;
-- (IBAction)qtDispatcherToQAction:(id)sender;
-- (void)qtUpdateMenubar;
-- (void)orderFrontCharacterPalette:(id)sender;
-- (BOOL)validateMenuItem:(NSMenuItem*)menuItem;
-@end
-
-#endif // QT_MAC_USE_COCOA
-#endif // QCOCOAMENULOADER_P_H
diff --git a/src/gui/kernel/qcocoapanel_mac.mm b/src/gui/kernel/qcocoapanel_mac.mm
deleted file mode 100644 (file)
index 4aff7ec..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#import <qcocoapanel_mac_p.h>
-#ifdef QT_MAC_USE_COCOA
-#import <qt_cocoa_helpers_mac_p.h>
-#import <qcocoawindow_mac_p.h>
-#import <qcocoawindowdelegate_mac_p.h>
-#import <qcocoaview_mac_p.h>
-#import <qcocoawindowcustomthemeframe_mac_p.h>
-#import <qcocoaapplication_mac_p.h>
-#import <qmultitouch_mac_p.h>
-#import <qapplication_p.h>
-#import <qbackingstore_p.h>
-#import <qdnd_p.h>
-
-#include <QtGui/QWidget>
-
-QT_FORWARD_DECLARE_CLASS(QWidget);
-QT_USE_NAMESPACE
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaPanel)
-
-/***********************************************************************
-  Copy and Paste between QCocoaWindow and QCocoaPanel
-  This is a bit unfortunate, but thanks to the dynamic dispatch we
-  have to duplicate this code or resort to really silly forwarding methods
-**************************************************************************/
-#include "qcocoasharedwindowmethods_mac_p.h"
-
-@end
-#endif
diff --git a/src/gui/kernel/qcocoapanel_mac_p.h b/src/gui/kernel/qcocoapanel_mac_p.h
deleted file mode 100644 (file)
index 1014cd4..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#ifndef QCOCOAPANEL_MAC_P
-#define QCOCOAPANEL_MAC_P
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_FORWARD_DECLARE_CLASS(QStringList);
-QT_FORWARD_DECLARE_CLASS(QCocoaDropData);
-
-@interface NSPanel (QtIntegration)
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
-- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender;
-- (void)draggingExited:(id <NSDraggingInfo>)sender;
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
-@end
-
-@interface QT_MANGLE_NAMESPACE(QCocoaPanel) : NSPanel {
-    QStringList *currentCustomDragTypes;
-    QCocoaDropData *dropData;
-    NSInteger dragEnterSequence;
-}
-
-+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask;
-- (void)registerDragTypes;
-- (void)drawRectOriginal:(NSRect)rect;
-
-@end
-#endif
-
-#endif
diff --git a/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h b/src/gui/kernel/qcocoasharedwindowmethods_mac_p.h
deleted file mode 100644 (file)
index 217c21c..0000000
+++ /dev/null
@@ -1,610 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
- NB: This is not a header file, dispite the file name suffix. This file is
- included directly into the source code of qcocoawindow_mac.mm and
- qcocoapanel_mac.mm to avoid manually doing copy and paste of the exact
- same code needed at both places. This solution makes it more difficult
- to e.g fix a bug in qcocoawindow_mac.mm, but forget to do the same in
- qcocoapanel_mac.mm.
- The reason we need to do copy and paste in the first place, rather than
- resolve to method overriding, is that QCocoaPanel needs to inherit from
- NSPanel, while QCocoaWindow needs to inherit NSWindow rather than NSPanel).
-****************************************************************************/
-
-// WARNING: Don't include any header files from within this file. Put them
-// directly into qcocoawindow_mac_p.h and qcocoapanel_mac_p.h
-
-QT_BEGIN_NAMESPACE
-extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum); // qcocoaview.mm
-extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
-extern const QStringList& qEnabledDraggedTypes(); // qmime_mac.cpp
-extern void qt_event_request_window_change(QWidget *); // qapplication_mac.mm
-extern void qt_mac_send_posted_gl_updates(QWidget *widget); // qapplication_mac.mm
-
-Q_GLOBAL_STATIC(QPointer<QWidget>, currentDragTarget);
-QT_END_NAMESPACE
-
-- (id)initWithContentRect:(NSRect)contentRect
-    styleMask:(NSUInteger)windowStyle
-    backing:(NSBackingStoreType)bufferingType
-    defer:(BOOL)deferCreation
-{
-    self = [super initWithContentRect:contentRect styleMask:windowStyle
-        backing:bufferingType defer:deferCreation];
-    if (self) {
-        currentCustomDragTypes = 0;
-    }
-    return self;
-}
-
-- (void)dealloc
-{
-    delete currentCustomDragTypes;
-    [super dealloc];
-}
-
-- (BOOL)canBecomeKeyWindow
-{
-    QWidget *widget = [self QT_MANGLE_NAMESPACE(qt_qwidget)];
-    if (!widget)
-        return NO; // This should happen only for qt_root_win
-    if (QApplicationPrivate::isBlockedByModal(widget))
-        return NO;
-
-    bool isToolTip = (widget->windowType() == Qt::ToolTip);
-    bool isPopup = (widget->windowType() == Qt::Popup);
-    return !(isPopup || isToolTip);
-}
-
-- (BOOL)canBecomeMainWindow
-{
-    QWidget *widget = [self QT_MANGLE_NAMESPACE(qt_qwidget)];
-    if (!widget)
-        return NO; // This should happen only for qt_root_win
-    if ([self isSheet])
-        return NO;
-
-    bool isToolTip = (widget->windowType() == Qt::ToolTip);
-    bool isPopup = (widget->windowType() == Qt::Popup);
-    bool isTool = (widget->windowType() == Qt::Tool);
-    return !(isPopup || isToolTip || isTool);
-}
-
-- (void)becomeMainWindow
-{
-    [super becomeMainWindow];
-    // Cocoa sometimes tell a hidden window to become the
-    // main window (and as such, show it). This can e.g
-    // happend when the application gets activated. If
-    // this is the case, we tell it to hide again:
-    if (![self isVisible])
-        [self orderOut:self];
-}
-
-- (void)toggleToolbarShown:(id)sender
-{
-    macSendToolbarChangeEvent([self QT_MANGLE_NAMESPACE(qt_qwidget)]);
-    [super toggleToolbarShown:sender];
-}
-
-- (void)flagsChanged:(NSEvent *)theEvent
-{
-    qt_dispatchModifiersChanged(theEvent, [self QT_MANGLE_NAMESPACE(qt_qwidget)]);
-    [super flagsChanged:theEvent];
-}
-
-
-- (void)tabletProximity:(NSEvent *)tabletEvent
-{
-    qt_dispatchTabletProximityEvent(tabletEvent);
-}
-
-- (void)terminate:(id)sender
-{
-    // This function is called from the quit item in the menubar when this window
-    // is in the first responder chain (see also qtDispatcherToQAction above)
-    [[NSApplication sharedApplication] terminate:sender];
-}
-
-- (void)setLevel:(NSInteger)windowLevel
-{
-    // Cocoa will upon activating/deactivating applications level modal
-    // windows up and down, regardsless of any explicit set window level.
-    // To ensure that modal stays-on-top dialogs actually stays on top after
-    // the application is activated (and therefore stacks in front of
-    // other stays-on-top windows), we need to add this little special-case override:
-    QWidget *widget = [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] qt_qwidgetForWindow:self];
-    if (widget && widget->isModal() && (widget->windowFlags() & Qt::WindowStaysOnTopHint))
-        [super setLevel:NSPopUpMenuWindowLevel];
-    else
-        [super setLevel:windowLevel];
-}
-
-- (void)sendEvent:(NSEvent *)event
-{
-    [self retain];
-
-    bool handled = false;
-    switch([event type]) {
-    case NSMouseMoved:
-        // Cocoa sends move events to a parent and all its children under the mouse, much
-        // like Qt handles hover events. But we only want to handle the move event once, so
-        // to optimize a bit (since we subscribe for move event for all views), we handle it
-        // here before this logic happends. Note: it might be tempting to do this shortcut for
-        // all mouse events. The problem is that Cocoa does more than just find the correct view
-        // when sending the event, like raising windows etc. So avoid it as much as possible:
-        handled = qt_mac_handleMouseEvent(event, QEvent::MouseMove, Qt::NoButton, 0);
-        break;
-    default:
-        break;
-    }
-
-    if (!handled) {
-        [super sendEvent:event];
-        qt_mac_handleNonClientAreaMouseEvent(self, event);
-    }
-    [self release];
-}
-
-- (void)setInitialFirstResponder:(NSView *)view
-{
-    // This method is called the first time the window is placed on screen and
-    // is the earliest point in time we can connect OpenGL contexts to NSViews.
-    QWidget *qwidget = [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] qt_qwidgetForWindow:self];
-    if (qwidget) {
-        qt_event_request_window_change(qwidget);
-        qt_mac_send_posted_gl_updates(qwidget);
-    }
-
-    [super setInitialFirstResponder:view];
-}
-
-- (BOOL)makeFirstResponder:(NSResponder *)responder
-{
-    // For some reason Cocoa wants to flip the first responder
-    // when Qt doesn't want to, sorry, but "No" :-)
-    if (responder == nil && qApp->focusWidget())
-        return NO;
-    return [super makeFirstResponder:responder];
-}
-
-+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask
-{
-    if (styleMask & QtMacCustomizeWindow)
-        return [QT_MANGLE_NAMESPACE(QCocoaWindowCustomThemeFrame) class];
-    return [super frameViewClassForStyleMask:styleMask];
-}
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-- (void)touchesBeganWithEvent:(NSEvent *)event;
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetTouch = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch);
-    if (!widgetToGetTouch)
-        return;
-
-    bool all = widgetToGetTouch->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
-    qt_translateRawTouchEvent(widgetToGetTouch, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
-}
-
-- (void)touchesMovedWithEvent:(NSEvent *)event;
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetTouch = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch);
-    if (!widgetToGetTouch)
-        return;
-
-    bool all = widgetToGetTouch->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
-    qt_translateRawTouchEvent(widgetToGetTouch, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
-}
-
-- (void)touchesEndedWithEvent:(NSEvent *)event;
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetTouch = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch);
-    if (!widgetToGetTouch)
-        return;
-
-    bool all = widgetToGetTouch->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
-    qt_translateRawTouchEvent(widgetToGetTouch, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
-}
-
-- (void)touchesCancelledWithEvent:(NSEvent *)event;
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetTouch = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch);
-    if (!widgetToGetTouch)
-        return;
-
-    bool all = widgetToGetTouch->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
-    qt_translateRawTouchEvent(widgetToGetTouch, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
-}
-#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
--(void)registerDragTypes
-{
-    // Calling registerForDraggedTypes below is slow, so only do
-    // it once for each window, or when the custom types change.
-    QMacCocoaAutoReleasePool pool;
-    const QStringList& customTypes = qEnabledDraggedTypes();
-    if (currentCustomDragTypes == 0 || *currentCustomDragTypes != customTypes) {
-        if (currentCustomDragTypes == 0)
-            currentCustomDragTypes = new QStringList();
-        *currentCustomDragTypes = customTypes;
-        const NSString* mimeTypeGeneric = @"com.trolltech.qt.MimeTypeName";
-        NSMutableArray *supportedTypes = [NSMutableArray arrayWithObjects:NSColorPboardType,
-                       NSFilenamesPboardType, NSStringPboardType,
-                       NSFilenamesPboardType, NSPostScriptPboardType, NSTIFFPboardType,
-                       NSRTFPboardType, NSTabularTextPboardType, NSFontPboardType,
-                       NSRulerPboardType, NSFileContentsPboardType, NSColorPboardType,
-                       NSRTFDPboardType, NSHTMLPboardType, NSPICTPboardType,
-                       NSURLPboardType, NSPDFPboardType, NSVCardPboardType,
-                       NSFilesPromisePboardType, NSInkTextPboardType,
-                       NSMultipleTextSelectionPboardType, mimeTypeGeneric, nil];
-        // Add custom types supported by the application.
-        for (int i = 0; i < customTypes.size(); i++) {
-           [supportedTypes addObject:qt_mac_QStringToNSString(customTypes[i])];
-        }
-        [self registerForDraggedTypes:supportedTypes];
-    }
-}
-
-- (void)removeDropData
-{
-    if (dropData) {
-        delete dropData;
-        dropData = 0;
-    }
-}
-
-- (void)addDropData:(id <NSDraggingInfo>)sender
-{
-    [self removeDropData];
-    CFStringRef dropPasteboard = (CFStringRef) [[sender draggingPasteboard] name];
-    dropData = new QCocoaDropData(dropPasteboard);
-}
-
-- (void)changeDraggingCursor:(NSDragOperation)newOperation
-{
-    static SEL action = nil;
-    static bool operationSupported = false;
-    if (action == nil) {
-        action = NSSelectorFromString(@"operationNotAllowedCursor");
-        if ([NSCursor respondsToSelector:action]) {
-            operationSupported = true;
-        }
-    }
-    if (operationSupported) {
-        NSCursor *notAllowedCursor = [NSCursor performSelector:action];
-        bool isNotAllowedCursor = ([NSCursor currentCursor] == notAllowedCursor);
-        if (newOperation == NSDragOperationNone && !isNotAllowedCursor) {
-            [notAllowedCursor push];
-        } else if (newOperation != NSDragOperationNone && isNotAllowedCursor) {
-            [notAllowedCursor pop];
-        }
-
-    }
-}
-
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
-{
-    // The user dragged something into the window. Send a draggingEntered message
-    // to the QWidget under the mouse. As the drag moves over the window, and over
-    // different widgets, we will handle enter and leave events from within
-    // draggingUpdated below. The reason why we handle this ourselves rather than
-    // subscribing for drag events directly in QCocoaView is that calling
-    // registerForDraggedTypes on the views will severly degrade initialization time
-    // for an application that uses a lot of drag subscribing widgets.
-
-    NSPoint nswindowPoint = [sender draggingLocation];
-    NSPoint nsglobalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:nswindowPoint];
-    QPoint globalPoint = flipPoint(nsglobalPoint).toPoint();
-
-    QWidget *qwidget = QApplication::widgetAt(globalPoint);
-    *currentDragTarget() = qwidget;
-    if (!qwidget)
-        return NSDragOperationNone;
-    if (qwidget->testAttribute(Qt::WA_DropSiteRegistered) == false)
-        return NSDragOperationNone;
-
-    [self addDropData:sender];
-
-    QMimeData *mimeData = dropData;
-    if (QDragManager::self()->source())
-        mimeData = QDragManager::self()->dragPrivate()->data;
-
-    NSDragOperation nsActions = [sender draggingSourceOperationMask];
-    Qt::DropActions qtAllowed = qt_mac_mapNSDragOperations(nsActions);
-    QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) = nsActions;
-    Qt::KeyboardModifiers modifiers = Qt::NoModifier;
-
-    if ([sender draggingSource] != nil) {
-        // modifier flags might have changed, update it here since we don't send any input events.
-        QApplicationPrivate::modifier_buttons = qt_cocoaModifiers2QtModifiers([[[NSApplication sharedApplication] currentEvent] modifierFlags]);
-        modifiers = QApplication::keyboardModifiers();
-    } else {
-        // when the source is from another application the above technique will not work.
-        modifiers = qt_cocoaDragOperation2QtModifiers(nsActions);
-    }
-
-    // send the drag enter event to the widget.
-    QPoint localPoint(qwidget->mapFromGlobal(globalPoint));
-    QDragEnterEvent qDEEvent(localPoint, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
-    QApplication::sendEvent(qwidget, &qDEEvent);
-
-    if (!qDEEvent.isAccepted()) {
-        // The enter event was not accepted. We mark this by removing
-        // the drop data so we don't send subsequent drag move events:
-        [self removeDropData];
-        [self changeDraggingCursor:NSDragOperationNone];
-        return NSDragOperationNone;
-    } else {
-        // Send a drag move event immediately after a drag enter event (as per documentation).
-        QDragMoveEvent qDMEvent(localPoint, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
-        qDMEvent.setDropAction(qDEEvent.dropAction());
-        qDMEvent.accept(); // accept by default, since enter event was accepted.
-        QApplication::sendEvent(qwidget, &qDMEvent);
-
-        if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction) {
-            // Since we accepted the drag enter event, the widget expects
-            // future drage move events.
-            nsActions = NSDragOperationNone;
-            // Save as ignored in the answer rect.
-            qDMEvent.setDropAction(Qt::IgnoreAction);
-        } else {
-            nsActions = QT_PREPEND_NAMESPACE(qt_mac_mapDropAction)(qDMEvent.dropAction());
-        }
-
-        QT_PREPEND_NAMESPACE(qt_mac_copy_answer_rect)(qDMEvent);
-        [self changeDraggingCursor:nsActions];
-        return nsActions;
-    }
- }
-
-- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
-{
-    NSPoint nswindowPoint = [sender draggingLocation];
-    NSPoint nsglobalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:nswindowPoint];
-    QPoint globalPoint = flipPoint(nsglobalPoint).toPoint();
-
-    QWidget *qwidget = QApplication::widgetAt(globalPoint);
-    if (!qwidget)
-        return NSDragOperationNone;
-
-    // First, check if the widget under the mouse has changed since the
-    // last drag move events. If so, we need to change target, and dispatch
-    // syntetic drag enter/leave events:
-    if (qwidget != *currentDragTarget()) {
-        if (*currentDragTarget() && dropData) {
-            QDragLeaveEvent de;
-            QApplication::sendEvent(*currentDragTarget(), &de);
-            [self removeDropData];
-        }
-        return [self draggingEntered:sender];
-    }
-
-    if (qwidget->testAttribute(Qt::WA_DropSiteRegistered) == false)
-        return NSDragOperationNone;
-
-    // If we have no drop data (which will be assigned inside draggingEntered), it means
-    // that the current drag target did not accept the enter event. If so, we ignore
-    // subsequent move events as well:
-    if (dropData == 0) {
-        [self changeDraggingCursor:NSDragOperationNone];
-        return NSDragOperationNone;
-    }
-
-    // If the mouse is still within the accepted rect (provided by
-    // the application on a previous event), we follow the optimization
-    // and just return the answer given at that point:
-    NSDragOperation nsActions = [sender draggingSourceOperationMask];
-    QPoint localPoint(qwidget->mapFromGlobal(globalPoint));
-    if (qt_mac_mouse_inside_answer_rect(localPoint)
-        && QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) == nsActions) {
-        NSDragOperation operation = QT_PREPEND_NAMESPACE(qt_mac_mapDropActions)(QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastAction));
-        [self changeDraggingCursor:operation];
-        return operation;
-    }
-
-    QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) = nsActions;
-    Qt::DropActions qtAllowed = QT_PREPEND_NAMESPACE(qt_mac_mapNSDragOperations)(nsActions);
-    Qt::KeyboardModifiers modifiers  = Qt::NoModifier;
-
-    // Update modifiers:
-    if ([sender draggingSource] != nil) {
-        QApplicationPrivate::modifier_buttons = qt_cocoaModifiers2QtModifiers([[[NSApplication sharedApplication] currentEvent] modifierFlags]);
-        modifiers = QApplication::keyboardModifiers();
-    } else {
-        modifiers = qt_cocoaDragOperation2QtModifiers(nsActions);
-    }
-
-    QMimeData *mimeData = dropData;
-    if (QDragManager::self()->source())
-        mimeData = QDragManager::self()->dragPrivate()->data;
-
-    // Insert the same drop action on the event according to
-    // what the application told us it should be on the previous event:
-    QDragMoveEvent qDMEvent(localPoint, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
-    if (QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).lastAction != Qt::IgnoreAction
-        && QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).buttons == qDMEvent.mouseButtons()
-        && QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).modifiers == qDMEvent.keyboardModifiers())
-        qDMEvent.setDropAction(QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).lastAction);
-
-    // Now, end the drag move event to the widget:
-    qDMEvent.accept();
-    QApplication::sendEvent(qwidget, &qDMEvent);
-
-    NSDragOperation operation = qt_mac_mapDropAction(qDMEvent.dropAction());
-    if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction) {
-        // Ignore this event (we will still receive further
-        // notifications), save as ignored in the answer rect:
-        operation = NSDragOperationNone;
-        qDMEvent.setDropAction(Qt::IgnoreAction);
-    }
-
-    qt_mac_copy_answer_rect(qDMEvent);
-    [self changeDraggingCursor:operation];
-
-    return operation;
-}
-
-- (void)draggingExited:(id <NSDraggingInfo>)sender
-{
-    NSPoint nswindowPoint = [sender draggingLocation];
-    NSPoint nsglobalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:nswindowPoint];
-    QPoint globalPoint = flipPoint(nsglobalPoint).toPoint();
-
-    QWidget *qwidget = *currentDragTarget();
-    if (!qwidget)
-        return;
-
-    if (dropData) {
-        QDragLeaveEvent de;
-        QApplication::sendEvent(qwidget, &de);
-        [self removeDropData];
-    }
-
-    // Clean-up:
-    [self removeDropData];
-    *currentDragTarget() = 0;
-    [self changeDraggingCursor:NSDragOperationEvery];
-}
-
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
-{
-    QWidget *qwidget = *currentDragTarget();
-    if (!qwidget)
-        return NO;
-
-    *currentDragTarget() = 0;
-    NSPoint nswindowPoint = [sender draggingLocation];
-    NSPoint nsglobalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:nswindowPoint];
-    QPoint globalPoint = flipPoint(nsglobalPoint).toPoint();
-
-    [self addDropData:sender];
-
-    NSDragOperation nsActions = [sender draggingSourceOperationMask];
-    Qt::DropActions qtAllowed = qt_mac_mapNSDragOperations(nsActions);
-    QMimeData *mimeData = dropData;
-
-    if (QDragManager::self()->source())
-        mimeData = QDragManager::self()->dragPrivate()->data;
-    if (QDragManager::self()->object)
-        QDragManager::self()->dragPrivate()->target = qwidget;
-
-    QPoint localPoint(qwidget->mapFromGlobal(globalPoint));
-    QDropEvent de(localPoint, qtAllowed, mimeData,
-                  QApplication::mouseButtons(), QApplication::keyboardModifiers());
-    QApplication::sendEvent(qwidget, &de);
-
-    if (QDragManager::self()->object)
-        QDragManager::self()->dragPrivate()->executed_action = de.dropAction();
-
-    return de.isAccepted();
-}
-
-// This is a hack and it should be removed once we find the real cause for
-// the painting problems.
-// We have a static variable that signals if we have been called before or not.
-static bool firstDrawingInvocation = true;
-
-// The method below exists only as a workaround to draw/not draw the baseline
-// in the title bar. This is to support unifiedToolbar look.
-
-// This method is very special. To begin with, it is a
-// method that will get called only if we enable documentMode.
-// Furthermore, it won't get called as a normal method, we swap
-// this method with the normal implementation of drawRect in
-// _NSThemeFrame. When this method is active, its mission is to
-// first call the original drawRect implementation so the widget
-// gets proper painting. After that, it needs to detect if there
-// is a toolbar or not, in order to decide how to handle the unified
-// look. The distinction is important since the presence and
-// visibility of a toolbar change the way we enter into unified mode.
-// When there is a toolbar and that toolbar is visible, the problem
-// is as simple as to tell the toolbar not to draw its baseline.
-// However when there is not toolbar or the toolbar is not visible,
-// we need to draw a line on top of the baseline, because the baseline
-// in that case will belong to the title. For this case we need to draw
-// a line on top of the baseline.
-// As usual, there is a special case. When we first are called, we might
-// need to repaint ourselves one more time. We only need that if we
-// didn't get the activation, i.e. when we are launched via the command
-// line. And this only if the toolbar is visible from the beginning,
-// so we have a special flag that signals if we need to repaint or not.
-- (void)drawRectSpecial:(NSRect)rect
-{
-    // Call the original drawing method.
-    [id(self) drawRectOriginal:rect];
-    NSWindow *window = [id(self) window];
-    NSToolbar *toolbar = [window toolbar];
-    if(!toolbar) {
-        // There is no toolbar, we have to draw a line on top of the line drawn by Cocoa.
-        macDrawRectOnTop((void *)window);
-    } else {
-        if([toolbar isVisible]) {
-            // We tell Cocoa to avoid drawing the line at the end.
-            if(firstDrawingInvocation) {
-                firstDrawingInvocation = false;
-                macSyncDrawingOnFirstInvocation((void *)window);
-            } else
-                [toolbar setShowsBaselineSeparator:NO];
-        } else {
-            // There is a toolbar but it is not visible so
-            // we have to draw a line on top of the line drawn by Cocoa.
-            macDrawRectOnTop((void *)window);
-        }
-    }
-}
-
-- (void)drawRectOriginal:(NSRect)rect
-{
-    Q_UNUSED(rect)
-    // This method implementation is here to silenct the compiler.
-    // See drawRectSpecial for information.
-}
-
diff --git a/src/gui/kernel/qcocoaview_mac.mm b/src/gui/kernel/qcocoaview_mac.mm
deleted file mode 100644 (file)
index d57d45f..0000000
+++ /dev/null
@@ -1,1408 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include <qconfig.h>
-#import <qcocoaview_mac_p.h>
-#ifdef QT_MAC_USE_COCOA
-
-#include <qwidget_p.h>
-#include <qt_mac_p.h>
-#include <qapplication_p.h>
-#include <qabstractscrollarea_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qdnd_p.h>
-#include <qmacinputcontext_p.h>
-#include <qevent_p.h>
-#include <qbackingstore_p.h>
-#include <qwindowsurface_raster_p.h>
-#include <qunifiedtoolbarsurface_mac_p.h>
-
-#include <qscrollarea.h>
-#include <qhash.h>
-#include <qtextformat.h>
-#include <qpaintengine.h>
-#include <QUrl>
-#include <QAccessible>
-#include <QFileInfo>
-#include <QFile>
-
-#include <qdebug.h>
-
-@interface NSEvent (Qt_Compile_Leopard_DeviceDelta)
-  // SnowLeopard:
-  - (CGFloat)deviceDeltaX;
-  - (CGFloat)deviceDeltaY;
-  - (CGFloat)deviceDeltaZ;
-  // Lion:
-  - (CGFloat)scrollingDeltaX;
-  - (CGFloat)scrollingDeltaY;
-  - (CGFloat)scrollingDeltaZ;
-@end
-
-@interface NSEvent (Qt_Compile_Leopard_Gestures)
-  - (CGFloat)magnification;
-@end
-
-QT_BEGIN_NAMESPACE
-
-extern void qt_mac_update_cursor(); // qcursor_mac.mm
-extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); // qapplication.cpp
-extern QPointer<QWidget> qt_last_mouse_receiver; // qapplication_mac.cpp
-extern QPointer<QWidget> qt_last_native_mouse_receiver; // qt_cocoa_helpers_mac.mm
-extern OSViewRef qt_mac_nativeview_for(const QWidget *w); // qwidget_mac.mm
-extern OSViewRef qt_mac_effectiveview_for(const QWidget *w); // qwidget_mac.mm
-extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
-extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum);
-extern QWidget *mac_mouse_grabber;
-extern bool qt_mac_clearDirtyOnWidgetInsideDrawWidget; // qwidget.cpp
-
-static QColor colorFrom(NSColor *color)
-{
-    QColor qtColor;
-    NSString *colorSpace = [color colorSpaceName];
-    if (colorSpace == NSDeviceCMYKColorSpace) {
-        CGFloat cyan, magenta, yellow, black, alpha;
-        [color getCyan:&cyan magenta:&magenta yellow:&yellow black:&black alpha:&alpha];
-        qtColor.setCmykF(cyan, magenta, yellow, black, alpha);
-    } else {
-        NSColor *tmpColor;
-        tmpColor = [color colorUsingColorSpaceName:NSDeviceRGBColorSpace];
-        CGFloat red, green, blue, alpha;
-        [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
-        qtColor.setRgbF(red, green, blue, alpha);
-    }
-    return qtColor;
-}
-
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QMacCocoaAutoReleasePool)
-QT_FORWARD_DECLARE_CLASS(QCFString)
-QT_FORWARD_DECLARE_CLASS(QDragManager)
-QT_FORWARD_DECLARE_CLASS(QMimeData)
-QT_FORWARD_DECLARE_CLASS(QPoint)
-QT_FORWARD_DECLARE_CLASS(QApplication)
-QT_FORWARD_DECLARE_CLASS(QApplicationPrivate)
-QT_FORWARD_DECLARE_CLASS(QDragEnterEvent)
-QT_FORWARD_DECLARE_CLASS(QDragMoveEvent)
-QT_FORWARD_DECLARE_CLASS(QStringList)
-QT_FORWARD_DECLARE_CLASS(QString)
-QT_FORWARD_DECLARE_CLASS(QRect)
-QT_FORWARD_DECLARE_CLASS(QRegion)
-QT_FORWARD_DECLARE_CLASS(QAbstractScrollArea)
-QT_FORWARD_DECLARE_CLASS(QAbstractScrollAreaPrivate)
-QT_FORWARD_DECLARE_CLASS(QPaintEvent)
-QT_FORWARD_DECLARE_CLASS(QPainter)
-QT_FORWARD_DECLARE_CLASS(QHoverEvent)
-QT_FORWARD_DECLARE_CLASS(QCursor)
-QT_USE_NAMESPACE
-extern "C" {
-    extern NSString *NSTextInputReplacementRangeAttributeName;
-}
-
-//#define ALIEN_DEBUG 1
-#ifdef ALIEN_DEBUG
-static int qCocoaViewCount = 0;
-#endif
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaView)
-
-- (id)initWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate
-{
-    self = [super init];
-    if (self) {
-        [self finishInitWithQWidget:widget widgetPrivate:widgetprivate];
-    }
-    [self setFocusRingType:NSFocusRingTypeNone];
-    composingText = new QString();
-
-#ifdef ALIEN_DEBUG
-    ++qCocoaViewCount;
-    qDebug() << "Alien: create native view for" << widget << ". qCocoaViewCount is:" << qCocoaViewCount;
-#endif
-
-    composing = false;
-    sendKeyEvents = true;
-    fromKeyDownEvent = false;
-    alienTouchCount = 0;
-
-    [self setHidden:YES];
-    return self;
-}
-
-- (void) finishInitWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate
-{
-    qwidget = widget;
-    qwidgetprivate = widgetprivate;
-    [[NSNotificationCenter defaultCenter] addObserver:self
-                                             selector:@selector(frameDidChange:)
-                                                 name:@"NSViewFrameDidChangeNotification"
-                                               object:self];
-}
-
-- (void)dealloc
-{
-    QMacCocoaAutoReleasePool pool;
-    delete composingText;
-    [[NSNotificationCenter defaultCenter] removeObserver:self];
-
-#ifdef ALIEN_DEBUG
-    --qCocoaViewCount;
-    qDebug() << "Alien: widget deallocated. qCocoaViewCount is:" << qCocoaViewCount;
-#endif
-
-    [super dealloc];
-}
-
-- (BOOL)isOpaque
-{
-    if (!qwidgetprivate)
-        return [super isOpaque];
-    return qwidgetprivate->isOpaque;
-}
-
-- (BOOL)isFlipped
-{
-    return YES;
-}
-
-// We preserve the content of the view if WA_StaticContents is defined.
-//
-// More info in the Cocoa documentation:
-// http://developer.apple.com/mac/library/documentation/cocoa/conceptual/CocoaViewsGuide/Optimizing/Optimizing.html
-- (BOOL) preservesContentDuringLiveResize
-{
-    return qwidget->testAttribute(Qt::WA_StaticContents);
-}
-
-- (void) setFrameSize:(NSSize)newSize
-{
-    [super setFrameSize:newSize];
-
-    // A change in size has required the view to be invalidated.
-    if ([self inLiveResize]) {
-        NSRect rects[4];
-        NSInteger count;
-        [self getRectsExposedDuringLiveResize:rects count:&count];
-        while (count-- > 0)
-        {
-            [self setNeedsDisplayInRect:rects[count]];
-        }
-    } else {
-        [self setNeedsDisplay:YES];
-    }
-
-    // Make sure the opengl context is updated on resize.
-    if (qwidgetprivate && qwidgetprivate->isGLWidget && [self window]) {
-        qwidgetprivate->needWindowChange = true;
-        QEvent event(QEvent::MacGLWindowChange);
-        qApp->sendEvent(qwidget, &event);
-    }
-}
-
-// We catch the 'setNeedsDisplay:' message in order to avoid a useless full repaint.
-// During the resize, the top of the widget is repainted, probably because of the
-// change of coordinate space (Quartz vs Qt). This is then followed by this message:
-// -[NSView _setNeedsDisplayIfTopLeftChanged]
-// which force a full repaint by sending the message 'setNeedsDisplay:'.
-// That is what we are preventing here.
-- (void)setNeedsDisplay:(BOOL)flag {
-    if (![self inLiveResize] || !(qwidget->testAttribute(Qt::WA_StaticContents))) {
-        [super setNeedsDisplay:flag];
-    }
-}
-
-- (void)drawRect:(NSRect)aRect
-{
-    if (!qwidget)
-        return;
-
-    // Getting context.
-    CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
-    qt_mac_retain_graphics_context(context);
-
-    // We use a different graphics system.
-    //
-    // Widgets that are set to paint on screen, specifically QGLWidget,
-    // requires the native engine to execute in order to be drawn.
-    if (QApplicationPrivate::graphics_system != 0 && !qwidget->testAttribute(Qt::WA_PaintOnScreen)) {
-
-        // Raster engine.
-        if (QApplicationPrivate::graphics_system_name == QLatin1String("raster")) {
-
-            if (!qwidgetprivate->isInUnifiedToolbar) {
-
-                // Qt handles the painting occuring inside the window.
-                // Cocoa also keeps track of all widgets as NSView and therefore might
-                // ask for a repainting of a widget even if Qt is already taking care of it.
-                //
-                // The only valid reason for Cocoa to call drawRect: is for window manipulation
-                // (ie. resize, ...).
-                //
-                // Qt will then forward the update to the children.
-                if (!qwidget->isWindow()) {
-                    qt_mac_release_graphics_context(context);
-                    return;
-                }
-
-                QRasterWindowSurface *winSurface = dynamic_cast<QRasterWindowSurface *>(qwidget->windowSurface());
-                if (!winSurface || !winSurface->needsFlush) {
-                    qt_mac_release_graphics_context(context);
-                    return;
-                }
-
-                // Clip to region.
-                const QVector<QRect> &rects = winSurface->regionToFlush.rects();
-                for (int i = 0; i < rects.size(); ++i) {
-                    const QRect &rect = rects.at(i);
-                    CGContextAddRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height()));
-                }
-                CGContextClip(context);
-
-                QRect r = winSurface->regionToFlush.boundingRect();
-                const CGRect area = CGRectMake(r.x(), r.y(), r.width(), r.height());
-
-                qt_mac_draw_image(context, winSurface->imageContext(), area, area);
-
-                winSurface->needsFlush = false;
-                winSurface->regionToFlush = QRegion();
-
-            } else {
-
-                QUnifiedToolbarSurface *unifiedSurface = qwidgetprivate->unifiedSurface;
-                if (!unifiedSurface) {
-                    qt_mac_release_graphics_context(context);
-                    return;
-                }
-
-                int areaX = qwidgetprivate->toolbar_offset.x();
-                int areaY = qwidgetprivate->toolbar_offset.y();
-                int areaWidth = qwidget->geometry().width();
-                int areaHeight = qwidget->geometry().height();
-                const CGRect area = CGRectMake(areaX, areaY, areaWidth, areaHeight);
-                const CGRect drawingArea = CGRectMake(0, 0, areaWidth, areaHeight);
-
-                qt_mac_draw_image(context, unifiedSurface->imageContext(), area, drawingArea);
-
-                qwidgetprivate->flushRequested = false;
-
-            }
-
-            CGContextSynchronize(context);
-            qt_mac_release_graphics_context(context);
-            return;
-        }
-
-        // Qt handles the painting occuring inside the window.
-        // Cocoa also keeps track of all widgets as NSView and therefore might
-        // ask for a repainting of a widget even if Qt is already taking care of it.
-        //
-        // The only valid reason for Cocoa to call drawRect: is for window manipulation
-        // (ie. resize, ...).
-        //
-        // Qt will then forward the update to the children.
-        if (qwidget->isWindow()) {
-            qwidget->update(qwidget->rect());
-            qwidgetprivate->syncBackingStore(qwidget->rect());
-        }
-    }
-
-    // Native engine.
-    qwidgetprivate->hd = context;
-
-    if (qwidget->isVisible() && qwidget->updatesEnabled()) { //process the actual paint event.
-        if (qwidget->testAttribute(Qt::WA_WState_InPaintEvent))
-            qWarning("QWidget::repaint: Recursive repaint detected");
-
-        const QRect qrect = QRect(aRect.origin.x, aRect.origin.y, aRect.size.width, aRect.size.height);
-        QRegion qrgn;
-
-        const NSRect *rects;
-        NSInteger count;
-        [self getRectsBeingDrawn:&rects count:&count];
-        for (int i = 0; i < count; ++i) {
-            QRect tmpRect = QRect(rects[i].origin.x, rects[i].origin.y, rects[i].size.width, rects[i].size.height);
-            qrgn += tmpRect;
-        }
-
-        if (!qwidget->isWindow() && !qobject_cast<QAbstractScrollArea *>(qwidget->parent())) {
-            const QRegion &parentMask = qwidget->window()->mask();
-            if (!parentMask.isEmpty()) {
-                const QPoint mappedPoint = qwidget->mapTo(qwidget->window(), qrect.topLeft());
-                qrgn.translate(mappedPoint);
-                qrgn &= parentMask;
-                qrgn.translate(-mappedPoint.x(), -mappedPoint.y());
-            }
-        }
-
-        QPoint redirectionOffset(0, 0);
-        //setup the context
-        qwidget->setAttribute(Qt::WA_WState_InPaintEvent);
-        QPaintEngine *engine = qwidget->paintEngine();
-        if (engine)
-            engine->setSystemClip(qrgn);
-        if (qwidgetprivate->extra && qwidgetprivate->extra->hasMask) {
-            CGRect widgetRect = CGRectMake(0, 0, qwidget->width(), qwidget->height());
-            CGContextTranslateCTM (context, 0, widgetRect.size.height);
-            CGContextScaleCTM(context, 1, -1);
-            if (qwidget->isWindow())
-                CGContextClearRect(context, widgetRect);
-            CGContextClipToMask(context, widgetRect, qwidgetprivate->extra->imageMask);
-            CGContextScaleCTM(context, 1, -1);
-            CGContextTranslateCTM (context, 0, -widgetRect.size.height);
-        }
-
-        if (qwidget->isWindow() && !qwidgetprivate->isOpaque
-            && !qwidget->testAttribute(Qt::WA_MacBrushedMetal)) {
-            CGContextClearRect(context, NSRectToCGRect(aRect));
-        }
-
-        qwidget->setAttribute(Qt::WA_WState_InPaintEvent, false);
-        QWidgetPrivate *qwidgetPrivate = qt_widget_private(qwidget);
-
-        // We specify that we want to draw the widget itself, and
-        // all its children recursive. But we skip native children, because
-        // they will receive drawRect calls by themselves as needed:
-        int flags = QWidgetPrivate::DrawPaintOnScreen
-            | QWidgetPrivate::DrawRecursive
-            | QWidgetPrivate::DontDrawNativeChildren;
-
-        if (qwidget->isWindow())
-            flags |= QWidgetPrivate::DrawAsRoot;
-
-        // Start to draw:
-        qt_mac_clearDirtyOnWidgetInsideDrawWidget = true;
-        qwidgetPrivate->drawWidget(qwidget, qrgn, QPoint(), flags, 0);
-        qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
-
-        if (!redirectionOffset.isNull())
-            QPainter::restoreRedirected(qwidget);
-        if (engine)
-            engine->setSystemClip(QRegion());
-        qwidget->setAttribute(Qt::WA_WState_InPaintEvent, false);
-        if(!qwidget->testAttribute(Qt::WA_PaintOutsidePaintEvent) && qwidget->paintingActive())
-            qWarning("QWidget: It is dangerous to leave painters active on a"
-            " widget outside of the PaintEvent");
-    }
-    qwidgetprivate->hd = 0;
-    qt_mac_release_graphics_context(context);
-}
-
-- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
-{
-    // Find the widget that should receive the event:
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetMouse = qt_mac_getTargetForMouseEvent(theEvent, QEvent::MouseButtonPress, qlocal, qglobal, qwidget, 0);
-    if (!widgetToGetMouse)
-        return NO;
-
-    return !widgetToGetMouse->testAttribute(Qt::WA_MacNoClickThrough);
-}
-
-- (NSView *)hitTest:(NSPoint)aPoint
-{
-    if (!qwidget)
-        return [super hitTest:aPoint];
-
-    if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents))
-        return nil; // You cannot hit a transparent for mouse event widget.
-    return [super hitTest:aPoint];
-}
-
-- (void)updateTrackingAreas
-{
-    if (!qwidget)
-        return;
-
-    // [NSView addTrackingArea] is slow, so bail out early if we can:
-    if (NSIsEmptyRect([self visibleRect]))
-        return;
-
-    QMacCocoaAutoReleasePool pool;
-    if (NSArray *trackingArray = [self trackingAreas]) {
-        NSUInteger size = [trackingArray count];
-        for (NSUInteger i = 0; i < size; ++i) {
-            NSTrackingArea *t = [trackingArray objectAtIndex:i];
-            [self removeTrackingArea:t];
-        }
-    }
-
-    // Ideally, we shouldn't have NSTrackingMouseMoved events included below, it should
-    // only be turned on if mouseTracking, hover is on or a tool tip is set.
-    // Unfortunately, Qt will send "tooltip" events on mouse moves, so we need to
-    // turn it on in ALL case. That means EVERY QCocoaView gets to pay the cost of
-    // mouse moves delivered to it (Apple recommends keeping it OFF because there
-    // is a performance hit). So it goes.
-    NSUInteger trackingOptions = NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp
-                                 | NSTrackingInVisibleRect | NSTrackingMouseMoved;
-    NSTrackingArea *ta = [[NSTrackingArea alloc] initWithRect:NSMakeRect(0, 0,
-                                                                         qwidget->width(),
-                                                                         qwidget->height())
-                                                      options:trackingOptions
-                                                        owner:self
-                                                     userInfo:nil];
-    [self addTrackingArea:ta];
-    [ta release];
-}
-
-- (void)mouseEntered:(NSEvent *)event
-{
-    // Cocoa will not send a move event on mouseEnter. But since
-    // Qt expect this, we fake one now. See also mouseExited below
-    // for info about enter/leave event handling
-    NSEvent *nsmoveEvent = [NSEvent
-        mouseEventWithType:NSMouseMoved
-        location:[[self window] mouseLocationOutsideOfEventStream]
-        modifierFlags: [event modifierFlags]
-        timestamp: [event timestamp]
-        windowNumber: [event windowNumber]
-        context: [event context]
-        eventNumber: [event eventNumber]
-        clickCount: 0
-        pressure: 0];
-
-    // Important: Cocoa sends us mouseEnter on all views under the mouse
-    // and not just the one on top. Therefore, to we cannot use qwidget
-    // as native widget for this case. Instead, we let qt_mac_handleMouseEvent
-    // resolve it (last argument set to 0):
-    qt_mac_handleMouseEvent(nsmoveEvent, QEvent::MouseMove, Qt::NoButton, 0, true);
-}
-
-- (void)mouseExited:(NSEvent *)event
-{
-    // Note: normal enter/leave handling is done from within mouseMove. This handler
-    // catches the case when the mouse moves out of the window (which mouseMove do not).
-    // Updating the mouse cursor follows the same logic as enter/leave. And we update
-    // neither if a grab exists (even if the grab points to this widget, it seems, ref X11)
-    Q_UNUSED(event);
-    if (self == [[self window] contentView] && !qt_button_down && !QWidget::mouseGrabber()) {
-        qt_mac_update_cursor();
-        // If the mouse exits the content view, but qt_mac_getTargetForMouseEvent still
-        // reports a target, it means that either there is a grab involved, or the mouse
-        // hovered over another window in the application. In both cases, move events will
-        // cause qt_mac_handleMouseEvent to be called, which will handle enter/leave.
-        QPoint qlocal, qglobal;
-        QWidget *widgetUnderMouse = 0;
-        qt_mac_getTargetForMouseEvent(event, QEvent::Leave, qlocal, qglobal, qwidget, &widgetUnderMouse);
-
-        if (widgetUnderMouse == 0) {
-            QApplicationPrivate::dispatchEnterLeave(0, qt_last_mouse_receiver);
-            qt_last_mouse_receiver = 0;
-            qt_last_native_mouse_receiver = 0;
-        }
-    }
-}
-
-- (void)flagsChanged:(NSEvent *)theEvent
-{
-    QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
-    if (!widgetToGetKey)
-        return;
-
-    qt_dispatchModifiersChanged(theEvent, widgetToGetKey);
-    [super flagsChanged:theEvent];
-}
-
-- (void)mouseMoved:(NSEvent *)theEvent
-{
-    // Important: this method will only be called when the view's window is _not_ inside
-    // QCocoaWindow/QCocoaPanel. Otherwise, [QCocoaWindow sendEvent] will handle the event
-    // before it ends up here. So, this method is added for supporting QMacNativeWidget.
-    // TODO: Cocoa send move events to all views under the mouse. So make sure we only
-    // handle the event for the widget on top when using QMacNativeWidget.
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseMove, Qt::NoButton, qwidget);
-}
-
-- (void)mouseDown:(NSEvent *)theEvent
-{
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonPress, Qt::LeftButton, qwidget);
-    // Don't call super here. This prevents us from getting the mouseUp event,
-    // which we need to send even if the mouseDown event was not accepted.
-    // (this is standard Qt behavior.)
-}
-
-- (void)mouseUp:(NSEvent *)theEvent
-{
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonRelease, Qt::LeftButton, qwidget);
-}
-
-- (void)rightMouseDown:(NSEvent *)theEvent
-{
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonPress, Qt::RightButton, qwidget);
-}
-
-- (void)rightMouseUp:(NSEvent *)theEvent
-{
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonRelease, Qt::RightButton, qwidget);
-}
-
-- (void)otherMouseDown:(NSEvent *)theEvent
-{
-    Qt::MouseButton mouseButton = cocoaButton2QtButton([theEvent buttonNumber]);
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseButtonPress, mouseButton, qwidget);
-}
-
-- (void)otherMouseUp:(NSEvent *)theEvent
-{
-    Qt::MouseButton mouseButton = cocoaButton2QtButton([theEvent buttonNumber]);
-    qt_mac_handleMouseEvent(theEvent,  QEvent::MouseButtonRelease, mouseButton, qwidget);
-}
-
-- (void)mouseDragged:(NSEvent *)theEvent
-{
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseMove, Qt::NoButton, qwidget);
-}
-
-- (void)rightMouseDragged:(NSEvent *)theEvent
-{
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseMove, Qt::NoButton, qwidget);
-}
-
-- (void)otherMouseDragged:(NSEvent *)theEvent
-{
-    qt_mac_handleMouseEvent(theEvent, QEvent::MouseMove, Qt::NoButton, qwidget);
-}
-
-- (void)scrollWheel:(NSEvent *)theEvent
-{
-    // Give the Input Manager a chance to process the wheel event.
-    NSInputManager *currentIManager = [NSInputManager currentInputManager];
-    if (currentIManager && [currentIManager wantsToHandleMouseEvents]) {
-        [currentIManager handleMouseEvent:theEvent];
-    }
-
-    Qt::MouseButtons buttons = QApplication::mouseButtons();
-    Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([theEvent modifierFlags]);
-
-    // Find the widget that should receive the event:
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetMouse = qt_mac_getTargetForMouseEvent(theEvent, QEvent::Wheel, qlocal, qglobal, qwidget, 0);
-    if (!widgetToGetMouse)
-        return;
-
-    int deltaX = 0;
-    int deltaY = 0;
-
-    const EventRef carbonEvent = (EventRef)[theEvent eventRef];
-    const UInt32 carbonEventKind = carbonEvent ? ::GetEventKind(carbonEvent) : 0;
-    const bool scrollEvent = carbonEventKind == kEventMouseScroll;
-
-    if (scrollEvent) {
-        // The mouse device containts pixel scroll wheel support (Mighty Mouse, Trackpad).
-        // Since deviceDelta is delivered as pixels rather than degrees, we need to
-        // convert from pixels to degrees in a sensible manner.
-        // It looks like 1/4 degrees per pixel behaves most native.
-        // (NB: Qt expects the unit for delta to be 8 per degree):
-        const int pixelsToDegrees = 2; // 8 * 1/4
-        if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_6) {
-            // Mac OS 10.6
-            deltaX = [theEvent deviceDeltaX] * pixelsToDegrees;
-            deltaY = [theEvent deviceDeltaY] * pixelsToDegrees;
-        } else {
-            // Mac OS 10.7+
-            deltaX = [theEvent scrollingDeltaX] * pixelsToDegrees;
-            deltaY = [theEvent scrollingDeltaY] * pixelsToDegrees;
-        }
-    } else {
-        // carbonEventKind == kEventMouseWheelMoved
-        // Remove acceleration, and use either -120 or 120 as delta:
-        deltaX = qBound(-120, int([theEvent deltaX] * 10000), 120);
-        deltaY = qBound(-120, int([theEvent deltaY] * 10000), 120);
-    }
-
-#ifndef QT_NO_WHEELEVENT
-    // ### Qt 5: Send one QWheelEvent with dx, dy and dz
-
-    if (deltaX != 0 && deltaY != 0)
-        QMacScrollOptimization::initDelayedScroll();
-
-    if (deltaX != 0) {
-        QWheelEvent qwe(qlocal, qglobal, deltaX, buttons, keyMods, Qt::Horizontal);
-        qt_sendSpontaneousEvent(widgetToGetMouse, &qwe);
-    }
-
-    if (deltaY != 0) {
-        QWheelEvent qwe(qlocal, qglobal, deltaY, buttons, keyMods, Qt::Vertical);
-        qt_sendSpontaneousEvent(widgetToGetMouse, &qwe);
-    }
-
-    if (deltaX != 0 && deltaY != 0)
-        QMacScrollOptimization::performDelayedScroll();
-#endif //QT_NO_WHEELEVENT
-}
-
-- (void)tabletProximity:(NSEvent *)tabletEvent
-{
-    qt_dispatchTabletProximityEvent(tabletEvent);
-}
-
-- (void)tabletPoint:(NSEvent *)tabletEvent
-{
-    if (!qt_mac_handleTabletEvent(self, tabletEvent))
-        [super tabletPoint:tabletEvent];
-}
-
-- (void)magnifyWithEvent:(NSEvent *)event
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetGesture = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
-    if (!widgetToGetGesture)
-        return;
-    if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
-        return;
-
-#ifndef QT_NO_GESTURES
-    QNativeGestureEvent qNGEvent;
-    qNGEvent.gestureType = QNativeGestureEvent::Zoom;
-    NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
-    qNGEvent.position = flipPoint(p).toPoint();
-    qNGEvent.percentage = [event magnification];
-    qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-#endif // QT_NO_GESTURES
-}
-
-- (void)rotateWithEvent:(NSEvent *)event
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetGesture = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
-    if (!widgetToGetGesture)
-        return;
-    if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
-        return;
-
-#ifndef QT_NO_GESTURES
-    QNativeGestureEvent qNGEvent;
-    qNGEvent.gestureType = QNativeGestureEvent::Rotate;
-    NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
-    qNGEvent.position = flipPoint(p).toPoint();
-    qNGEvent.percentage = -[event rotation];
-    qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-#endif // QT_NO_GESTURES
-}
-
-- (void)swipeWithEvent:(NSEvent *)event
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetGesture = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
-    if (!widgetToGetGesture)
-        return;
-    if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
-        return;
-
-#ifndef QT_NO_GESTURES
-    QNativeGestureEvent qNGEvent;
-    qNGEvent.gestureType = QNativeGestureEvent::Swipe;
-    NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
-    qNGEvent.position = flipPoint(p).toPoint();
-    if ([event deltaX] == 1)
-        qNGEvent.angle = 180.0f;
-    else if ([event deltaX] == -1)
-        qNGEvent.angle = 0.0f;
-    else if ([event deltaY] == 1)
-        qNGEvent.angle = 90.0f;
-    else if ([event deltaY] == -1)
-        qNGEvent.angle = 270.0f;
-    qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-#endif // QT_NO_GESTURES
-}
-
-- (void)beginGestureWithEvent:(NSEvent *)event
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetGesture = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
-    if (!widgetToGetGesture)
-        return;
-    if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
-        return;
-
-#ifndef QT_NO_GESTURES
-    QNativeGestureEvent qNGEvent;
-    qNGEvent.gestureType = QNativeGestureEvent::GestureBegin;
-    NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
-    qNGEvent.position = flipPoint(p).toPoint();
-    qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-#endif // QT_NO_GESTURES
-}
-
-- (void)endGestureWithEvent:(NSEvent *)event
-{
-    QPoint qlocal, qglobal;
-    QWidget *widgetToGetGesture = 0;
-    qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, qwidget, &widgetToGetGesture);
-    if (!widgetToGetGesture)
-        return;
-    if (!QApplicationPrivate::tryModalHelper(widgetToGetGesture, 0))
-        return;
-
-#ifndef QT_NO_GESTURES
-    QNativeGestureEvent qNGEvent;
-    qNGEvent.gestureType = QNativeGestureEvent::GestureEnd;
-    NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
-    qNGEvent.position = flipPoint(p).toPoint();
-    qt_sendSpontaneousEvent(widgetToGetGesture, &qNGEvent);
-}
-#endif // QT_NO_GESTURES
-
-- (void)frameDidChange:(NSNotification *)note
-{
-    Q_UNUSED(note);
-    if (!qwidget)
-        return;
-    if (qwidget->isWindow())
-        return;
-    NSRect newFrame = [self frame];
-    QRect newGeo(newFrame.origin.x, newFrame.origin.y, newFrame.size.width, newFrame.size.height);
-    bool moved = qwidget->testAttribute(Qt::WA_Moved);
-    bool resized = qwidget->testAttribute(Qt::WA_Resized);
-    qwidget->setGeometry(newGeo);
-    qwidget->setAttribute(Qt::WA_Moved, moved);
-    qwidget->setAttribute(Qt::WA_Resized, resized);
-    qwidgetprivate->syncCocoaMask();
-}
-
-- (BOOL)isEnabled
-{
-    if (!qwidget)
-        return [super isEnabled];
-    return [super isEnabled] && qwidget->isEnabled();
-}
-
-- (void)setEnabled:(BOOL)flag
-{
-    QMacCocoaAutoReleasePool pool;
-    [super setEnabled:flag];
-    if (qwidget && qwidget->isEnabled() != flag)
-        qwidget->setEnabled(flag);
-}
-
-+ (Class)cellClass
-{
-    return [NSActionCell class];
-}
-
-- (BOOL)acceptsFirstResponder
-{
-    if (!qwidget)
-        return NO;
-
-    // Disabled widget shouldn't get focus even if it's a window.
-    // hence disabled windows will not get any key or mouse events.
-    if (!qwidget->isEnabled())
-        return NO;
-
-    if (qwidget->isWindow() && !qt_widget_private(qwidget)->topData()->embedded) {
-        QWidget *focusWidget = qApp->focusWidget();
-        if (!focusWidget) {
-            // There is no focus widget, but we still want to receive key events
-            // for shortcut handling etc. So we accept first responer for the
-            // content view as a last resort:
-            return YES;
-        }
-        if (!focusWidget->internalWinId() && focusWidget->nativeParentWidget() == qwidget) {
-            // The current focus widget is alien, and hence, cannot get acceptsFirstResponder
-            // calls. Since the focus widget is a child of qwidget, we let this view say YES:
-            return YES;
-        }
-        if (focusWidget->window() != qwidget) {
-            // The current focus widget is in another window. Since cocoa
-            // suggest that this window should be key now, we accept:
-            return YES;
-        }
-    }
-
-    return qwidget->focusPolicy() != Qt::NoFocus;
-}
-
-- (BOOL)resignFirstResponder
-{
-    if (!qwidget)
-        return YES;
-
-    // Seems like the following test only triggers if this
-    // view is inside a QMacNativeWidget:
-//    if (QWidget *fw = QApplication::focusWidget()) {
-//        if (qwidget == fw || qwidget == fw->nativeParentWidget())
-//            fw->clearFocus();
-//    }
-    return YES;
-}
-
-- (BOOL)becomeFirstResponder
-{
-    // see the comment in the acceptsFirstResponder - if the window "stole" focus
-    // let it become the responder, but don't tell Qt
-    if (qwidget && qt_widget_private(qwidget->window())->topData()->embedded
-        && !QApplication::focusWidget() && qwidget->focusPolicy() != Qt::NoFocus)
-        qwidget->setFocus(Qt::OtherFocusReason);
-    return YES;
-}
-
-- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
-{
-    Q_UNUSED(isLocal);
-    return supportedActions;
-}
-
-- (void)setSupportedActions:(NSDragOperation)actions
-{
-    supportedActions = actions;
-}
-
-- (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
-{
-    Q_UNUSED(anImage);
-    Q_UNUSED(aPoint);
-    macCurrentDnDParameters()->performedAction = operation;
-    if (QDragManager::self()->object
-        && QDragManager::self()->dragPrivate()->executed_action != Qt::ActionMask) {
-        macCurrentDnDParameters()->performedAction =
-            qt_mac_mapDropAction(QDragManager::self()->dragPrivate()->executed_action);
-    }
-}
-
-- (QWidget *)qt_qwidget
-{
-    return qwidget;
-}
-
-- (void) qt_clearQWidget
-{
-    qwidget = 0;
-    qwidgetprivate = 0;
-}
-
-- (void)keyDown:(NSEvent *)theEvent
-{
-    if (!qwidget)
-        return;
-    QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
-    if (!widgetToGetKey)
-        return;
-
-    sendKeyEvents = true;
-
-    if (widgetToGetKey->testAttribute(Qt::WA_InputMethodEnabled)
-            && !(widgetToGetKey->inputMethodHints() & Qt::ImhDigitsOnly
-                 || widgetToGetKey->inputMethodHints() & Qt::ImhFormattedNumbersOnly
-                 || widgetToGetKey->inputMethodHints() & Qt::ImhHiddenText)) {
-        fromKeyDownEvent = true;
-        [qt_mac_nativeview_for(qwidget) interpretKeyEvents:[NSArray arrayWithObject: theEvent]];
-        fromKeyDownEvent = false;
-    }
-
-    if (sendKeyEvents && !composing) {
-        bool keyEventEaten = qt_dispatchKeyEvent(theEvent, widgetToGetKey);
-        if (!keyEventEaten && qwidget) {
-            // The event is not yet eaten, and if Qt is embedded inside a native
-            // cocoa application, send it to first responder not owned by Qt.
-            // The exception is if widgetToGetKey was redirected to a popup.
-            QWidget *toplevel = qwidget->window();
-            if (toplevel == widgetToGetKey->window()) {
-                if (qt_widget_private(toplevel)->topData()->embedded) {
-                    if (NSResponder *w = [qt_mac_nativeview_for(toplevel) superview])
-                        [w keyDown:theEvent];
-                }
-            }
-        }
-    }
-}
-
-
-- (void)keyUp:(NSEvent *)theEvent
-{
-    if (sendKeyEvents) {
-        QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
-        if (!widgetToGetKey)
-            return;
-
-        bool keyEventEaten = qt_dispatchKeyEvent(theEvent, widgetToGetKey);
-        if (!keyEventEaten && qwidget) {
-            // The event is not yet eaten, and if Qt is embedded inside a native
-            // cocoa application, send it to first responder not owned by Qt.
-            // The exception is if widgetToGetKey was redirected to a popup.
-            QWidget *toplevel = qwidget->window();
-            if (toplevel == widgetToGetKey->window()) {
-                if (qt_widget_private(toplevel)->topData()->embedded) {
-                    if (NSResponder *w = [qt_mac_nativeview_for(toplevel) superview])
-                        [w keyUp:theEvent];
-                }
-            }
-        }
-    }
-}
-
-- (void)viewWillMoveToWindow:(NSWindow *)window
-{
-    if (qwidget == 0)
-        return;
-
-    if (qwidget->windowFlags() & Qt::MSWindowsOwnDC
-          && (window != [self window])) { // OpenGL Widget
-        QEvent event(QEvent::MacGLClearDrawable);
-        qApp->sendEvent(qwidget, &event);
-    }
-}
-
-- (void)viewDidMoveToWindow
-{
-    if (qwidget == 0)
-        return;
-
-    if (qwidget->windowFlags() & Qt::MSWindowsOwnDC && [self window]) {
-        // call update paint event
-        qwidgetprivate->needWindowChange = true;
-        QEvent event(QEvent::MacGLWindowChange);
-        qApp->sendEvent(qwidget, &event);
-    }
-}
-
-
-// NSTextInput Protocol implementation
-
-- (void) insertText:(id)aString
-{
-    QString commitText;
-    if ([aString length]) {
-        if ([aString isKindOfClass:[NSAttributedString class]]) {
-            commitText = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string]));
-        } else {
-            commitText = QCFString::toQString(reinterpret_cast<CFStringRef>(aString));
-        };
-    }
-
-    // When entering characters through Character Viewer or Keyboard Viewer, the text is passed
-    // through this insertText method. Since we dont receive a keyDown Event in such cases, the
-    // composing flag will be false.
-    //
-    // Characters can be sent through input method directly without composing process as well,
-    // for instance a Chinese input method will send "," (U+FF0C) to insertText: when "," key
-    // is pressed. In that case we want to set commit string directly instead of going through
-    // key events handling again. Hence we only leave the string with Unicode value less than
-    // 256 to the key events handling process.
-    if (([aString length] && (composing || commitText.at(0).unicode() > 0xff)) || !fromKeyDownEvent) {
-        // Send the commit string to the widget.
-        QInputMethodEvent e;
-        e.setCommitString(commitText);
-        QWidget *widgetToGetKey = 0;
-        if (!composing || qApp->focusWidget())
-            widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
-#ifndef QT_NO_IM
-        else if (QMacInputContext *mic = qobject_cast<QMacInputContext *>(qApp->inputContext()))
-            widgetToGetKey = mic->lastFocusWidget();
-#endif
-        if (widgetToGetKey)
-            qt_sendSpontaneousEvent(widgetToGetKey, &e);
-        composing = false;
-        sendKeyEvents = false;
-    } else {
-        // The key sequence "`q" on a French Keyboard will generate two calls to insertText before
-        // it returns from interpretKeyEvents. The first call will turn off 'composing' and accept
-        // the "`" key. The last keyDown event needs to be processed by the widget to get the
-        // character "q". The string parameter is ignored for the second call.
-        sendKeyEvents = true;
-    }
-
-    composingText->clear();
-}
-
-- (void) setMarkedText:(id)aString selectedRange:(NSRange)selRange
-{
-    // Generate the QInputMethodEvent with preedit string and the attributes
-    // for rendering it. The attributes handled here are 'underline',
-    // 'underline color' and 'cursor position'.
-    sendKeyEvents = false;
-    composing = true;
-    QString qtText;
-    // Cursor position is retrived from the range.
-    QList<QInputMethodEvent::Attribute> attrs;
-    attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, selRange.location + selRange.length, 1, QVariant());
-    if ([aString isKindOfClass:[NSAttributedString class]]) {
-        qtText = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string]));
-        composingLength = qtText.length();
-        int index = 0;
-        // Create attributes for individual sections of preedit text
-        while (index < composingLength) {
-            NSRange effectiveRange;
-            NSRange range = NSMakeRange(index, composingLength-index);
-            NSDictionary *attributes = [aString attributesAtIndex:index
-                                            longestEffectiveRange:&effectiveRange
-                                                          inRange:range];
-            NSNumber *underlineStyle = [attributes objectForKey:NSUnderlineStyleAttributeName];
-            if (underlineStyle) {
-                QColor clr (Qt::black);
-                NSColor *color = [attributes objectForKey:NSUnderlineColorAttributeName];
-                if (color) {
-                    clr = colorFrom(color);
-                }
-                QTextCharFormat format;
-                format.setFontUnderline(true);
-                format.setUnderlineColor(clr);
-                attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
-                                                    effectiveRange.location,
-                                                    effectiveRange.length,
-                                                    format);
-            }
-            index = effectiveRange.location + effectiveRange.length;
-        }
-    } else {
-        // No attributes specified, take only the preedit text.
-        qtText = QCFString::toQString(reinterpret_cast<CFStringRef>(aString));
-        composingLength = qtText.length();
-    }
-    // Make sure that we have at least one text format.
-    if (attrs.size() <= 1) {
-        QTextCharFormat format;
-        format.setFontUnderline(true);
-        attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
-                                            0, composingLength, format);
-    }
-    *composingText = qtText;
-
-    QInputMethodEvent e(qtText, attrs);
-    if (QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget))
-        qt_sendSpontaneousEvent(widgetToGetKey, &e);
-
-    if (!composingLength)
-        composing = false;
-}
-
-- (void) unmarkText
-{
-    if (composing) {
-        QInputMethodEvent e;
-        e.setCommitString(*composingText);
-        if (QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget))
-            qt_sendSpontaneousEvent(widgetToGetKey, &e);
-    }
-    composingText->clear();
-    composing = false;
-}
-
-- (BOOL) hasMarkedText
-{
-    return (composing ? YES: NO);
-}
-
-- (void) doCommandBySelector:(SEL)aSelector
-{
-    Q_UNUSED(aSelector);
-}
-
-- (BOOL)isComposing
-{
-    return composing;
-}
-
-- (NSInteger) conversationIdentifier
-{
-    // Return a unique identifier fot this ime conversation
-    return (NSInteger)self;
-}
-
-- (NSAttributedString *) attributedSubstringFromRange:(NSRange)theRange
-{
-    QString selectedText(qwidget->inputMethodQuery(Qt::ImCurrentSelection).toString());
-    if (!selectedText.isEmpty()) {
-        QCFString string(selectedText.mid(theRange.location, theRange.length));
-        const NSString *tmpString = reinterpret_cast<const NSString *>((CFStringRef)string);
-        return [[[NSAttributedString alloc]  initWithString:const_cast<NSString *>(tmpString)] autorelease];
-    } else {
-        return nil;
-    }
-}
-
-- (NSRange) markedRange
-{
-    NSRange range;
-    if (composing) {
-        range.location = 0;
-        range.length = composingLength;
-    } else {
-        range.location = NSNotFound;
-        range.length = 0;
-    }
-    return range;
-}
-
-- (NSRange) selectedRange
-{
-    NSRange selRange;
-    QString selectedText(qwidget->inputMethodQuery(Qt::ImCurrentSelection).toString());
-    if (!selectedText.isEmpty()) {
-        // Consider only the selected text.
-        selRange.location = 0;
-        selRange.length = selectedText.length();
-    } else {
-        // No selected text.
-        selRange.location = NSNotFound;
-        selRange.length = 0;
-    }
-    return selRange;
-
-}
-
-- (NSRect) firstRectForCharacterRange:(NSRange)theRange
-{
-    Q_UNUSED(theRange);
-    // The returned rect is always based on the internal cursor.
-    QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
-    if (!widgetToGetKey)
-        return NSZeroRect;
-
-    QRect mr(widgetToGetKey->inputMethodQuery(Qt::ImMicroFocus).toRect());
-    QPoint mp(widgetToGetKey->mapToGlobal(QPoint(mr.bottomLeft())));
-    NSRect rect ;
-    rect.origin.x = mp.x();
-    rect.origin.y = flipYCoordinate(mp.y());
-    rect.size.width = mr.width();
-    rect.size.height = mr.height();
-    return rect;
-}
-
-- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
-{
-    // We dont support cursor movements using mouse while composing.
-    Q_UNUSED(thePoint);
-    return NSNotFound;
-}
-
-- (NSArray*) validAttributesForMarkedText
-{
-    QWidget *widgetToGetKey = qt_mac_getTargetForKeyEvent(qwidget);
-    if (!widgetToGetKey)
-        return nil;
-
-    if (!widgetToGetKey->testAttribute(Qt::WA_InputMethodEnabled))
-        return nil;  // Not sure if that's correct, but it's saves a malloc.
-
-    // Support only underline color/style.
-    return [NSArray arrayWithObjects:NSUnderlineColorAttributeName,
-                                     NSUnderlineStyleAttributeName, nil];
-}
-@end
-
-QT_BEGIN_NAMESPACE
-#ifndef QT_NO_IM
-void QMacInputContext::reset()
-{
-    QWidget *w = QInputContext::focusWidget();
-    if (w) {
-        NSView *view = qt_mac_effectiveview_for(w);
-        if ([view isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) {
-            QMacCocoaAutoReleasePool pool;
-            QT_MANGLE_NAMESPACE(QCocoaView) *qc = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
-            NSInputManager *currentIManager = [NSInputManager currentInputManager];
-            if (currentIManager) {
-                [currentIManager markedTextAbandoned:view];
-                [qc unmarkText];
-            }
-        }
-    }
-}
-
-bool QMacInputContext::isComposing() const
-{
-    QWidget *w = QInputContext::focusWidget();
-    if (w) {
-        NSView *view = qt_mac_effectiveview_for(w);
-        if ([view isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) {
-            return [static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view) isComposing];
-        }
-    }
-    return false;
-}
-#endif // QT_NO_IM
-
-extern bool qt_mac_in_drag;
-void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm);
-static const int default_pm_hotx = -2;
-static const int default_pm_hoty = -16;
-static const char* default_pm[] = {
-    "13 9 3 1",
-    ".      c None",
-    "       c #000000",
-    "X      c #FFFFFF",
-    "X X X X X X X",
-    " X X X X X X ",
-    "X ......... X",
-    " X.........X ",
-    "X ......... X",
-    " X.........X ",
-    "X ......... X",
-    " X X X X X X ",
-    "X X X X X X X",
-};
-
-Qt::DropAction QDragManager::drag(QDrag *o)
-{
-    if(qt_mac_in_drag) {     //just make sure..
-        qWarning("Qt: Internal error: WH0A, unexpected condition reached");
-        return Qt::IgnoreAction;
-    }
-    if(object == o)
-        return Qt::IgnoreAction;
-    /* At the moment it seems clear that Mac OS X does not want to drag with a non-left button
-     so we just bail early to prevent it */
-    if (!(GetCurrentEventButtonState() & kEventMouseButtonPrimary)) {
-        o->setMimeData(0);
-        o->deleteLater();
-        return Qt::IgnoreAction;
-    }
-
-    if(object) {
-        dragPrivate()->source->removeEventFilter(this);
-        cancel();
-        beingCancelled = false;
-    }
-
-    object = o;
-    dragPrivate()->target = 0;
-
-#ifndef QT_NO_ACCESSIBILITY
-    QAccessible::updateAccessibility(this, 0, QAccessible::DragDropStart);
-#endif
-
-    // setup the data
-    QMacPasteboard dragBoard((CFStringRef) NSDragPboard, QMacPasteboardMime::MIME_DND);
-    dragPrivate()->data->setData(QLatin1String("application/x-qt-mime-type-name"), QByteArray("dummy"));
-    dragBoard.setMimeData(dragPrivate()->data);
-
-    // create the image
-    QPoint hotspot;
-    QPixmap pix = dragPrivate()->pixmap;
-    if(pix.isNull()) {
-        if(dragPrivate()->data->hasText() || dragPrivate()->data->hasUrls()) {
-            // get the string
-            QString s = dragPrivate()->data->hasText() ? dragPrivate()->data->text()
-            : dragPrivate()->data->urls().first().toString();
-            if(s.length() > 26)
-                s = s.left(23) + QChar(0x2026);
-            if(!s.isEmpty()) {
-                // draw it
-                QFont f(qApp->font());
-                f.setPointSize(12);
-                QFontMetrics fm(f);
-                QPixmap tmp(fm.width(s), fm.height());
-                if(!tmp.isNull()) {
-                    QPainter p(&tmp);
-                    p.fillRect(0, 0, tmp.width(), tmp.height(), Qt::color0);
-                    p.setPen(Qt::color1);
-                    p.setFont(f);
-                    p.drawText(0, fm.ascent(), s);
-                    // save it
-                    pix = tmp;
-                    hotspot = QPoint(tmp.width() / 2, tmp.height() / 2);
-                }
-            }
-        } else {
-            pix = QPixmap(default_pm);
-            hotspot = QPoint(default_pm_hotx, default_pm_hoty);
-        }
-    } else {
-        hotspot = dragPrivate()->hotspot;
-    }
-
-    // Convert the image to NSImage:
-    NSImage *image = (NSImage *)qt_mac_create_nsimage(pix);
-
-    DnDParams *dndParams = macCurrentDnDParameters();
-    QT_MANGLE_NAMESPACE(QCocoaView) *theView = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(dndParams->view);
-
-    // Save supported actions:
-    [theView setSupportedActions: qt_mac_mapDropActions(dragPrivate()->possible_actions)];
-    QPoint pointInView = [theView qt_qwidget]->mapFromGlobal(dndParams->globalPoint);
-    NSPoint imageLoc = {pointInView.x() - hotspot.x(), pointInView.y() + pix.height() - hotspot.y()};
-    NSSize mouseOffset = {0.0, 0.0};
-    NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
-    dragPrivate()->executed_action = Qt::ActionMask;
-
-    // Execute the drag:
-    [theView retain];
-    [theView dragImage:image
-        at:imageLoc
-        offset:mouseOffset
-        event:dndParams->theEvent
-        pasteboard:pboard
-        source:theView
-        slideBack:YES];
-
-    // Reset the implicit grab widget when drag ends because we will not
-    // receive the mouse release event when DND is active:
-    qt_button_down = 0;
-    [theView release];
-    [image release];
-    if (dragPrivate())
-        dragPrivate()->executed_action = Qt::IgnoreAction;
-    object = 0;
-    Qt::DropAction performedAction(qt_mac_mapNSDragOperation(dndParams->performedAction));
-
-    // Do post drag processing, if required.
-    if (performedAction != Qt::IgnoreAction) {
-        // Check if the receiver points us to a file location.
-        // if so, we need to do the file copy/move ourselves.
-        QCFType<CFURLRef> pasteLocation = 0;
-        PasteboardCopyPasteLocation(dragBoard.pasteBoard(), &pasteLocation);
-        if (pasteLocation) {
-            QList<QUrl> urls = o->mimeData()->urls();
-            for (int i = 0; i < urls.size(); ++i) {
-                QUrl fromUrl = urls.at(i);
-                QString filename = QFileInfo(fromUrl.path()).fileName();
-                QUrl toUrl(QCFString::toQString(CFURLGetString(pasteLocation)) + filename);
-                if (performedAction == Qt::MoveAction)
-                    QFile::rename(fromUrl.path(), toUrl.path());
-                else if (performedAction == Qt::CopyAction)
-                    QFile::copy(fromUrl.path(), toUrl.path());
-            }
-        }
-    }
-
-    // Clean-up:
-    o->setMimeData(0);
-    o->deleteLater();
-    return performedAction;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_MAC_USE_COCOA
diff --git a/src/gui/kernel/qcocoaview_mac_p.h b/src/gui/kernel/qcocoaview_mac_p.h
deleted file mode 100644 (file)
index 07bd283..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#include <qevent.h>
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-@class QT_MANGLE_NAMESPACE(QCocoaView);
-QT_FORWARD_DECLARE_CLASS(QWidgetPrivate);
-QT_FORWARD_DECLARE_CLASS(QWidget);
-QT_FORWARD_DECLARE_CLASS(QEvent);
-QT_FORWARD_DECLARE_CLASS(QString);
-QT_FORWARD_DECLARE_CLASS(QStringList);
-
-Q_GUI_EXPORT
-@interface QT_MANGLE_NAMESPACE(QCocoaView) : NSControl <NSTextInput> {
-    QWidget *qwidget;
-    QWidgetPrivate *qwidgetprivate;
-    NSDragOperation supportedActions;
-    bool composing;
-    int composingLength;
-    bool sendKeyEvents;
-    bool fromKeyDownEvent;
-    QString *composingText;
-    @public int alienTouchCount;
-}
-- (id)initWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate;
-- (void) finishInitWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate;
-- (void)frameDidChange:(NSNotification *)note;
-- (void)setSupportedActions:(NSDragOperation)actions;
-- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal;
-- (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation;
-- (BOOL)isComposing;
-- (QWidget *)qt_qwidget;
-- (void) qt_clearQWidget;
-
-@end
-#endif
diff --git a/src/gui/kernel/qcocoawindow_mac.mm b/src/gui/kernel/qcocoawindow_mac.mm
deleted file mode 100644 (file)
index 02196b3..0000000
+++ /dev/null
@@ -1,90 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <qcocoawindow_mac_p.h>
-#import <qcocoawindowdelegate_mac_p.h>
-#import <qcocoaview_mac_p.h>
-#import <qt_cocoa_helpers_mac_p.h>
-#import <qcocoawindowcustomthemeframe_mac_p.h>
-#import <qcocoaapplication_mac_p.h>
-#import <qdnd_p.h>
-#import <qmultitouch_mac_p.h>
-
-#include <QtGui/QWidget>
-
-QT_FORWARD_DECLARE_CLASS(QWidget);
-QT_USE_NAMESPACE
-
-@implementation NSWindow (QT_MANGLE_NAMESPACE(QWidgetIntegration))
-
-- (id)QT_MANGLE_NAMESPACE(qt_initWithQWidget):(QWidget*)widget contentRect:(NSRect)rect styleMask:(NSUInteger)mask
-{
-    self = [self initWithContentRect:rect styleMask:mask backing:NSBackingStoreBuffered defer:YES];
-    if (self) {
-        [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] becomeDelegateForWindow:self widget:widget];
-        [self setReleasedWhenClosed:NO];
-    }
-    return self;
-}
-
-- (QWidget *)QT_MANGLE_NAMESPACE(qt_qwidget)
-{
-    QWidget *widget = 0;
-    if ([self delegate] == [QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate])
-        widget = [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] qt_qwidgetForWindow:self];
-    return widget;
-}
-
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaWindow)
-
-/***********************************************************************
-  Copy and Paste between QCocoaWindow and QCocoaPanel
-  This is a bit unfortunate, but thanks to the dynamic dispatch we
-  have to duplicate this code or resort to really silly forwarding methods
-**************************************************************************/
-#include "qcocoasharedwindowmethods_mac_p.h"
-
-@end
-#endif
diff --git a/src/gui/kernel/qcocoawindow_mac_p.h b/src/gui/kernel/qcocoawindow_mac_p.h
deleted file mode 100644 (file)
index 091c59f..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#ifndef QCOCOAWINDOW_MAC_P
-#define QCOCOAWINDOW_MAC_P
-
-#ifdef QT_MAC_USE_COCOA
-#include "qmacdefines_mac.h"
-#import <Cocoa/Cocoa.h>
-#include <qapplication_p.h>
-#include <qbackingstore_p.h>
-
-enum { QtMacCustomizeWindow = 1 << 21 }; // This will one day be run over by
-
-QT_FORWARD_DECLARE_CLASS(QWidget);
-QT_FORWARD_DECLARE_CLASS(QStringList);
-QT_FORWARD_DECLARE_CLASS(QCocoaDropData);
-
-@interface NSWindow (QtCoverForHackWithCategory)
-+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask;
-@end
-
-@interface NSWindow (QT_MANGLE_NAMESPACE(QWidgetIntegration))
-- (id)QT_MANGLE_NAMESPACE(qt_initWithQWidget):(QWidget *)widget contentRect:(NSRect)rect styleMask:(NSUInteger)mask;
-- (QWidget *)QT_MANGLE_NAMESPACE(qt_qwidget);
-@end
-
-@interface NSWindow (QtIntegration)
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
-- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender;
-- (void)draggingExited:(id <NSDraggingInfo>)sender;
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
-@end
-
-@interface QT_MANGLE_NAMESPACE(QCocoaWindow) : NSWindow {
-    QStringList *currentCustomDragTypes;
-    QCocoaDropData *dropData;
-    NSInteger dragEnterSequence;
-}
-
-+ (Class)frameViewClassForStyleMask:(NSUInteger)styleMask;
-- (void)registerDragTypes;
-- (void)drawRectOriginal:(NSRect)rect;
-
-@end
-#endif
-
-#endif
diff --git a/src/gui/kernel/qcocoawindowcustomthemeframe_mac.mm b/src/gui/kernel/qcocoawindowcustomthemeframe_mac.mm
deleted file mode 100644 (file)
index f52f475..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmacdefines_mac.h"
-
-#ifdef QT_MAC_USE_COCOA
-
-#import "qcocoawindowcustomthemeframe_mac_p.h"
-#import "qcocoawindow_mac_p.h"
-#include "qt_cocoa_helpers_mac_p.h"
-#include "qwidget.h"
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaWindowCustomThemeFrame)
-
-- (void)_updateButtons
-{
-    [super _updateButtons];
-    NSWindow *window = [self window];
-    qt_syncCocoaTitleBarButtons(window, [window QT_MANGLE_NAMESPACE(qt_qwidget)]);
-}
-
-@end
-
-#endif
diff --git a/src/gui/kernel/qcocoawindowcustomthemeframe_mac_p.h b/src/gui/kernel/qcocoawindowcustomthemeframe_mac_p.h
deleted file mode 100644 (file)
index 3a3e3e2..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
-// and many other.  This header file may change from version to version
-// without notice, or even be removed.
-//
-// We mean it.
-//
-#import <Cocoa/Cocoa.h>
-#include "qmacdefines_mac.h"
-#import "qnsthemeframe_mac_p.h"
-
-@interface QT_MANGLE_NAMESPACE(QCocoaWindowCustomThemeFrame) : NSThemeFrame
-{
-}
-
-@end
diff --git a/src/gui/kernel/qcocoawindowdelegate_mac.mm b/src/gui/kernel/qcocoawindowdelegate_mac.mm
deleted file mode 100644 (file)
index d0fd5d7..0000000
+++ /dev/null
@@ -1,444 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#import "qcocoawindowdelegate_mac_p.h"
-#ifdef QT_MAC_USE_COCOA
-#include <qwidget_p.h>
-#include <qapplication_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qevent.h>
-#include <qlayout.h>
-#include <qcoreapplication.h>
-#include <qmenubar.h>
-#include <QMainWindow>
-#include <QToolBar>
-#include <qmainwindowlayout_p.h>
-#include <qpaintengine_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-extern QWidgetData *qt_qwidget_data(QWidget *); // qwidget.cpp
-extern void onApplicationWindowChangedActivation(QWidget *, bool); //qapplication_mac.mm
-extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); // qapplication.cpp
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-static QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) *sharedCocoaWindowDelegate = nil;
-
-// This is a singleton, but unlike most Cocoa singletons, it lives in a library and could be
-// pontentially loaded and unloaded. This means we should at least attempt to do the
-// memory management correctly.
-
-static void cleanupCocoaWindowDelegate()
-{
-    [sharedCocoaWindowDelegate release];
-}
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaWindowDelegate)
-
-- (id)init
-{
-    self = [super init];
-    if (self != nil) {
-        m_windowHash = new QHash<NSWindow *, QWidget *>();
-        m_drawerHash = new QHash<NSDrawer *, QWidget *>();
-    }
-    return self;
-}
-
-- (void)dealloc
-{
-    sharedCocoaWindowDelegate = nil;
-    QHash<NSWindow *, QWidget *>::const_iterator windowIt = m_windowHash->constBegin();
-    while (windowIt != m_windowHash->constEnd()) {
-        [windowIt.key() setDelegate:nil];
-        ++windowIt;
-    }
-    delete m_windowHash;
-    QHash<NSDrawer *, QWidget *>::const_iterator drawerIt = m_drawerHash->constBegin();
-    while (drawerIt != m_drawerHash->constEnd()) {
-        [drawerIt.key() setDelegate:nil];
-        ++drawerIt;
-    }
-    delete m_drawerHash;
-    [super dealloc];
-}
-
-+ (id)allocWithZone:(NSZone *)zone
-{
-    @synchronized(self) {
-        if (sharedCocoaWindowDelegate == nil) {
-            sharedCocoaWindowDelegate = [super allocWithZone:zone];
-            return sharedCocoaWindowDelegate;
-            qAddPostRoutine(cleanupCocoaWindowDelegate);
-        }
-    }
-    return nil;
-}
-
-+ (QT_MANGLE_NAMESPACE(QCocoaWindowDelegate)*)sharedDelegate
-{
-    @synchronized(self) {
-        if (sharedCocoaWindowDelegate == nil)
-            [[self alloc] init];
-    }
-    return [[sharedCocoaWindowDelegate retain] autorelease];
-}
-
--(void)syncSizeForWidget:(QWidget *)qwidget toSize:(const QSize &)newSize fromSize:(const QSize &)oldSize
-{
-    qt_qwidget_data(qwidget)->crect.setSize(newSize);
-    // ### static contents optimization needs to go here
-    const OSViewRef view = qt_mac_nativeview_for(qwidget);
-    [view setFrameSize:NSMakeSize(newSize.width(), newSize.height())];
-    if (!qwidget->isVisible()) {
-        qwidget->setAttribute(Qt::WA_PendingResizeEvent, true);
-    } else {
-        QResizeEvent qre(newSize, oldSize);
-        if (qwidget->testAttribute(Qt::WA_PendingResizeEvent)) {
-            qwidget->setAttribute(Qt::WA_PendingResizeEvent, false);
-            QApplication::sendEvent(qwidget, &qre);
-        } else {
-            qt_sendSpontaneousEvent(qwidget, &qre);
-        }
-    }
-}
-
-- (void)dumpMaximizedStateforWidget:(QWidget*)qwidget window:(NSWindow *)window
-{
-    if (!window)
-        return; // Nothing to do.
-    QWidgetData *widgetData = qt_qwidget_data(qwidget);
-    if ((widgetData->window_state & Qt::WindowMaximized) && ![window isZoomed]) {
-        widgetData->window_state &= ~Qt::WindowMaximized;
-        QWindowStateChangeEvent e(Qt::WindowState(widgetData->window_state | Qt::WindowMaximized));
-        qt_sendSpontaneousEvent(qwidget, &e);
-    }
-}
-
-- (NSSize)closestAcceptableSizeForWidget:(QWidget *)qwidget window:(NSWindow *)window
-                             withNewSize:(NSSize)proposedSize
-{
-    [self dumpMaximizedStateforWidget:qwidget window:window];
-    QSize newSize = QLayout::closestAcceptableSize(qwidget, 
-                                                   QSize(proposedSize.width, proposedSize.height));
-    return [NSWindow frameRectForContentRect:
-            NSMakeRect(0., 0., newSize.width(), newSize.height())
-                                   styleMask:[window styleMask]].size;
-}
-
-- (NSSize)windowWillResize:(NSWindow *)windowToResize toSize:(NSSize)proposedFrameSize
-{
-    QWidget *qwidget = m_windowHash->value(windowToResize);
-    return [self closestAcceptableSizeForWidget:qwidget window:windowToResize
-                                    withNewSize:[NSWindow contentRectForFrameRect:
-                                                 NSMakeRect(0, 0, 
-                                                            proposedFrameSize.width,
-                                                            proposedFrameSize.height) 
-                                                    styleMask:[windowToResize styleMask]].size];
-}
-
-- (NSSize)drawerWillResizeContents:(NSDrawer *)sender toSize:(NSSize)contentSize
-{
-    QWidget *qwidget = m_drawerHash->value(sender);
-    return [self closestAcceptableSizeForWidget:qwidget window:nil withNewSize:contentSize];
-}
-
--(void)windowDidMiniaturize:(NSNotification*)notification
-{
-    QWidget *qwidget = m_windowHash->value([notification object]);
-    if (!qwidget->isMinimized()) {
-        QWidgetData *widgetData = qt_qwidget_data(qwidget);
-        widgetData->window_state = widgetData->window_state | Qt::WindowMinimized;
-        QWindowStateChangeEvent e(widgetData->window_state & ~Qt::WindowMinimized);
-        qt_sendSpontaneousEvent(qwidget, &e);
-    }
-    // Send hide to match Qt on X11 and Windows
-    QEvent e(QEvent::Hide);
-    qt_sendSpontaneousEvent(qwidget, &e);
-}
-
-- (void)windowDidResize:(NSNotification *)notification
-{
-    NSWindow *window = [notification object];
-    QWidget *qwidget = m_windowHash->value(window);
-    QWidgetData *widgetData = qt_qwidget_data(qwidget);
-    if (!(qwidget->windowState() & (Qt::WindowMaximized | Qt::WindowFullScreen)) && [window isZoomed]) {
-        widgetData->window_state = widgetData->window_state | Qt::WindowMaximized;
-        QWindowStateChangeEvent e(widgetData->window_state & ~Qt::WindowMaximized);
-        qt_sendSpontaneousEvent(qwidget, &e);
-    } else {
-        widgetData->window_state = widgetData->window_state & ~Qt::WindowMaximized;
-        QWindowStateChangeEvent e(widgetData->window_state | Qt::WindowMaximized);
-        qt_sendSpontaneousEvent(qwidget, &e);
-    }
-    NSRect rect = [[window contentView] frame];
-    const QSize newSize(rect.size.width, rect.size.height);
-    const QSize &oldSize = widgetData->crect.size();
-    if (newSize != oldSize) {
-        QWidgetPrivate::qt_mac_update_sizer(qwidget);
-        [self syncSizeForWidget:qwidget toSize:newSize fromSize:oldSize];
-    }
-
-    // We force the repaint to be synchronized with the resize of the window.
-    // Otherwise, the resize looks sluggish because we paint one event loop later.
-    if ([[window contentView] inLiveResize]) {
-        qwidget->repaint();
-
-        // We need to repaint the toolbar as well.
-        QMainWindow* mWindow = qobject_cast<QMainWindow*>(qwidget->window());
-        if (mWindow) {
-            QMainWindowLayout *mLayout = qobject_cast<QMainWindowLayout*>(mWindow->layout());
-            QList<QToolBar *> toolbarList = mLayout->qtoolbarsInUnifiedToolbarList;
-
-            for (int i = 0; i < toolbarList.size(); ++i) {
-                QToolBar* toolbar = toolbarList.at(i);
-                toolbar->repaint();
-            }
-        }
-    }
-}
-
-- (void)windowDidMove:(NSNotification *)notification
-{
-    // The code underneath needs to translate the window location
-    // from bottom left (which is the origin used by Cocoa) to
-    // upper left (which is the origin used by Qt):
-    NSWindow *window = [notification object];
-    NSRect newRect = [window frame];
-    QWidget *qwidget = m_windowHash->value(window);
-    QPoint qtPoint = flipPoint(NSMakePoint(newRect.origin.x,
-                                           newRect.origin.y + newRect.size.height)).toPoint();
-    const QRect &oldRect = qwidget->frameGeometry();
-
-    if (qtPoint.x() != oldRect.x() || qtPoint.y() != oldRect.y()) {
-        QWidgetData *widgetData = qt_qwidget_data(qwidget);
-        QRect oldCRect = widgetData->crect;
-        QWidgetPrivate *widgetPrivate = qt_widget_private(qwidget);
-        const QRect &fStrut = widgetPrivate->frameStrut();
-        widgetData->crect.moveTo(qtPoint.x() + fStrut.left(), qtPoint.y() + fStrut.top());
-        if (!qwidget->isVisible()) {
-            qwidget->setAttribute(Qt::WA_PendingMoveEvent, true);
-        } else {
-            QMoveEvent qme(qtPoint, oldRect.topLeft());
-            qt_sendSpontaneousEvent(qwidget, &qme);
-        }
-    }
-}
-
--(BOOL)windowShouldClose:(id)windowThatWantsToClose
-{
-    QWidget *qwidget = m_windowHash->value(windowThatWantsToClose);
-    QScopedLoopLevelCounter counter(qt_widget_private(qwidget)->threadData);
-    return qt_widget_private(qwidget)->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
-}
-
--(void)windowDidDeminiaturize:(NSNotification *)notification
-{
-    QWidget *qwidget = m_windowHash->value([notification object]);
-    QWidgetData *widgetData = qt_qwidget_data(qwidget);
-    Qt::WindowStates currState = widgetData->window_state;
-    Qt::WindowStates newState = currState;
-    if (currState & Qt::WindowMinimized)
-        newState &= ~Qt::WindowMinimized;
-    if (!(currState & Qt::WindowActive))
-        newState |= Qt::WindowActive;
-    if (newState != currState) {
-        widgetData->window_state = newState;
-        QWindowStateChangeEvent e(currState);
-        qt_sendSpontaneousEvent(qwidget, &e);
-    }
-    QShowEvent qse;
-    qt_sendSpontaneousEvent(qwidget, &qse);
-}
-
--(void)windowDidBecomeMain:(NSNotification*)notification
-{
-    QWidget *qwidget = m_windowHash->value([notification object]);
-    Q_ASSERT(qwidget);
-    onApplicationWindowChangedActivation(qwidget, true);
-}
-
--(void)windowDidResignMain:(NSNotification*)notification
-{
-    QWidget *qwidget = m_windowHash->value([notification object]);
-    Q_ASSERT(qwidget);
-    onApplicationWindowChangedActivation(qwidget, false);
-}
-
-// These are the same as main, but they are probably better to keep separate since there is a
-// tiny difference between main and key windows.
--(void)windowDidBecomeKey:(NSNotification*)notification
-{
-    QWidget *qwidget = m_windowHash->value([notification object]);
-    Q_ASSERT(qwidget);
-    onApplicationWindowChangedActivation(qwidget, true);
-}
-
--(void)windowDidResignKey:(NSNotification*)notification
-{
-    QWidget *qwidget = m_windowHash->value([notification object]);
-    Q_ASSERT(qwidget);
-    onApplicationWindowChangedActivation(qwidget, false);
-}
-
--(QWidget *)qt_qwidgetForWindow:(NSWindow *)window
-{
-    return m_windowHash->value(window);
-}
-
-- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame
-{
-    Q_UNUSED(newFrame);
-    // saving the current window geometry before the window is maximized
-    QWidget *qwidget = m_windowHash->value(window);
-    QWidgetPrivate *widgetPrivate = qt_widget_private(qwidget);
-    if (qwidget->isWindow()) {
-        if(qwidget->windowState() & Qt::WindowMaximized) {
-            // Restoring
-            widgetPrivate->topData()->wasMaximized = false;
-        } else {
-            // Maximizing
-            widgetPrivate->topData()->normalGeometry = qwidget->geometry();
-            // If the window was maximized we need to update the coordinates since now it will start at 0,0.
-            // We do this in a special field that is only used when not restoring but manually resizing the window.
-            // Since the coordinates are fixed we just set a boolean flag.
-            widgetPrivate->topData()->wasMaximized = true;
-        }
-    }
-    return YES;
-}
-
-- (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)defaultFrame
-{
-    NSRect frameToReturn = defaultFrame;
-    QWidget *qwidget = m_windowHash->value(window);
-    QSizeF size = qwidget->maximumSize();
-    NSRect windowFrameRect = [window frame];
-    NSRect viewFrameRect = [[window contentView] frame];
-    // consider additional size required for titlebar & frame
-    frameToReturn.size.width = qMin<CGFloat>(frameToReturn.size.width,
-            size.width()+(windowFrameRect.size.width - viewFrameRect.size.width));
-    frameToReturn.size.height = qMin<CGFloat>(frameToReturn.size.height,
-            size.height()+(windowFrameRect.size.height - viewFrameRect.size.height));
-    return frameToReturn;
-}
-
-- (void)becomeDelegateForWindow:(NSWindow *)window  widget:(QWidget *)widget
-{
-    m_windowHash->insert(window, widget);
-    [window setDelegate:self];
-}
-
-- (void)resignDelegateForWindow:(NSWindow *)window
-{
-    [window setDelegate:nil];
-    m_windowHash->remove(window);
-}
-
-- (void)becomeDelegateForDrawer:(NSDrawer *)drawer widget:(QWidget *)widget
-{
-    m_drawerHash->insert(drawer, widget);
-    [drawer setDelegate:self];
-    NSWindow *window = [[drawer contentView] window];
-    [self becomeDelegateForWindow:window widget:widget];
-}
-
-- (void)resignDelegateForDrawer:(NSDrawer *)drawer
-{
-    QWidget *widget = m_drawerHash->value(drawer);
-    [drawer setDelegate:nil];
-    if (widget)
-        [self resignDelegateForWindow:[[drawer contentView] window]];
-    m_drawerHash->remove(drawer);
-}
-
-- (void)windowDidChangeScreen:(NSNotification*)notification
-{
-    QWidget *qwidget = m_windowHash->value([notification object]);
-    QCoreGraphicsPaintEngine::clearColorSpace(qwidget);
-}
-
-- (BOOL)window:(NSWindow *)window shouldPopUpDocumentPathMenu:(NSMenu *)menu
-{
-    Q_UNUSED(menu);
-    QWidget *qwidget = m_windowHash->value(window);
-    if (qwidget && !qwidget->windowFilePath().isEmpty()) {
-        return YES;
-    }
-    return NO;
-}
-
-- (BOOL)window:(NSWindow *)window shouldDragDocumentWithEvent:(NSEvent *)event
-                                                          from:(NSPoint)dragImageLocation
-                                                withPasteboard:(NSPasteboard *)pasteboard
-{
-    Q_UNUSED(event);
-    Q_UNUSED(dragImageLocation);
-    Q_UNUSED(pasteboard);
-    QWidget *qwidget = m_windowHash->value(window);
-    if (qwidget && !qwidget->windowFilePath().isEmpty()) {
-        return YES;
-    }
-    return NO;
-}
-
-- (void)syncContentViewFrame: (NSNotification *)notification
-{
-    NSView *cView = [notification object];
-    if (cView) {
-        NSWindow *window = [cView window];
-        QWidget *qwidget = m_windowHash->value(window);
-        if (qwidget) {
-            QWidgetData *widgetData = qt_qwidget_data(qwidget);
-            NSRect rect = [cView frame];
-            const QSize newSize(rect.size.width, rect.size.height);
-            const QSize &oldSize = widgetData->crect.size();
-            if (newSize != oldSize) {
-                [self syncSizeForWidget:qwidget toSize:newSize fromSize:oldSize];
-            }
-        }
-
-    }
-}
-
-@end
-#endif// QT_MAC_USE_COCOA
diff --git a/src/gui/kernel/qcocoawindowdelegate_mac_p.h b/src/gui/kernel/qcocoawindowdelegate_mac_p.h
deleted file mode 100644 (file)
index d576c9d..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#include "qmacdefines_mac.h"
-
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_BEGIN_NAMESPACE
-template <class Key, class T> class QHash;
-QT_END_NAMESPACE
-using QT_PREPEND_NAMESPACE(QHash);
-QT_FORWARD_DECLARE_CLASS(QWidget)
-QT_FORWARD_DECLARE_CLASS(QSize)
-QT_FORWARD_DECLARE_CLASS(QWidgetData)
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-@protocol NSWindowDelegate <NSObject>
-- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize;
-- (void)windowDidMiniaturize:(NSNotification*)notification;
-- (void)windowDidResize:(NSNotification *)notification;
-- (NSRect)windowWillUseStandardFrame:(NSWindow *)window defaultFrame:(NSRect)defaultFrame;
-- (void)windowDidMove:(NSNotification *)notification;
-- (BOOL)windowShouldClose:(id)window;
-- (void)windowDidDeminiaturize:(NSNotification *)notification;
-- (void)windowDidBecomeMain:(NSNotification*)notification;
-- (void)windowDidResignMain:(NSNotification*)notification;
-- (void)windowDidBecomeKey:(NSNotification*)notification;
-- (void)windowDidResignKey:(NSNotification*)notification;
-- (void)windowDidChangeScreen:(NSNotification*)notification;
-- (BOOL)window:(NSWindow *)window shouldPopUpDocumentPathMenu:(NSMenu *)menu;
-- (BOOL)window:(NSWindow *)window shouldDragDocumentWithEvent:(NSEvent *)event from:(NSPoint)dragImageLocation withPasteboard:(NSPasteboard *)pasteboard;
-- (BOOL)windowShouldZoom:(NSWindow *)window toFrame:(NSRect)newFrame;
-@end
-
-@protocol NSDrawerDelegate <NSObject>
-- (NSSize)drawerWillResizeContents:(NSDrawer *)sender toSize:(NSSize)contentSize;
-@end
-
-#endif
-
-
-
-@interface QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) : NSObject<NSWindowDelegate, NSDrawerDelegate> {
-    QHash<NSWindow *, QWidget *> *m_windowHash;
-    QHash<NSDrawer *, QWidget *> *m_drawerHash;
-}
-+ (QT_MANGLE_NAMESPACE(QCocoaWindowDelegate)*)sharedDelegate;
-- (void)becomeDelegateForWindow:(NSWindow *)window  widget:(QWidget *)widget;
-- (void)resignDelegateForWindow:(NSWindow *)window;
-- (void)becomeDelegateForDrawer:(NSDrawer *)drawer widget:(QWidget *)widget;
-- (void)resignDelegateForDrawer:(NSDrawer *)drawer;
-- (void)dumpMaximizedStateforWidget:(QWidget*)qwidget window:(NSWindow *)window;
-- (void)syncSizeForWidget:(QWidget *)qwidget
-        toSize:(const QSize &)newSize
-        fromSize:(const QSize &)oldSize;
-- (NSSize)closestAcceptableSizeForWidget:(QWidget *)qwidget
-        window:(NSWindow *)window withNewSize:(NSSize)proposedSize;
-- (QWidget *)qt_qwidgetForWindow:(NSWindow *)window;
-- (void)syncContentViewFrame: (NSNotification *)notification;
-@end
-#endif
diff --git a/src/gui/kernel/qcursor_mac.mm b/src/gui/kernel/qcursor_mac.mm
deleted file mode 100644 (file)
index 0e7ff9e..0000000
+++ /dev/null
@@ -1,690 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qcursor_p.h>
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qcursor.h>
-#include <qevent.h>
-#include <string.h>
-#include <unistd.h>
-#include <AppKit/NSCursor.h>
-#include <qpainter.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qapplication_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
-  Externals
- *****************************************************************************/
-extern QCursorData *qt_cursorTable[Qt::LastCursor + 1];
-extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
-extern GrafPtr qt_mac_qd_context(const QPaintDevice *); //qpaintdevice_mac.cpp
-extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); //qapplication_mac.cpp
-extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
-
-/*****************************************************************************
-  Internal QCursorData class
- *****************************************************************************/
-
-class QMacAnimateCursor : public QObject
-{
-    int timerId, step;
-    ThemeCursor curs;
-public:
-    QMacAnimateCursor() : QObject(), timerId(-1) { }
-    void start(ThemeCursor c) {
-        step = 1;
-        if(timerId != -1)
-            killTimer(timerId);
-        timerId = startTimer(300);
-        curs = c;
-    }
-    void stop() {
-        if(timerId != -1) {
-            killTimer(timerId);
-            timerId = -1;
-        }
-    }
-protected:
-    void timerEvent(QTimerEvent *e) {
-        if(e->timerId() == timerId) {
-            /*
-            if(SetAnimatedThemeCursor(curs, step++) == themeBadCursorIndexErr)
-                stop();
-            */
-        }
-    }
-};
-
-inline void *qt_mac_nsCursorForQCursor(const QCursor &c)
-{
-    c.d->update();
-    return [[static_cast<NSCursor *>(c.d->curs.cp.nscursor) retain] autorelease];
-}
-
-static QCursorData *currentCursor = 0; //current cursor
-
-void qt_mac_set_cursor(const QCursor *c)
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    [static_cast<NSCursor *>(qt_mac_nsCursorForQCursor(*c)) set];
-#else
-    if (!c) {
-        currentCursor = 0;
-        return;
-    }
-    c->handle(); //force the cursor to get loaded, if it's not
-
-    if(currentCursor && currentCursor->type == QCursorData::TYPE_ThemeCursor
-            && currentCursor->curs.tc.anim)
-        currentCursor->curs.tc.anim->stop();
-    if(c->d->type == QCursorData::TYPE_ImageCursor) {
-        [static_cast<NSCursor *>(c->d->curs.cp.nscursor) set];
-    } else if(c->d->type == QCursorData::TYPE_ThemeCursor) {
-        if(SetAnimatedThemeCursor(c->d->curs.tc.curs, 0) == themeBadCursorIndexErr) {
-            SetThemeCursor(c->d->curs.tc.curs);
-        } else {
-            if(!c->d->curs.tc.anim)
-                c->d->curs.tc.anim = new QMacAnimateCursor;
-            c->d->curs.tc.anim->start(c->d->curs.tc.curs);
-        }
-    }
-
-    currentCursor = c->d;
-#endif
-}
-
-static QPointer<QWidget> lastWidgetUnderMouse = 0;
-static QPointer<QWidget> lastMouseCursorWidget = 0;
-static bool qt_button_down_on_prev_call = false;
-static QCursor *grabCursor = 0;
-
-void qt_mac_updateCursorWithWidgetUnderMouse(QWidget *widgetUnderMouse)
-{
-    QCursor cursor(Qt::ArrowCursor);
-    if (qt_button_down) {
-        // The widget that is currently pressed
-        // grabs the mouse cursor:
-        widgetUnderMouse = qt_button_down;
-        qt_button_down_on_prev_call = true;
-    } else if (qt_button_down_on_prev_call) {
-        // Grab has been released, so do
-        // a full check:
-        qt_button_down_on_prev_call = false;
-        lastWidgetUnderMouse = 0;
-        lastMouseCursorWidget = 0;
-    }
-
-    if (QApplication::overrideCursor()) {
-        cursor = *QApplication::overrideCursor();
-    } else if (grabCursor) {
-        cursor = *grabCursor;
-    } else if (widgetUnderMouse) {
-        if (widgetUnderMouse == lastWidgetUnderMouse) {
-            // Optimization that should hit when the widget under
-            // the mouse does not change as the mouse moves:
-            if (lastMouseCursorWidget)
-                cursor = lastMouseCursorWidget->cursor();
-        } else {
-            QWidget *w = widgetUnderMouse;
-            for (; w; w = w->parentWidget()) {
-                if (w->testAttribute(Qt::WA_SetCursor)) {
-                    cursor = w->cursor();
-                    break;
-                }
-                if (w->isWindow())
-                    break;
-            }
-            // One final check in case we ran out of parents in the loop:
-            if (w && !w->testAttribute(Qt::WA_SetCursor))
-                w = 0;
-
-            lastWidgetUnderMouse = widgetUnderMouse;
-            lastMouseCursorWidget = w;
-        }
-    }
-
-#ifdef QT_MAC_USE_COCOA
-    cursor.d->update();
-    NSCursor *nsCursor = static_cast<NSCursor *>(cursor.d->curs.cp.nscursor);
-    if ([NSCursor currentCursor] != nsCursor) {
-        QMacCocoaAutoReleasePool pool;
-        [nsCursor set];
-    }
-#else
-    qt_mac_set_cursor(&cursor);
-#endif
-}
-
-void qt_mac_update_cursor()
-{
-    // This function is similar to qt_mac_updateCursorWithWidgetUnderMouse
-    // except that is clears the optimization cache, and finds the widget
-    // under mouse itself. Clearing the cache is useful in cases where the
-    // application has been deactivated/activated etc.
-    // NB: since we dont have any true native widget, the call to
-    // qt_mac_getTargetForMouseEvent will fail when the mouse is over QMacNativeWidgets.
-#ifdef QT_MAC_USE_COCOA
-    lastWidgetUnderMouse = 0;
-    lastMouseCursorWidget = 0;
-    QWidget *widgetUnderMouse = 0;
-
-    if (qt_button_down) {
-        widgetUnderMouse = qt_button_down;
-    } else {
-        QPoint localPoint;
-        QPoint globalPoint;
-        qt_mac_getTargetForMouseEvent(0, QEvent::None, localPoint, globalPoint, 0, &widgetUnderMouse);
-    }
-    qt_mac_updateCursorWithWidgetUnderMouse(widgetUnderMouse);
-#else
-    qt_mac_updateCursorWithWidgetUnderMouse(QApplication::widgetAt(QCursor::pos()));
-#endif
-}
-
-void qt_mac_setMouseGrabCursor(bool set, QCursor *const cursor = 0)
-{
-    if (grabCursor) {
-        delete grabCursor;
-        grabCursor = 0;
-    }
-    if (set) {
-        if (cursor)
-            grabCursor = new QCursor(*cursor);
-        else if (lastMouseCursorWidget)
-            grabCursor = new QCursor(lastMouseCursorWidget->cursor());
-        else
-            grabCursor = new QCursor(Qt::ArrowCursor);
-    }
-    qt_mac_update_cursor();
-}
-
-#ifndef QT_MAC_USE_COCOA
-void qt_mac_update_cursor_at_global_pos(const QPoint &globalPos)
-{
-    qt_mac_updateCursorWithWidgetUnderMouse(QApplication::widgetAt(globalPos));
-}
-#endif
-
-static int nextCursorId = Qt::BitmapCursor;
-
-QCursorData::QCursorData(Qt::CursorShape s)
-    : cshape(s), bm(0), bmm(0), hx(-1), hy(-1), mId(s), type(TYPE_None)
-{
-    ref = 1;
-    memset(&curs, '\0', sizeof(curs));
-}
-
-QCursorData::~QCursorData()
-{
-    if (type == TYPE_ImageCursor) {
-        if (curs.cp.my_cursor) {
-            QMacCocoaAutoReleasePool pool;
-            [static_cast<NSCursor *>(curs.cp.nscursor) release];
-        }
-    } else if(type == TYPE_ThemeCursor) {
-        delete curs.tc.anim;
-    }
-    type = TYPE_None;
-
-    delete bm;
-    delete bmm;
-    if(currentCursor == this)
-        currentCursor = 0;
-}
-
-QCursorData *QCursorData::setBitmap(const QBitmap &bitmap, const QBitmap &mask, int hotX, int hotY)
-{
-    if (!QCursorData::initialized)
-        QCursorData::initialize();
-    if (bitmap.depth() != 1 || mask.depth() != 1 || bitmap.size() != mask.size()) {
-        qWarning("Qt: QCursor: Cannot create bitmap cursor; invalid bitmap(s)");
-        QCursorData *c = qt_cursorTable[0];
-        c->ref.ref();
-        return c;
-    }
-    // This is silly, but this is apparently called outside the constructor, so we have
-    // to be ready for that case.
-    QCursorData *x = new QCursorData;
-    x->ref = 1;
-    x->mId = ++nextCursorId;
-    x->bm  = new QBitmap(bitmap);
-    x->bmm = new QBitmap(mask);
-    x->cshape = Qt::BitmapCursor;
-    x->hx = hotX >= 0 ? hotX : bitmap.width() / 2;
-    x->hy = hotY >= 0 ? hotY : bitmap.height() / 2;
-    return x;
-}
-
-Qt::HANDLE QCursor::handle() const
-{
-    if(!QCursorData::initialized)
-        QCursorData::initialize();
-    if(d->type == QCursorData::TYPE_None)
-        d->update();
-    return (Qt::HANDLE)d->mId;
-}
-
-QPoint QCursor::pos()
-{
-    return flipPoint([NSEvent mouseLocation]).toPoint();
-}
-
-void QCursor::setPos(int x, int y)
-{
-#ifdef QT_MAC_USE_COCOA
-    CGPoint pos;
-    pos.x = x;
-    pos.y = y;
-
-    CGEventRef e = CGEventCreateMouseEvent(0, kCGEventMouseMoved, pos, 0);
-    CGEventPost(kCGHIDEventTap, e);
-    CFRelease(e);
-#else
-    CGWarpMouseCursorPosition(CGPointMake(x, y));
-
-    /* I'm not too keen on doing this, but this makes it a lot easier, so I just
-       send the event back through the event system and let it get propagated correctly
-       ideally this would not really need to be faked --Sam
-    */
-    QWidget *widget = 0;
-    if(QWidget *grb = QWidget::mouseGrabber())
-        widget = grb;
-    else
-        widget = QApplication::widgetAt(QPoint(x, y));
-    if(widget) {
-        QMouseEvent me(QMouseEvent::MouseMove, widget->mapFromGlobal(QPoint(x, y)), Qt::NoButton,
-                       QApplication::mouseButtons(), QApplication::keyboardModifiers());
-        qt_sendSpontaneousEvent(widget, &me);
-    }
-#endif
-}
-
-void QCursorData::initCursorFromBitmap()
-{
-    NSImage *nsimage;
-    QImage finalCursor(bm->size(), QImage::Format_ARGB32);
-    QImage bmi = bm->toImage().convertToFormat(QImage::Format_RGB32);
-    QImage bmmi = bmm->toImage().convertToFormat(QImage::Format_RGB32);
-    for (int row = 0; row < finalCursor.height(); ++row) {
-        QRgb *bmData = reinterpret_cast<QRgb *>(bmi.scanLine(row));
-        QRgb *bmmData = reinterpret_cast<QRgb *>(bmmi.scanLine(row));
-        QRgb *finalData = reinterpret_cast<QRgb *>(finalCursor.scanLine(row));
-        for (int col = 0; col < finalCursor.width(); ++col) {
-            if (bmmData[col] == 0xff000000 && bmData[col] == 0xffffffff) {
-                finalData[col] = 0xffffffff;
-            } else if (bmmData[col] == 0xff000000 && bmData[col] == 0xffffffff) {
-                finalData[col] = 0x7f000000;
-            } else if (bmmData[col] == 0xffffffff && bmData[col] == 0xffffffff) {
-                finalData[col] = 0x00000000;
-            } else {
-                finalData[col] = 0xff000000;
-            }
-        }
-    }
-    type = QCursorData::TYPE_ImageCursor;
-    curs.cp.my_cursor = true;
-    QPixmap bmCopy = QPixmap::fromImage(finalCursor);
-    NSPoint hotSpot = { hx, hy };
-    nsimage = static_cast<NSImage*>(qt_mac_create_nsimage(bmCopy));
-    curs.cp.nscursor = [[NSCursor alloc] initWithImage:nsimage hotSpot: hotSpot];
-    [nsimage release];
-}
-
-void QCursorData::initCursorFromPixmap()
-{
-    type = QCursorData::TYPE_ImageCursor;
-    curs.cp.my_cursor = true;
-    NSPoint hotSpot = { hx, hy };
-    NSImage *nsimage;
-    nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(pixmap));
-    curs.cp.nscursor = [[NSCursor alloc] initWithImage:nsimage hotSpot: hotSpot];
-    [nsimage release];
-}
-
-void QCursorData::update()
-{
-    if(!QCursorData::initialized)
-        QCursorData::initialize();
-    if(type != QCursorData::TYPE_None)
-        return;
-
-    /* Note to self... ***
-     * mask x data
-     * 0xFF x 0x00 == fully opaque white
-     * 0x00 x 0xFF == xor'd black
-     * 0xFF x 0xFF == fully opaque black
-     * 0x00 x 0x00 == fully transparent
-     */
-
-    if (hx < 0)
-        hx = 0;
-    if (hy < 0)
-        hy = 0;
-
-#define QT_USE_APPROXIMATE_CURSORS
-#ifdef QT_USE_APPROXIMATE_CURSORS
-    static const uchar cur_ver_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x03, 0xc0, 0x07, 0xe0, 0x0f, 0xf0,
-        0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x0f, 0xf0,
-        0x07, 0xe0, 0x03, 0xc0, 0x01, 0x80, 0x00, 0x00 };
-    static const uchar mcur_ver_bits[] = {
-        0x00, 0x00, 0x03, 0x80, 0x07, 0xc0, 0x0f, 0xe0, 0x1f, 0xf0, 0x3f, 0xf8,
-        0x7f, 0xfc, 0x07, 0xc0, 0x07, 0xc0, 0x07, 0xc0, 0x7f, 0xfc, 0x3f, 0xf8,
-        0x1f, 0xf0, 0x0f, 0xe0, 0x07, 0xc0, 0x03, 0x80 };
-
-    static const uchar cur_hor_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x20, 0x18, 0x30,
-        0x38, 0x38, 0x7f, 0xfc, 0x7f, 0xfc, 0x38, 0x38, 0x18, 0x30, 0x08, 0x20,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-    static const uchar mcur_hor_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x04, 0x40, 0x0c, 0x60, 0x1c, 0x70, 0x3c, 0x78,
-        0x7f, 0xfc, 0xff, 0xfe, 0xff, 0xfe, 0xff, 0xfe, 0x7f, 0xfc, 0x3c, 0x78,
-        0x1c, 0x70, 0x0c, 0x60, 0x04, 0x40, 0x00, 0x00 };
-
-    static const uchar cur_fdiag_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xf8, 0x00, 0xf8, 0x00, 0x78,
-        0x00, 0xf8, 0x01, 0xd8, 0x23, 0x88, 0x37, 0x00, 0x3e, 0x00, 0x3c, 0x00,
-        0x3e, 0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00 };
-    static const uchar mcur_fdiag_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x07, 0xfc, 0x03, 0xfc, 0x01, 0xfc, 0x00, 0xfc,
-        0x41, 0xfc, 0x63, 0xfc, 0x77, 0xdc, 0x7f, 0x8c, 0x7f, 0x04, 0x7e, 0x00,
-        0x7f, 0x00, 0x7f, 0x80, 0x7f, 0xc0, 0x00, 0x00 };
-
-    static const uchar cur_bdiag_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x3e, 0x00, 0x3c, 0x00, 0x3e, 0x00,
-        0x37, 0x00, 0x23, 0x88, 0x01, 0xd8, 0x00, 0xf8, 0x00, 0x78, 0x00, 0xf8,
-        0x01, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-    static const uchar mcur_bdiag_bits[] = {
-        0x00, 0x00, 0x7f, 0xc0, 0x7f, 0x80, 0x7f, 0x00, 0x7e, 0x00, 0x7f, 0x04,
-        0x7f, 0x8c, 0x77, 0xdc, 0x63, 0xfc, 0x41, 0xfc, 0x00, 0xfc, 0x01, 0xfc,
-        0x03, 0xfc, 0x07, 0xfc, 0x00, 0x00, 0x00, 0x00 };
-
-    static const unsigned char cur_up_arrow_bits[] = {
-        0x00, 0x80, 0x01, 0x40, 0x01, 0x40, 0x02, 0x20, 0x02, 0x20, 0x04, 0x10,
-        0x04, 0x10, 0x08, 0x08, 0x0f, 0x78, 0x01, 0x40, 0x01, 0x40, 0x01, 0x40,
-        0x01, 0x40, 0x01, 0x40, 0x01, 0x40, 0x01, 0xc0 };
-    static const unsigned char mcur_up_arrow_bits[] = {
-        0x00, 0x80, 0x01, 0xc0, 0x01, 0xc0, 0x03, 0xe0, 0x03, 0xe0, 0x07, 0xf0,
-        0x07, 0xf0, 0x0f, 0xf8, 0x0f, 0xf8, 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0,
-        0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0, 0x01, 0xc0 };
-#endif
-    const uchar *cursorData = 0;
-    const uchar *cursorMaskData = 0;
-#ifdef QT_MAC_USE_COCOA
-    switch (cshape) {                        // map Q cursor to MAC cursor
-    case Qt::BitmapCursor: {
-        if (pixmap.isNull())
-            initCursorFromBitmap();
-        else
-            initCursorFromPixmap();
-        break; }
-    case Qt::BlankCursor: {
-        pixmap = QPixmap(16, 16);
-        pixmap.fill(Qt::transparent);
-        initCursorFromPixmap();
-        break; }
-    case Qt::ArrowCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor arrowCursor];
-        break; }
-    case Qt::CrossCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor crosshairCursor];
-        break; }
-    case Qt::WaitCursor: {
-        pixmap = QPixmap(QLatin1String(":/trolltech/mac/cursors/images/spincursor.png"));
-        initCursorFromPixmap();
-        break; }
-    case Qt::IBeamCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor IBeamCursor];
-        break; }
-    case Qt::SizeAllCursor: {
-        pixmap = QPixmap(QLatin1String(":/trolltech/mac/cursors/images/pluscursor.png"));
-        initCursorFromPixmap();
-        break; }
-    case Qt::WhatsThisCursor: { //for now just use the pointing hand
-    case Qt::PointingHandCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor pointingHandCursor];
-        break; }
-    case Qt::BusyCursor: {
-        pixmap = QPixmap(QLatin1String(":/trolltech/mac/cursors/images/waitcursor.png"));
-        initCursorFromPixmap();
-        break; }
-    case Qt::SplitVCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor resizeUpDownCursor];
-        break; }
-    case Qt::SplitHCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor resizeLeftRightCursor];
-        break; }
-    case Qt::ForbiddenCursor: {
-        pixmap = QPixmap(QLatin1String(":/trolltech/mac/cursors/images/forbiddencursor.png"));
-        initCursorFromPixmap();
-        break; }
-    case Qt::OpenHandCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor openHandCursor];
-        break;
-    case Qt::ClosedHandCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor closedHandCursor];
-        break;
-    case Qt::DragCopyCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        if ([NSCursor respondsToSelector:@selector(dragCopyCursor)])
-            curs.cp.nscursor = [NSCursor performSelector:@selector(dragCopyCursor)];
-        break;
-    case Qt::DragMoveCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.cp.nscursor = [NSCursor arrowCursor];
-        break;
-    case Qt::DragLinkCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        if ([NSCursor respondsToSelector:@selector(dragLinkCursor)])
-            curs.cp.nscursor = [NSCursor performSelector:@selector(dragLinkCursor)];
-        break;
-#define QT_USE_APPROXIMATE_CURSORS
-#ifdef QT_USE_APPROXIMATE_CURSORS
-    case Qt::SizeVerCursor:
-        cursorData = cur_ver_bits;
-        cursorMaskData = mcur_ver_bits;
-        hx = hy = 8;
-        break;
-    case Qt::SizeHorCursor:
-        cursorData = cur_hor_bits;
-        cursorMaskData = mcur_hor_bits;
-        hx = hy = 8;
-        break;
-    case Qt::SizeBDiagCursor:
-        cursorData = cur_fdiag_bits;
-        cursorMaskData = mcur_fdiag_bits;
-        hx = hy = 8;
-        break;
-    case Qt::SizeFDiagCursor:
-        cursorData = cur_bdiag_bits;
-        cursorMaskData = mcur_bdiag_bits;
-        hx = hy = 8;
-        break;
-    case Qt::UpArrowCursor:
-        cursorData = cur_up_arrow_bits;
-        cursorMaskData = mcur_up_arrow_bits;
-        hx = 8;
-        break;
-#endif
-    default:
-        qWarning("Qt: QCursor::update: Invalid cursor shape %d", cshape);
-        return;
-    }
-#else
-    // Carbon
-    switch (cshape) {                        // map Q cursor to MAC cursor
-    case Qt::BitmapCursor: {
-        if (pixmap.isNull())
-            initCursorFromBitmap();
-        else
-            initCursorFromPixmap();
-        break; }
-    case Qt::BlankCursor: {
-        pixmap = QPixmap(16, 16);
-        pixmap.fill(Qt::transparent);
-        initCursorFromPixmap();
-        break; }
-    case Qt::ArrowCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeArrowCursor;
-        break; }
-    case Qt::CrossCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeCrossCursor;
-        break; }
-    case Qt::WaitCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeWatchCursor;
-        break; }
-    case Qt::IBeamCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeIBeamCursor;
-        break; }
-    case Qt::SizeAllCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemePlusCursor;
-        break; }
-    case Qt::WhatsThisCursor: { //for now just use the pointing hand
-    case Qt::PointingHandCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemePointingHandCursor;
-        break; }
-    case Qt::BusyCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeSpinningCursor;
-        break; }
-    case Qt::SplitVCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeResizeUpDownCursor;
-        break; }
-    case Qt::SplitHCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeResizeLeftRightCursor;
-        break; }
-    case Qt::ForbiddenCursor: {
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeNotAllowedCursor;
-        break; }
-    case Qt::OpenHandCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeOpenHandCursor;
-        break;
-    case Qt::ClosedHandCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeClosedHandCursor;
-        break;
-    case Qt::DragMoveCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeArrowCursor;
-        break;
-    case Qt::DragCopyCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeCopyArrowCursor;
-        break;
-    case Qt::DragLinkCursor:
-        type = QCursorData::TYPE_ThemeCursor;
-        curs.tc.curs = kThemeAliasArrowCursor;
-        break;
-#define QT_USE_APPROXIMATE_CURSORS
-#ifdef QT_USE_APPROXIMATE_CURSORS
-    case Qt::SizeVerCursor:
-        cursorData = cur_ver_bits;
-        cursorMaskData = mcur_ver_bits;
-        hx = hy = 8;
-        break;
-    case Qt::SizeHorCursor:
-        cursorData = cur_hor_bits;
-        cursorMaskData = mcur_hor_bits;
-        hx = hy = 8;
-        break;
-    case Qt::SizeBDiagCursor:
-        cursorData = cur_fdiag_bits;
-        cursorMaskData = mcur_fdiag_bits;
-        hx = hy = 8;
-        break;
-    case Qt::SizeFDiagCursor:
-        cursorData = cur_bdiag_bits;
-        cursorMaskData = mcur_bdiag_bits;
-        hx = hy = 8;
-        break;
-    case Qt::UpArrowCursor:
-        cursorData = cur_up_arrow_bits;
-        cursorMaskData = mcur_up_arrow_bits;
-        hx = 8;
-        break;
-#endif
-    default:
-        qWarning("Qt: QCursor::update: Invalid cursor shape %d", cshape);
-        return;
-    }
-#endif
-
-    if (cursorData) {
-        bm = new QBitmap(QBitmap::fromData(QSize(16, 16), cursorData,
-                    QImage::Format_Mono));
-        bmm = new QBitmap(QBitmap::fromData(QSize(16, 16), cursorMaskData,
-                    QImage::Format_Mono));
-        initCursorFromBitmap();
-    }
-
-#if 0
-    if(type == QCursorData::TYPE_CursPtr && curs.cp.hcurs && curs.cp.my_cursor) {
-        curs.cp.hcurs->hotSpot.h = hx >= 0 ? hx : 8;
-        curs.cp.hcurs->hotSpot.v = hy >= 0 ? hy : 8;
-    }
-#endif
-}
-
-QT_END_NAMESPACE
-
-#include "qrc_macresources.cpp"
diff --git a/src/gui/kernel/qcursor_win.cpp b/src/gui/kernel/qcursor_win.cpp
deleted file mode 100644 (file)
index c1be2ad..0000000
+++ /dev/null
@@ -1,493 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qcursor_p.h>
-#include <qbitmap.h>
-#include <qcursor.h>
-
-#ifndef QT_NO_CURSOR
-
-#include <qimage.h>
-#include <qt_windows.h>
-#include <qapplication_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
-  Internal QCursorData class
- *****************************************************************************/
-
-QCursorData::QCursorData(Qt::CursorShape s)
-  : cshape(s), bm(0), bmm(0), hx(0), hy(0), hcurs(0)
-{
-    ref = 1;
-}
-
-QCursorData::~QCursorData()
-{
-    delete bm;
-    delete bmm;
-#if !defined(Q_WS_WINCE) || defined(GWES_ICONCURS)
-    if (hcurs)
-        DestroyCursor(hcurs);
-#endif
-}
-
-
-QCursorData *QCursorData::setBitmap(const QBitmap &bitmap, const QBitmap &mask, int hotX, int hotY)
-{
-    if (!QCursorData::initialized)
-        QCursorData::initialize();
-    if (bitmap.depth() != 1 || mask.depth() != 1 || bitmap.size() != mask.size()) {
-        qWarning("QCursor: Cannot create bitmap cursor; invalid bitmap(s)");
-        QCursorData *c = qt_cursorTable[0];
-        c->ref.ref();
-        return c;
-    }
-    QCursorData *d = new QCursorData;
-    d->bm  = new QBitmap(bitmap);
-    d->bmm = new QBitmap(mask);
-    d->hcurs = 0;
-    d->cshape = Qt::BitmapCursor;
-    d->hx = hotX >= 0 ? hotX : bitmap.width()/2;
-    d->hy = hotY >= 0 ? hotY : bitmap.height()/2;
-    return d;
-}
-
-HCURSOR QCursor::handle() const
-{
-    if (!QCursorData::initialized)
-        QCursorData::initialize();
-    if (!d->hcurs)
-        d->update();
-    return d->hcurs;
-}
-
-QCursor::QCursor(HCURSOR handle)
-{
-    d = new QCursorData(Qt::CustomCursor);
-    d->hcurs = handle;
-}
-
-#endif //QT_NO_CURSOR
-
-QPoint QCursor::pos()
-{
-    POINT p;
-    GetCursorPos(&p);
-    return QPoint(p.x, p.y);
-}
-
-void QCursor::setPos(int x, int y)
-{
-    SetCursorPos(x, y);
-}
-
-#ifndef QT_NO_CURSOR
-
-extern HBITMAP qt_createIconMask(const QBitmap &bitmap);
-
-static HCURSOR create32BitCursor(const QPixmap &pixmap, int hx, int hy)
-{
-    HCURSOR cur = 0;
-#if !defined(Q_WS_WINCE)
-    QBitmap mask = pixmap.mask();
-    if (mask.isNull()) {
-        mask = QBitmap(pixmap.size());
-        mask.fill(Qt::color1);
-    }
-
-    HBITMAP ic = pixmap.toWinHBITMAP(QPixmap::Alpha);
-    HBITMAP im = qt_createIconMask(mask);
-
-    ICONINFO ii;
-    ii.fIcon     = 0;
-    ii.xHotspot  = hx;
-    ii.yHotspot  = hy;
-    ii.hbmMask   = im;
-    ii.hbmColor  = ic;
-
-    cur = CreateIconIndirect(&ii);
-
-    DeleteObject(ic);
-    DeleteObject(im);
-#elif defined(GWES_ICONCURS)
-    QImage bbits, mbits;
-    bool invb, invm;
-    bbits = pixmap.toImage().convertToFormat(QImage::Format_Mono);
-    mbits = pixmap.toImage().convertToFormat(QImage::Format_Mono);
-    invb = bbits.colorCount() > 1 && qGray(bbits.color(0)) < qGray(bbits.color(1));
-    invm = mbits.colorCount() > 1 && qGray(mbits.color(0)) < qGray(mbits.color(1));
-
-    int sysW = GetSystemMetrics(SM_CXCURSOR);
-    int sysH = GetSystemMetrics(SM_CYCURSOR);
-    int sysN = qMax(1, sysW / 8);
-    int n = qMax(1, bbits.width() / 8);
-    int h = bbits.height();
-
-    uchar* xBits = new uchar[sysH * sysN];
-    uchar* xMask = new uchar[sysH * sysN];
-    int x = 0;
-    for (int i = 0; i < sysH; ++i) {
-        if (i >= h) {
-            memset(&xBits[x] , 255, sysN);
-            memset(&xMask[x] ,   0, sysN);
-            x += sysN;
-        } else {
-            int fillWidth = n > sysN ? sysN : n;
-            uchar *bits = bbits.scanLine(i);
-            uchar *mask = mbits.scanLine(i);
-            for (int j = 0; j < fillWidth; ++j) {
-                uchar b = bits[j];
-                uchar m = mask[j];
-                if (invb)
-                    b ^= 0xFF;
-                if (invm)
-                    m ^= 0xFF;
-                xBits[x] = ~m;
-                xMask[x] = b ^ m;
-                ++x;
-            }
-            for (int j = fillWidth; j < sysN; ++j ) {
-                xBits[x] = 255;
-                xMask[x] = 0;
-                ++x;
-            }
-        }
-    }
-
-    cur = CreateCursor(qWinAppInst(), hx, hy, sysW, sysH,
-        xBits, xMask);
-#else
-    Q_UNUSED(pixmap);
-    Q_UNUSED(hx);
-    Q_UNUSED(hy);
-#endif
-    return cur;
-}
-
-void QCursorData::update()
-{
-    if (!QCursorData::initialized)
-        QCursorData::initialize();
-    if (hcurs)
-        return;
-
-    if (cshape == Qt::BitmapCursor && !pixmap.isNull()) {
-        hcurs = create32BitCursor(pixmap, hx, hy);
-        if (hcurs)
-            return;
-    }
-
-
-    // Non-standard Windows cursors are created from bitmaps
-
-    static const uchar vsplit_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x80, 0x00, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xe0, 0x03, 0x00,
-        0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
-        0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xff, 0x7f, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x7f, 0x00,
-        0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
-        0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xe0, 0x03, 0x00,
-        0x00, 0xc0, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-    static const uchar vsplitm_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00,
-        0x00, 0xc0, 0x01, 0x00, 0x00, 0xe0, 0x03, 0x00, 0x00, 0xf0, 0x07, 0x00,
-        0x00, 0xf8, 0x0f, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xc0, 0x01, 0x00,
-        0x00, 0xc0, 0x01, 0x00, 0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00,
-        0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0x00,
-        0x80, 0xff, 0xff, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0xc0, 0x01, 0x00,
-        0x00, 0xc0, 0x01, 0x00, 0x00, 0xf8, 0x0f, 0x00, 0x00, 0xf0, 0x07, 0x00,
-        0x00, 0xe0, 0x03, 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-    static const uchar hsplit_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
-        0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
-        0x00, 0x41, 0x82, 0x00, 0x80, 0x41, 0x82, 0x01, 0xc0, 0x7f, 0xfe, 0x03,
-        0x80, 0x41, 0x82, 0x01, 0x00, 0x41, 0x82, 0x00, 0x00, 0x40, 0x02, 0x00,
-        0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00,
-        0x00, 0x40, 0x02, 0x00, 0x00, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-    static const uchar hsplitm_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00,
-        0x00, 0xe0, 0x07, 0x00, 0x00, 0xe2, 0x47, 0x00, 0x00, 0xe3, 0xc7, 0x00,
-        0x80, 0xe3, 0xc7, 0x01, 0xc0, 0xff, 0xff, 0x03, 0xe0, 0xff, 0xff, 0x07,
-        0xc0, 0xff, 0xff, 0x03, 0x80, 0xe3, 0xc7, 0x01, 0x00, 0xe3, 0xc7, 0x00,
-        0x00, 0xe2, 0x47, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00,
-        0x00, 0xe0, 0x07, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-    static const uchar phand_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x80, 0x04, 0x00, 0x00,
-        0x80, 0x04, 0x00, 0x00, 0x80, 0x04, 0x00, 0x00, 0x80, 0x04, 0x00, 0x00,
-        0x80, 0x1c, 0x00, 0x00, 0x80, 0xe4, 0x00, 0x00, 0x80, 0x24, 0x03, 0x00,
-        0x80, 0x24, 0x05, 0x00, 0xb8, 0x24, 0x09, 0x00, 0xc8, 0x00, 0x09, 0x00,
-        0x88, 0x00, 0x08, 0x00, 0x90, 0x00, 0x08, 0x00, 0xa0, 0x00, 0x08, 0x00,
-        0x20, 0x00, 0x08, 0x00, 0x40, 0x00, 0x08, 0x00, 0x40, 0x00, 0x04, 0x00,
-        0x80, 0x00, 0x04, 0x00, 0x80, 0x00, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00,
-        0x00, 0x01, 0x02, 0x00, 0x00, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-
-   static const uchar phandm_bits[] = {
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x80, 0x07, 0x00, 0x00,
-        0x80, 0x07, 0x00, 0x00, 0x80, 0x07, 0x00, 0x00, 0x80, 0x07, 0x00, 0x00,
-        0x80, 0x1f, 0x00, 0x00, 0x80, 0xff, 0x00, 0x00, 0x80, 0xff, 0x03, 0x00,
-        0x80, 0xff, 0x07, 0x00, 0xb8, 0xff, 0x0f, 0x00, 0xf8, 0xff, 0x0f, 0x00,
-        0xf8, 0xff, 0x0f, 0x00, 0xf0, 0xff, 0x0f, 0x00, 0xe0, 0xff, 0x0f, 0x00,
-        0xe0, 0xff, 0x0f, 0x00, 0xc0, 0xff, 0x0f, 0x00, 0xc0, 0xff, 0x07, 0x00,
-        0x80, 0xff, 0x07, 0x00, 0x80, 0xff, 0x07, 0x00, 0x00, 0xff, 0x03, 0x00,
-        0x00, 0xff, 0x03, 0x00, 0x00, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
-
-   static const uchar openhand_bits[] = {
-        0x80,0x01,0x58,0x0e,0x64,0x12,0x64,0x52,0x48,0xb2,0x48,0x92,
-        0x16,0x90,0x19,0x80,0x11,0x40,0x02,0x40,0x04,0x40,0x04,0x20,
-        0x08,0x20,0x10,0x10,0x20,0x10,0x00,0x00};
-    static const uchar openhandm_bits[] = {
-       0x80,0x01,0xd8,0x0f,0xfc,0x1f,0xfc,0x5f,0xf8,0xff,0xf8,0xff,
-       0xf6,0xff,0xff,0xff,0xff,0x7f,0xfe,0x7f,0xfc,0x7f,0xfc,0x3f,
-       0xf8,0x3f,0xf0,0x1f,0xe0,0x1f,0x00,0x00};
-    static const uchar closedhand_bits[] = {
-        0x00,0x00,0x00,0x00,0x00,0x00,0xb0,0x0d,0x48,0x32,0x08,0x50,
-        0x10,0x40,0x18,0x40,0x04,0x40,0x04,0x20,0x08,0x20,0x10,0x10,
-        0x20,0x10,0x20,0x10,0x00,0x00,0x00,0x00};
-    static const uchar closedhandm_bits[] = {
-        0x00,0x00,0x00,0x00,0x00,0x00,0xb0,0x0d,0xf8,0x3f,0xf8,0x7f,
-        0xf0,0x7f,0xf8,0x7f,0xfc,0x7f,0xfc,0x3f,0xf8,0x3f,0xf0,0x1f,
-        0xe0,0x1f,0xe0,0x1f,0x00,0x00,0x00,0x00};
-
-    static const uchar * const cursor_bits32[] = {
-        vsplit_bits, vsplitm_bits, hsplit_bits, hsplitm_bits,
-        phand_bits, phandm_bits
-    };
-
-    wchar_t *sh = 0;
-    switch (cshape) {                        // map to windows cursor
-    case Qt::ArrowCursor:
-        sh = IDC_ARROW;
-        break;
-    case Qt::UpArrowCursor:
-        sh = IDC_UPARROW;
-        break;
-    case Qt::CrossCursor:
-        sh = IDC_CROSS;
-        break;
-    case Qt::WaitCursor:
-        sh = IDC_WAIT;
-        break;
-    case Qt::IBeamCursor:
-        sh = IDC_IBEAM;
-        break;
-    case Qt::SizeVerCursor:
-        sh = IDC_SIZENS;
-        break;
-    case Qt::SizeHorCursor:
-        sh = IDC_SIZEWE;
-        break;
-    case Qt::SizeBDiagCursor:
-        sh = IDC_SIZENESW;
-        break;
-    case Qt::SizeFDiagCursor:
-        sh = IDC_SIZENWSE;
-        break;
-    case Qt::SizeAllCursor:
-        sh = IDC_SIZEALL;
-        break;
-    case Qt::ForbiddenCursor:
-        sh = IDC_NO;
-        break;
-    case Qt::WhatsThisCursor:
-        sh = IDC_HELP;
-        break;
-    case Qt::BusyCursor:
-        sh = IDC_APPSTARTING;
-        break;
-    case Qt::PointingHandCursor:
-        sh = IDC_HAND;
-        break;
-    case Qt::BlankCursor:
-    case Qt::SplitVCursor:
-    case Qt::SplitHCursor:
-    case Qt::OpenHandCursor:
-    case Qt::ClosedHandCursor:
-    case Qt::BitmapCursor: {
-        QImage bbits, mbits;
-        bool invb, invm;
-        if (cshape == Qt::BlankCursor) {
-            bbits = QImage(32, 32, QImage::Format_Mono);
-            bbits.fill(0);                // ignore color table
-            mbits = bbits.copy();
-            hx = hy = 16;
-            invb = invm = false;
-        } else if (cshape == Qt::OpenHandCursor || cshape == Qt::ClosedHandCursor) {
-            bool open = cshape == Qt::OpenHandCursor;
-            QBitmap cb = QBitmap::fromData(QSize(16, 16), open ? openhand_bits : closedhand_bits);
-            QBitmap cm = QBitmap::fromData(QSize(16, 16), open ? openhandm_bits : closedhandm_bits);
-            bbits = cb.toImage().convertToFormat(QImage::Format_Mono);
-            mbits = cm.toImage().convertToFormat(QImage::Format_Mono);
-            hx = hy = 8;
-            invb = invm = false;
-        } else if (cshape != Qt::BitmapCursor) {
-            int i = cshape - Qt::SplitVCursor;
-            QBitmap cb = QBitmap::fromData(QSize(32, 32), cursor_bits32[i * 2]);
-            QBitmap cm = QBitmap::fromData(QSize(32, 32), cursor_bits32[i * 2 + 1]);
-            bbits = cb.toImage().convertToFormat(QImage::Format_Mono);
-            mbits = cm.toImage().convertToFormat(QImage::Format_Mono);
-            if (cshape == Qt::PointingHandCursor) {
-                hx = 7;
-                hy = 0;
-            } else
-                hx = hy = 16;
-            invb = invm = false;
-        } else {
-            bbits = bm->toImage().convertToFormat(QImage::Format_Mono);
-            mbits = bmm->toImage().convertToFormat(QImage::Format_Mono);
-            invb = bbits.colorCount() > 1 && qGray(bbits.color(0)) < qGray(bbits.color(1));
-            invm = mbits.colorCount() > 1 && qGray(mbits.color(0)) < qGray(mbits.color(1));
-        }
-        int n = qMax(1, bbits.width() / 8);
-        int h = bbits.height();
-#if !defined(Q_WS_WINCE)
-        uchar* xBits = new uchar[h * n];
-        uchar* xMask = new uchar[h * n];
-        int x = 0;
-        for (int i = 0; i < h; ++i) {
-            uchar *bits = bbits.scanLine(i);
-            uchar *mask = mbits.scanLine(i);
-            for (int j = 0; j < n; ++j) {
-                uchar b = bits[j];
-                uchar m = mask[j];
-                if (invb)
-                    b ^= 0xff;
-                if (invm)
-                    m ^= 0xff;
-                xBits[x] = ~m;
-                xMask[x] = b ^ m;
-                ++x;
-            }
-        }
-        hcurs = CreateCursor(qWinAppInst(), hx, hy, bbits.width(), bbits.height(),
-                                   xBits, xMask);
-        delete [] xBits;
-        delete [] xMask;
-#elif defined(GWES_ICONCURS) // Q_WS_WINCE
-        // Windows CE only supports fixed cursor size.
-        int sysW = GetSystemMetrics(SM_CXCURSOR);
-        int sysH = GetSystemMetrics(SM_CYCURSOR);
-        int sysN = qMax(1, sysW / 8);
-        uchar* xBits = new uchar[sysH * sysN];
-        uchar* xMask = new uchar[sysH * sysN];
-        int x = 0;
-        for (int i = 0; i < sysH; ++i) {
-            if (i >= h) {
-                memset(&xBits[x] , 255, sysN);
-                memset(&xMask[x] ,   0, sysN);
-                x += sysN;
-            } else {
-                int fillWidth = n > sysN ? sysN : n;
-                uchar *bits = bbits.scanLine(i);
-                uchar *mask = mbits.scanLine(i);
-                for (int j = 0; j < fillWidth; ++j) {
-                    uchar b = bits[j];
-                    uchar m = mask[j];
-                    if (invb)
-                        b ^= 0xFF;
-                    if (invm)
-                        m ^= 0xFF;
-                    xBits[x] = ~m;
-                    xMask[x] = b ^ m;
-                    ++x;
-                }
-                for (int j = fillWidth; j < sysN; ++j ) {
-                    xBits[x] = 255;
-                    xMask[x] = 0;
-                    ++x;
-                }
-            }
-        }
-
-        hcurs = CreateCursor(qWinAppInst(), hx, hy, sysW, sysH,
-                                   xBits, xMask);
-        delete [] xBits;
-        delete [] xMask;
-#else
-        Q_UNUSED(n);
-        Q_UNUSED(h);
-#endif
-        return;
-    }
-    case Qt::DragCopyCursor:
-    case Qt::DragMoveCursor:
-    case Qt::DragLinkCursor: {
-        QPixmap pixmap = QApplicationPrivate::instance()->getPixmapCursor(cshape);
-        hcurs = create32BitCursor(pixmap, hx, hy);
-    }
-        return;
-    default:
-        qWarning("QCursor::update: Invalid cursor shape %d", cshape);
-        return;
-    }
-#ifdef Q_WS_WINCE
-    hcurs = LoadCursor(0, sh);
-#else
-    hcurs = (HCURSOR)LoadImage(0, sh, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED);
-#endif
-}
-
-QT_END_NAMESPACE
-#endif // QT_NO_CURSOR
diff --git a/src/gui/kernel/qdesktopwidget_mac.mm b/src/gui/kernel/qdesktopwidget_mac.mm
deleted file mode 100644 (file)
index 6a12fda..0000000
+++ /dev/null
@@ -1,252 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#import <Cocoa/Cocoa.h>
-
-#include "qapplication.h"
-#include "qdesktopwidget.h"
-#include <qt_mac_p.h>
-#include "qwidget_p.h"
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qdesktopwidget_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-/*****************************************************************************
-  Externals
- *****************************************************************************/
-
-/*****************************************************************************
-  QDesktopWidget member functions
- *****************************************************************************/
-
-Q_GLOBAL_STATIC(QDesktopWidgetImplementation, qdesktopWidgetImplementation)
-
-QDesktopWidgetImplementation::QDesktopWidgetImplementation()
-    : appScreen(0)
-{
-    onResize();
-}
-
-QDesktopWidgetImplementation::~QDesktopWidgetImplementation()
-{
-}
-
-QDesktopWidgetImplementation *QDesktopWidgetImplementation::instance()
-{
-    return qdesktopWidgetImplementation();
-}
-
-QRect QDesktopWidgetImplementation::availableRect(int screenIndex) const
-{
-    if (screenIndex < 0 || screenIndex >= screenCount)
-        screenIndex = appScreen;
-
-       return availableRects[screenIndex].toRect(); 
-}
-
-QRect QDesktopWidgetImplementation::screenRect(int screenIndex) const
-{
-    if (screenIndex < 0 || screenIndex >= screenCount)
-        screenIndex = appScreen;
-
-    return screenRects[screenIndex].toRect();
-}
-
-void QDesktopWidgetImplementation::onResize()
-{
-    QMacCocoaAutoReleasePool pool; 
-    NSArray *displays = [NSScreen screens]; 
-    screenCount = [displays count]; 
-    screenRects.clear(); 
-    availableRects.clear(); 
-    NSRect primaryRect = [[displays objectAtIndex:0] frame]; 
-    for (int i = 0; i<screenCount; i++) {
-        NSRect r = [[displays objectAtIndex:i] frame];
-        int flippedY = - r.origin.y +                  // account for position offset and
-              primaryRect.size.height - r.size.height; // height difference. 
-        screenRects.append(QRectF(r.origin.x, flippedY, 
-            r.size.width, r.size.height)); 
-
-        r = [[displays objectAtIndex:i] visibleFrame];
-        flippedY = - r.origin.y +                      // account for position offset and
-              primaryRect.size.height - r.size.height; // height difference. 
-        availableRects.append(QRectF(r.origin.x, flippedY, 
-                r.size.width, r.size.height)); 
-    }
-}
-
-
-
-QDesktopWidget::QDesktopWidget()
-    : QWidget(0, Qt::Desktop)
-{
-    setObjectName(QLatin1String("desktop"));
-    setAttribute(Qt::WA_WState_Visible);
-}
-
-QDesktopWidget::~QDesktopWidget()
-{
-}
-
-bool QDesktopWidget::isVirtualDesktop() const
-{
-    return true;
-}
-
-int QDesktopWidget::primaryScreen() const
-{
-    return qdesktopWidgetImplementation()->appScreen;
-}
-
-QWidget *QDesktopWidget::screen(int)
-{
-    return this;
-}
-
-const QRect QDesktopWidget::availableGeometry(int screen) const
-{
-    return qdesktopWidgetImplementation()->availableRect(screen);
-}
-
-const QRect QDesktopWidget::screenGeometry(int screen) const
-{
-    return qdesktopWidgetImplementation()->screenRect(screen);
-}
-
-int QDesktopWidget::screenNumber(const QWidget *widget) const
-{
-    QDesktopWidgetImplementation *d = qdesktopWidgetImplementation();
-    if (!widget)
-        return d->appScreen;
-    QRect frame = widget->frameGeometry();
-    if (!widget->isWindow())
-        frame.moveTopLeft(widget->mapToGlobal(QPoint(0,0)));
-    int maxSize = -1, maxScreen = -1;
-    for (int i = 0; i < d->screenCount; ++i) {
-        QRect rr = d->screenRect(i);
-        QRect sect = rr.intersected(frame);
-        int size = sect.width() * sect.height();
-        if (size > maxSize && sect.width() > 0 && sect.height() > 0) {
-            maxSize = size;
-            maxScreen = i;
-        }
-    }
-    return maxScreen;
-}
-
-int QDesktopWidget::screenNumber(const QPoint &point) const
-{
-    QDesktopWidgetImplementation *d = qdesktopWidgetImplementation();
-    int closestScreen = -1;
-    int shortestDistance = INT_MAX;
-    for (int i = 0; i < d->screenCount; ++i) {
-        QRect rr = d->screenRect(i);
-        int thisDistance = QWidgetPrivate::pointToRect(point, rr);
-        if (thisDistance < shortestDistance) {
-            shortestDistance = thisDistance;
-            closestScreen = i;
-        }
-    }
-    return closestScreen;
-}
-
-void QDesktopWidget::resizeEvent(QResizeEvent *)
-{
-    QDesktopWidgetImplementation *d = qdesktopWidgetImplementation();
-
-    const int oldScreenCount = d->screenCount;
-    const QVector<QRectF> oldRects(d->screenRects);
-    const QVector<QRectF> oldWorks(d->availableRects);
-
-    d->onResize();
-
-    for (int i = 0; i < qMin(oldScreenCount, d->screenCount); ++i) {
-        if (oldRects.at(i) != d->screenRects.at(i))
-            emit resized(i);
-    }
-    for (int i = 0; i < qMin(oldScreenCount, d->screenCount); ++i) {
-        if (oldWorks.at(i) != d->availableRects.at(i))
-            emit workAreaResized(i);
-    }
-
-    if (oldScreenCount != d->screenCount)
-        emit screenCountChanged(d->screenCount);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qdesktopwidget_mac_p.h b/src/gui/kernel/qdesktopwidget_mac_p.h
deleted file mode 100644 (file)
index 24d08d3..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#include <qrect.h>
-
-QT_BEGIN_NAMESPACE
-
-class QDesktopWidgetImplementation
-{
-public:
-    QDesktopWidgetImplementation();
-    ~QDesktopWidgetImplementation();
-    static QDesktopWidgetImplementation *instance();
-
-    int appScreen;
-    int screenCount;
-
-    QVector<QRectF> availableRects; 
-    QVector<QRectF> screenRects; 
-
-    QRect availableRect(int screenIndex) const;
-    QRect screenRect(int screenIndex) const;
-    void onResize();
-};
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qdesktopwidget_win.cpp b/src/gui/kernel/qdesktopwidget_win.cpp
deleted file mode 100644 (file)
index 5e2f2d0..0000000
+++ /dev/null
@@ -1,387 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdesktopwidget.h"
-#include "qt_windows.h"
-#include "qapplication_p.h"
-#include <qsystemlibrary_p.h>
-#include <qvector.h>
-#include <limits.h>
-#ifdef Q_WS_WINCE
-#include <sipapi.h>
-#endif
-#include "qwidget_p.h"
-#include "qdebug.h"
-
-QT_BEGIN_NAMESPACE
-
-class QDesktopWidgetPrivate : public QWidgetPrivate
-{
-public:
-    QDesktopWidgetPrivate();
-    ~QDesktopWidgetPrivate();
-
-    static void init(QDesktopWidget *that);
-    static void cleanup();
-    static int screenCount;
-    static int primaryScreen;
-
-    static QVector<QRect> *rects;
-    static QVector<QRect> *workrects;
-
-    struct MONITORINFO
-    {
-        DWORD   cbSize;
-        RECT    rcMonitor;
-        RECT    rcWork;
-        DWORD   dwFlags;
-    };
-
-    typedef BOOL (WINAPI *InfoFunc)(HMONITOR, MONITORINFO*);
-    typedef BOOL (QT_WIN_CALLBACK *EnumProc)(HMONITOR, HDC, LPRECT, LPARAM);
-    typedef BOOL (WINAPI *EnumFunc)(HDC, LPCRECT, EnumProc, LPARAM);
-
-    static EnumFunc enumDisplayMonitors;
-    static InfoFunc getMonitorInfo;
-    static int refcount;
-};
-
-int QDesktopWidgetPrivate::screenCount = 1;
-int QDesktopWidgetPrivate::primaryScreen = 0;
-QDesktopWidgetPrivate::EnumFunc QDesktopWidgetPrivate::enumDisplayMonitors = 0;
-QDesktopWidgetPrivate::InfoFunc QDesktopWidgetPrivate::getMonitorInfo = 0;
-QVector<QRect> *QDesktopWidgetPrivate::rects = 0;
-QVector<QRect> *QDesktopWidgetPrivate::workrects = 0;
-static int screen_number = 0;
-int QDesktopWidgetPrivate::refcount = 0;
-#ifdef Q_WS_WINCE_WM
-// Use SIP information, if available
-// SipGetInfo is not supported by SSDK (no definition!). 
-static inline void qt_get_sip_info(QRect &rect)
-{
-    SIPINFO sip;
-    memset(&sip, 0, sizeof(SIPINFO));
-    sip.cbSize = sizeof(SIPINFO);
-    if (SipGetInfo(&sip))
-        rect = QRect(QPoint(sip.rcVisibleDesktop.left, sip.rcVisibleDesktop.top),
-        QPoint(sip.rcVisibleDesktop.right - 1, sip.rcVisibleDesktop.bottom - 1));
-}
-#endif
-
-
-BOOL QT_WIN_CALLBACK enumCallback(HMONITOR hMonitor, HDC, LPRECT, LPARAM)
-{
-    QDesktopWidgetPrivate::screenCount++;
-    QDesktopWidgetPrivate::rects->resize(QDesktopWidgetPrivate::screenCount);
-    QDesktopWidgetPrivate::workrects->resize(QDesktopWidgetPrivate::screenCount);
-    // Get the MONITORINFO block
-    QDesktopWidgetPrivate::MONITORINFO info;
-    memset(&info, 0, sizeof(QDesktopWidgetPrivate::MONITORINFO));
-    info.cbSize = sizeof(QDesktopWidgetPrivate::MONITORINFO);
-    BOOL res = QDesktopWidgetPrivate::getMonitorInfo(hMonitor, &info);
-    if (!res) {
-        (*QDesktopWidgetPrivate::rects)[screen_number] = QRect();
-        (*QDesktopWidgetPrivate::workrects)[screen_number] = QRect();
-        return true;
-    }
-
-    // Fill list of rects
-    RECT r = info.rcMonitor;
-    QRect qr(QPoint(r.left, r.top), QPoint(r.right - 1, r.bottom - 1));
-    (*QDesktopWidgetPrivate::rects)[screen_number] = qr;
-
-    r = info.rcWork;
-    qr = QRect(QPoint(r.left, r.top), QPoint(r.right - 1, r.bottom - 1));
-    (*QDesktopWidgetPrivate::workrects)[screen_number] = qr;
-
-    if (info.dwFlags & 0x00000001) //MONITORINFOF_PRIMARY
-        QDesktopWidgetPrivate::primaryScreen = screen_number;
-
-    ++screen_number;
-    // Stop the enumeration if we have them all
-    return true;
-}
-
-QDesktopWidgetPrivate::QDesktopWidgetPrivate()
-{
-    ++refcount;
-}
-
-void QDesktopWidgetPrivate::init(QDesktopWidget *that)
-{
-    if (rects)
-        return;
-
-    rects = new QVector<QRect>();
-    workrects = new QVector<QRect>();
-    screenCount = 0;
-
-#ifndef Q_OS_WINCE
-    QSystemLibrary user32Lib(QLatin1String("user32"));
-    enumDisplayMonitors = (EnumFunc)user32Lib.resolve("EnumDisplayMonitors");
-    getMonitorInfo = (InfoFunc)user32Lib.resolve("GetMonitorInfoW");
-
-    if (!enumDisplayMonitors || !getMonitorInfo) {
-        screenCount = GetSystemMetrics(80);  // SM_CMONITORS
-        rects->resize(screenCount);
-        for (int i = 0; i < screenCount; ++i)
-            rects->replace(i, that->rect());
-        return;
-    }
-    // Calls enumCallback
-    enumDisplayMonitors(0, 0, enumCallback, 0);
-    enumDisplayMonitors = 0;
-    getMonitorInfo = 0;
-#else
-    QSystemLibrary coreLib(QLatin1String("coredll"));
-    // CE >= 4.0 case
-    enumDisplayMonitors = (EnumFunc)coreLib.resolve("EnumDisplayMonitors");
-    getMonitorInfo = (InfoFunc)coreLib.resolve("GetMonitorInfo");
-
-    if ((!enumDisplayMonitors || !getMonitorInfo)) {
-        screenCount = GetSystemMetrics(SM_CMONITORS);
-        return;
-    }
-
-    if (!coreLib.isLoaded() || !enumDisplayMonitors || !getMonitorInfo) {
-        rects->resize(screenCount);
-        for (int i = 0; i < screenCount; ++i)
-            (*rects)[i] = that->rect();
-
-        RECT r;
-        SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
-        QRect qr = QRect(QPoint(r.left, r.top), QPoint(r.right - 1, r.bottom - 1));
-
-#if defined(Q_WS_WINCE_WM)
-        qt_get_sip_info(qr);
-#endif
-
-        workrects->resize(screenCount);
-        for (int j = 0; j < screenCount; ++j)
-            (*workrects)[j] = qr;
-        return;
-    }
-
-    // Calls enumCallback
-    enumDisplayMonitors(0, 0, enumCallback, 0);
-    enumDisplayMonitors = 0;
-    getMonitorInfo = 0;
-#endif // Q_WS_WINCE
-}
-
-QDesktopWidgetPrivate::~QDesktopWidgetPrivate()
-{
-    if (!--refcount)
-        cleanup();
-}
-
-void QDesktopWidgetPrivate::cleanup()
-{
-    screen_number = 0;
-    screenCount = 1;
-    primaryScreen = 0;
-    enumDisplayMonitors = 0;
-    getMonitorInfo = 0;
-    delete rects;
-    rects = 0;
-    delete workrects;
-    workrects = 0;
-}
-
-/*
-    \omit
-    Function is commented out in header
-    \fn void *QDesktopWidget::handle(int screen) const
-
-    Returns the window system handle of the display device with the
-    index \a screen, for low-level access.  Using this function is not
-    portable.
-
-    The return type varies with platform; see qwindowdefs.h for details.
-
-    \sa x11Display(), QPaintDevice::handle()
-    \endomit
-*/
-
-QDesktopWidget::QDesktopWidget()
-    : QWidget(*new QDesktopWidgetPrivate, 0, Qt::Desktop)
-{
-    setObjectName(QLatin1String("desktop"));
-    QDesktopWidgetPrivate::init(this);
-}
-
-QDesktopWidget::~QDesktopWidget()
-{
-}
-
-bool QDesktopWidget::isVirtualDesktop() const
-{
-    return true;
-}
-
-int QDesktopWidget::primaryScreen() const
-{
-    return d_func()->primaryScreen;
-}
-
-int QDesktopWidget::screenCount() const
-{
-    return d_func()->screenCount;
-}
-
-QWidget *QDesktopWidget::screen(int /* screen */)
-{
-    // It seems that a Qt::WType_Desktop cannot be moved?
-    return this;
-}
-
-//
-// MSVC 7.10 warns that d (the result of the expanded Q_D macro) as a local variable that is not referenced.
-// Therefore, we ignore that warning with the following pragmas
-// I've also tried to eliminate the macro, but to no use...
-// We pop it further down
-#ifdef Q_CC_MSVC
-# pragma warning(push)
-# pragma warning(disable : 4189)
-#endif
-const QRect QDesktopWidget::availableGeometry(int screen) const
-{
-    Q_D(const QDesktopWidget);
-#ifdef Q_WS_WINCE_WM
-    for(int i=0; i < d->workrects->size(); ++i)
-        qt_get_sip_info((*d->workrects)[i]);
-#endif
-    if (screen < 0 || screen >= d->screenCount)
-        screen = d->primaryScreen;
-
-    return d->workrects->at(screen);
-}
-
-const QRect QDesktopWidget::screenGeometry(int screen) const
-{
-    const QDesktopWidgetPrivate *d = d_func();
-    if (screen < 0 || screen >= d->screenCount)
-        screen = d->primaryScreen;
-
-    return d->rects->at(screen);
-}
-
-int QDesktopWidget::screenNumber(const QWidget *widget) const
-{
-    Q_D(const QDesktopWidget);
-    if (!widget)
-        return d->primaryScreen;
-
-    QRect frame = widget->frameGeometry();
-    if (!widget->isWindow())
-        frame.moveTopLeft(widget->mapToGlobal(QPoint(0,0)));
-
-    int maxSize = -1;
-    int maxScreen = -1;
-
-    for (int i = 0; i < d->screenCount; ++i) {
-        QRect sect = d->rects->at(i).intersected(frame);
-        int size = sect.width() * sect.height();
-        if (size > maxSize && sect.width() > 0 && sect.height() > 0) {
-            maxSize = size;
-            maxScreen = i;
-        }
-    }
-
-    return maxScreen;
-}
-
-int QDesktopWidget::screenNumber(const QPoint &point) const
-{
-    Q_D(const QDesktopWidget);
-
-    int closestScreen = -1;
-    int shortestDistance = INT_MAX;
-
-    for (int i = 0; i < d->screenCount; ++i) {
-        int thisDistance = d->pointToRect(point, d->rects->at(i));
-        if (thisDistance < shortestDistance) {
-            shortestDistance = thisDistance;
-            closestScreen = i;
-        }
-    }
-
-    return closestScreen;
-}
-
-void QDesktopWidget::resizeEvent(QResizeEvent *)
-{
-    Q_D(QDesktopWidget);
-    const QVector<QRect> oldrects(*d->rects);
-    const QVector<QRect> oldworkrects(*d->workrects);
-    int oldscreencount = d->screenCount;
-
-    QDesktopWidgetPrivate::cleanup();
-    QDesktopWidgetPrivate::init(this);
-#ifdef Q_WS_WINCE_WM
-    for(int i=0; i < d->workrects->size(); ++i)
-        qt_get_sip_info((*d->workrects)[i]);
-#endif
-
-    for (int i = 0; i < qMin(oldscreencount, d->screenCount); ++i) {
-        const QRect oldrect = oldrects[i];
-        const QRect newrect = d->rects->at(i);
-        if (oldrect != newrect)
-            emit resized(i);
-    }
-
-    for (int j = 0; j < qMin(oldscreencount, d->screenCount); ++j) {
-        const QRect oldrect = oldworkrects[j];
-        const QRect newrect = d->workrects->at(j);
-        if (oldrect != newrect)
-            emit workAreaResized(j);
-    }
-
-    if (oldscreencount != d->screenCount) {
-        emit screenCountChanged(d->screenCount);
-    }
-}
-
-#ifdef Q_CC_MSVC
-# pragma warning(pop)
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qdnd_mac.mm b/src/gui/kernel/qdnd_mac.mm
deleted file mode 100644 (file)
index 5089e25..0000000
+++ /dev/null
@@ -1,756 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qapplication.h"
-#ifndef QT_NO_DRAGANDDROP
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qurl.h"
-#include "qwidget.h"
-#include "qfile.h"
-#include "qfileinfo.h"
-#include <stdlib.h>
-#include <string.h>
-#ifndef QT_NO_ACCESSIBILITY
-# include "qaccessible.h"
-#endif
-
-#include <qapplication_p.h>
-#include <qwidget_p.h>
-#include <qdnd_p.h>
-#include <qt_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-QMacDndAnswerRecord qt_mac_dnd_answer_rec; 
-
-/*****************************************************************************
-  QDnD debug facilities
- *****************************************************************************/
-//#define DEBUG_DRAG_EVENTS
-//#define DEBUG_DRAG_PROMISES
-
-/*****************************************************************************
-  QDnD globals
- *****************************************************************************/
-bool qt_mac_in_drag = false;
-#ifndef QT_MAC_USE_COCOA
-static DragReference qt_mac_current_dragRef = 0;
-#endif
-
-/*****************************************************************************
-  Externals
- *****************************************************************************/
-extern void qt_mac_send_modifiers_changed(quint32, QObject *); //qapplication_mac.cpp
-extern uint qGlobalPostedEventsCount(); //qapplication.cpp
-extern RgnHandle qt_mac_get_rgn(); // qregion_mac.cpp
-extern void qt_mac_dispose_rgn(RgnHandle); // qregion_mac.cpp
-/*****************************************************************************
-  QDnD utility functions
- *****************************************************************************/
-
-//default pixmap
-static const int default_pm_hotx = -2;
-static const int default_pm_hoty = -16;
-#ifndef QT_MAC_USE_COCOA
-static const char * const default_pm[] = {
-    "13 9 3 1",
-    ".      c None",
-    "       c #000000",
-    "X      c #FFFFFF",
-    "X X X X X X X",
-    " X X X X X X ",
-    "X ......... X",
-    " X.........X ",
-    "X ......... X",
-    " X.........X ",
-    "X ......... X",
-    " X X X X X X ",
-    "X X X X X X X",
-};
-#endif
-
-//action management
-#ifdef DEBUG_DRAG_EVENTS
-# define MAP_MAC_ENUM(x) x, #x
-#else
-# define MAP_MAC_ENUM(x) x
-#endif
-struct mac_enum_mapper
-{
-    int mac_code;
-    int qt_code;
-#ifdef DEBUG_DRAG_EVENTS
-    char *qt_desc;
-#endif
-};
-#ifndef QT_MAC_USE_COCOA
-static mac_enum_mapper dnd_action_symbols[] = {
-    { kDragActionAlias, MAP_MAC_ENUM(Qt::LinkAction) },
-    { kDragActionMove, MAP_MAC_ENUM(Qt::MoveAction) },
-    { kDragActionGeneric, MAP_MAC_ENUM(Qt::CopyAction) },
-    { kDragActionCopy, MAP_MAC_ENUM(Qt::CopyAction) },
-    { 0, MAP_MAC_ENUM(0) }
-};
-static DragActions qt_mac_dnd_map_qt_actions(Qt::DropActions qActions)
-{
-    DragActions ret = kDragActionNothing;
-    for(int i = 0; dnd_action_symbols[i].qt_code; ++i) {
-        if(qActions & dnd_action_symbols[i].qt_code)
-            ret |= dnd_action_symbols[i].mac_code;
-    }
-    return ret;
-}
-static Qt::DropActions qt_mac_dnd_map_mac_actions(DragActions macActions)
-{
-#ifdef DEBUG_DRAG_EVENTS
-    qDebug("Converting DND ActionList: 0x%lx", macActions);
-#endif
-    Qt::DropActions ret = Qt::IgnoreAction;
-    for(int i = 0; dnd_action_symbols[i].qt_code; ++i) {
-#ifdef DEBUG_DRAG_EVENTS
-        qDebug(" %d) [%s] : %s", i, dnd_action_symbols[i].qt_desc,
-                (macActions & dnd_action_symbols[i].mac_code) ? "true" : "false");
-#endif
-        if(macActions & dnd_action_symbols[i].mac_code)
-            ret |= Qt::DropAction(dnd_action_symbols[i].qt_code);
-    }
-    return ret;
-}
-static Qt::DropAction qt_mac_dnd_map_mac_default_action(DragActions macActions)
-{
-    static Qt::DropAction preferred_actions[] = { Qt::CopyAction, Qt::LinkAction, //in order
-        Qt::MoveAction, Qt::IgnoreAction };
-    Qt::DropAction ret = Qt::IgnoreAction;
-    const Qt::DropActions qtActions = qt_mac_dnd_map_mac_actions(macActions);
-    for(int i = 0; preferred_actions[i] != Qt::IgnoreAction; ++i) {
-        if(qtActions & preferred_actions[i]) {
-            ret = preferred_actions[i];
-            break;
-        }
-    }
-#ifdef DEBUG_DRAG_EVENTS
-    for(int i = 0; dnd_action_symbols[i].qt_code; ++i) {
-        if(dnd_action_symbols[i].qt_code == ret) {
-            qDebug("Got default action: %s [0x%lx]", dnd_action_symbols[i].qt_desc, macActions);
-            break;
-        }
-    }
-#endif
-    return ret;
-}
-static void qt_mac_dnd_update_action(DragReference dragRef) {
-    SInt16 modifiers;
-    GetDragModifiers(dragRef, &modifiers, 0, 0);
-    qt_mac_send_modifiers_changed(modifiers, qApp);
-
-    Qt::DropAction qtAction = Qt::IgnoreAction;
-    {
-        DragActions macAllowed = kDragActionNothing;
-        GetDragDropAction(dragRef, &macAllowed);
-        Qt::DropActions qtAllowed = qt_mac_dnd_map_mac_actions(macAllowed);
-        qtAction = QDragManager::self()->defaultAction(qtAllowed, QApplication::keyboardModifiers());
-#if 1
-        if(!(qtAllowed & qtAction))
-            qtAction = qt_mac_dnd_map_mac_default_action(macAllowed);
-#endif
-    }
-    DragActions macAction = qt_mac_dnd_map_qt_actions(qtAction);
-
-    DragActions currentActions;
-    GetDragDropAction(dragRef, &currentActions);
-    if(currentActions != macAction) {
-        SetDragDropAction(dragRef, macAction);
-        QDragManager::self()->emitActionChanged(qtAction);
-    }
-}
-#endif // !QT_MAC_USE_COCOA
-
-/*****************************************************************************
-  DnD functions
- *****************************************************************************/
-bool QDropData::hasFormat_sys(const QString &mime) const
-{
-#ifndef QT_MAC_USE_COCOA
-    OSPasteboardRef board;
-    if(GetDragPasteboard(qt_mac_current_dragRef, &board) != noErr) {
-        qDebug("DnD: Cannot get PasteBoard!");
-        return false;
-    }
-    return QMacPasteboard(board, QMacPasteboardMime::MIME_DND).hasFormat(mime);
-#else
-    Q_UNUSED(mime);
-    return false;
-#endif // !QT_MAC_USE_COCOA
-}
-
-QVariant QDropData::retrieveData_sys(const QString &mime, QVariant::Type type) const
-{
-#ifndef QT_MAC_USE_COCOA
-    OSPasteboardRef board;
-    if(GetDragPasteboard(qt_mac_current_dragRef, &board) != noErr) {
-        qDebug("DnD: Cannot get PasteBoard!");
-        return QVariant();
-    }
-    return QMacPasteboard(board, QMacPasteboardMime::MIME_DND).retrieveData(mime, type);
-#else
-    Q_UNUSED(mime);
-    Q_UNUSED(type);
-    return QVariant();
-#endif // !QT_MAC_USE_COCOA
-}
-
-QStringList QDropData::formats_sys() const
-{
-#ifndef QT_MAC_USE_COCOA
-    OSPasteboardRef board;
-    if(GetDragPasteboard(qt_mac_current_dragRef, &board) != noErr) {
-        qDebug("DnD: Cannot get PasteBoard!");
-        return QStringList();
-    }
-    return QMacPasteboard(board, QMacPasteboardMime::MIME_DND).formats();
-#else
-    return QStringList();
-#endif
-}
-
-void QDragManager::timerEvent(QTimerEvent*)
-{
-}
-
-bool QDragManager::eventFilter(QObject *, QEvent *)
-{
-    return false;
-}
-
-void QDragManager::updateCursor()
-{
-}
-
-void QDragManager::cancel(bool)
-{
-    if(object) {
-        beingCancelled = true;
-        object = 0;
-    }
-#ifndef QT_NO_ACCESSIBILITY
-    QAccessible::updateAccessibility(this, 0, QAccessible::DragDropEnd);
-#endif
-}
-
-void QDragManager::move(const QPoint &)
-{
-}
-
-void QDragManager::drop()
-{
-}
-
-/**
-    If a drop action is already set on the carbon event
-    (from e.g. an earlier enter event), we insert the same
-    action on the new Qt event that has yet to be sendt.
-*/
-static inline bool qt_mac_set_existing_drop_action(const DragRef &dragRef, QDropEvent &event)
-{
-#ifndef QT_MAC_USE_COCOA
-    DragActions currentAction = kDragActionNothing;        
-    OSStatus err = GetDragDropAction(dragRef, &currentAction);
-    if (err == noErr && currentAction != kDragActionNothing) {
-        // This looks a bit evil, but we only ever set one action, so it's OK.
-        event.setDropAction(Qt::DropAction(int(qt_mac_dnd_map_mac_actions(currentAction))));
-        return true;
-    }
-#else
-    Q_UNUSED(dragRef);
-    Q_UNUSED(event);
-#endif
-    return false;
-}
-
-/**
-    If an answer rect has been set on the event (after being sent
-    to the global event processor), we store that rect so we can
-    check if the mouse is in the same area upon next drag move event. 
-*/
-void qt_mac_copy_answer_rect(const QDragMoveEvent &event)
-{
-    if (!event.answerRect().isEmpty()) {
-        qt_mac_dnd_answer_rec.rect = event.answerRect();
-        qt_mac_dnd_answer_rec.buttons = event.mouseButtons();
-        qt_mac_dnd_answer_rec.modifiers = event.keyboardModifiers();
-        qt_mac_dnd_answer_rec.lastAction = event.dropAction();
-    }    
-}
-
-bool qt_mac_mouse_inside_answer_rect(QPoint mouse)
-{
-    if (!qt_mac_dnd_answer_rec.rect.isEmpty()
-            && qt_mac_dnd_answer_rec.rect.contains(mouse)
-            && QApplication::mouseButtons() == qt_mac_dnd_answer_rec.buttons
-            && QApplication::keyboardModifiers() == qt_mac_dnd_answer_rec.modifiers)
-        return true;
-    else
-        return false;
-}
-
-bool QWidgetPrivate::qt_mac_dnd_event(uint kind, DragRef dragRef)
-{
-#ifndef QT_MAC_USE_COCOA
-    Q_Q(QWidget);
-    qt_mac_current_dragRef = dragRef;
-    if (kind != kEventControlDragLeave)
-        qt_mac_dnd_update_action(dragRef);
-
-    Point mouse;
-    GetDragMouse(dragRef, &mouse, 0L);
-    if(!mouse.h && !mouse.v)
-        GetGlobalMouse(&mouse);
-
-    if(QApplicationPrivate::modalState()) {
-        for(QWidget *modal = q; modal; modal = modal->parentWidget()) {
-            if(modal->isWindow()) {
-                if(modal != QApplication::activeModalWidget())
-                    return noErr;
-                break;
-            }
-        }
-    }
-
-    //lookup the possible actions
-    DragActions allowed = kDragActionNothing;
-    GetDragAllowableActions(dragRef, &allowed);
-    Qt::DropActions qtAllowed = qt_mac_dnd_map_mac_actions(allowed);
-
-    //lookup the source dragAccepted 
-    QMimeData *dropdata = QDragManager::self()->dropData;
-    if(QDragManager::self()->source())
-        dropdata = QDragManager::self()->dragPrivate()->data;
-
-    // 'interrestedInDrag' should end up being 'true' if a later drop
-    // will be accepted by the widget for the current mouse position 
-    bool interrestedInDrag = true;
-
-    //Dispatch events
-    if (kind == kEventControlDragWithin) {
-        if (qt_mac_mouse_inside_answer_rect(q->mapFromGlobal(QPoint(mouse.h, mouse.v))))
-            return qt_mac_dnd_answer_rec.lastAction == Qt::IgnoreAction;
-        else
-            qt_mac_dnd_answer_rec.clear();
-        
-        QDragMoveEvent qDMEvent(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata,
-                QApplication::mouseButtons(), QApplication::keyboardModifiers());
-                
-        // Accept the event by default if a
-        // drag action exists on the carbon event
-        if (qt_mac_set_existing_drop_action(dragRef, qDMEvent))
-            qDMEvent.accept();
-            
-        QApplication::sendEvent(q, &qDMEvent);
-        if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction)
-            interrestedInDrag = false;
-
-        qt_mac_copy_answer_rect(qDMEvent);
-        SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(qDMEvent.dropAction()));
-        
-    } else if (kind == kEventControlDragEnter) {
-        qt_mac_dnd_answer_rec.clear();
-        
-        QDragEnterEvent qDEEvent(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata,
-                QApplication::mouseButtons(), QApplication::keyboardModifiers());
-        qt_mac_set_existing_drop_action(dragRef, qDEEvent);                         
-        QApplication::sendEvent(q, &qDEEvent);
-        SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(qDEEvent.dropAction()));
-        
-        if (!qDEEvent.isAccepted())
-            // The widget is simply not interested in this
-            // drag. So tell carbon this by returning 'false'. We will then
-            // not receive any further move, drop or leave events for this widget.
-            return false;
-        else {
-            // Documentation states that a drag move event is sent immediately after
-            // a drag enter event. So we do that. This will honor widgets overriding
-            // 'dragMoveEvent' only, and not 'dragEnterEvent' 
-            QDragMoveEvent qDMEvent(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata,
-                    QApplication::mouseButtons(), QApplication::keyboardModifiers());
-            qDMEvent.accept(); // accept by default, since enter event was accepted.
-            qDMEvent.setDropAction(qDEEvent.dropAction());         
-            QApplication::sendEvent(q, &qDMEvent);
-            if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction)
-                interrestedInDrag = false;
-            
-            qt_mac_copy_answer_rect(qDMEvent);           
-            SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(qDMEvent.dropAction()));
-        }
-        
-    } else if(kind == kEventControlDragLeave) {
-        QDragLeaveEvent de;
-        QApplication::sendEvent(q, &de);
-    } else if(kind == kEventControlDragReceive) {
-        QDropEvent de(q->mapFromGlobal(QPoint(mouse.h, mouse.v)), qtAllowed, dropdata,
-                      QApplication::mouseButtons(), QApplication::keyboardModifiers());
-        if(QDragManager::self()->object)
-            QDragManager::self()->dragPrivate()->target = q;
-        QApplication::sendEvent(q, &de);
-        if(!de.isAccepted()) {
-            interrestedInDrag = false;
-            SetDragDropAction(dragRef, kDragActionNothing);
-        } else {
-            if(QDragManager::self()->object)
-                QDragManager::self()->dragPrivate()->executed_action = de.dropAction();
-            SetDragDropAction(dragRef, qt_mac_dnd_map_qt_actions(de.dropAction()));
-        }
-    }
-
-#ifdef DEBUG_DRAG_EVENTS
-    {
-        const char *desc = 0;
-        switch(kind) {
-        case kEventControlDragWithin: desc = "DragMove"; break;
-        case kEventControlDragEnter: desc = "DragEnter"; break;
-        case kEventControlDragLeave: desc = "DragLeave"; break;
-        case kEventControlDragReceive: desc = "DragDrop"; break;
-        }
-        if(desc) {
-            QPoint pos(q->mapFromGlobal(QPoint(mouse.h, mouse.v)));
-            qDebug("Sending <%s>(%d, %d) event to %p(%s::%s) [%d] (%p)",
-                   desc, pos.x(), pos.y(), q, q->metaObject()->className(),
-                   q->objectName().toLocal8Bit().constData(), ret, dragRef);
-        }
-    }
-#endif
-
-    //set the cursor
-    bool found_cursor = false;
-    if(kind == kEventControlDragWithin || kind == kEventControlDragEnter) {
-        ThemeCursor cursor = kThemeNotAllowedCursor;
-        found_cursor = true;
-        if (interrestedInDrag) {
-            DragActions action = kDragActionNothing;
-            GetDragDropAction(dragRef, &action);
-            switch(qt_mac_dnd_map_mac_default_action(action)) {
-            case Qt::IgnoreAction:
-                cursor = kThemeNotAllowedCursor;
-                break;
-            case Qt::MoveAction:
-                cursor = kThemeArrowCursor;
-                break;
-            case Qt::CopyAction:
-                cursor = kThemeCopyArrowCursor;
-                break;
-            case Qt::LinkAction:
-                cursor = kThemeAliasArrowCursor;
-                break;
-            default:
-                cursor = kThemeNotAllowedCursor;
-                break;
-            }
-        }
-        SetThemeCursor(cursor);
-    }
-    if(found_cursor) {
-        qt_mac_set_cursor(0); //just use our's
-    } else {
-        QCursor cursor(Qt::ArrowCursor);
-        if(qApp && qApp->overrideCursor()) {
-            cursor = *qApp->overrideCursor();
-        } else if(q) {
-            for(QWidget *p = q; p; p = p->parentWidget()) {
-                if(p->isEnabled() && p->testAttribute(Qt::WA_SetCursor)) {
-                    cursor = p->cursor();
-                    break;
-                }
-            }
-        }
-        qt_mac_set_cursor(&cursor);
-    }
-
-    //idle things
-    if(qGlobalPostedEventsCount()) {
-        QApplication::sendPostedEvents();
-        QApplication::flush();
-    }
-    
-    // If this was not a drop, tell carbon that we will be interresed in receiving more
-    // events for the current drag. We do that by returning true. 
-    if (kind == kEventControlDragReceive)
-        return interrestedInDrag;
-    else
-        return true;
-#else
-    Q_UNUSED(kind);
-    Q_UNUSED(dragRef);
-    return false;
-#endif // !QT_MAC_USE_COCOA
-}
-
-#ifndef QT_MAC_USE_COCOA
-Qt::DropAction QDragManager::drag(QDrag *o)
-{
-  
-    if(qt_mac_in_drag) {     //just make sure..
-        qWarning("Qt: Internal error: WH0A, unexpected condition reached");
-        return Qt::IgnoreAction;
-    }
-    if(object == o)
-        return Qt::IgnoreAction;
-    /* At the moment it seems clear that Mac OS X does not want to drag with a non-left button
-       so we just bail early to prevent it */
-    if(!(GetCurrentEventButtonState() & kEventMouseButtonPrimary))
-        return Qt::IgnoreAction;
-
-    if(object) {
-        dragPrivate()->source->removeEventFilter(this);
-        cancel();
-        beingCancelled = false;
-    }
-
-    object = o;
-    dragPrivate()->target = 0;
-
-#ifndef QT_NO_ACCESSIBILITY
-    QAccessible::updateAccessibility(this, 0, QAccessible::DragDropStart);
-#endif
-
-    //setup the data
-    QMacPasteboard dragBoard(QMacPasteboardMime::MIME_DND);
-    dragBoard.setMimeData(dragPrivate()->data);
-
-    //create the drag
-    OSErr result;
-    DragRef dragRef;
-    if((result = NewDragWithPasteboard(dragBoard.pasteBoard(), &dragRef)))
-        return Qt::IgnoreAction;
-    //setup the actions
-    DragActions possibleActions = qt_mac_dnd_map_qt_actions(dragPrivate()->possible_actions);
-    SetDragAllowableActions(dragRef, //local
-                            possibleActions,
-                            true);
-    SetDragAllowableActions(dragRef, //remote (same as local)
-                            possibleActions,
-                            false);
-
-
-    QPoint hotspot;
-    QPixmap pix = dragPrivate()->pixmap;
-    if(pix.isNull()) {
-        if(dragPrivate()->data->hasText() || dragPrivate()->data->hasUrls()) {
-            //get the string
-            QString s = dragPrivate()->data->hasText() ? dragPrivate()->data->text()
-                                                : dragPrivate()->data->urls().first().toString();
-            if(s.length() > 26)
-                s = s.left(23) + QChar(0x2026);
-            if(!s.isEmpty()) {
-                //draw it
-                QFont f(qApp->font());
-                f.setPointSize(12);
-                QFontMetrics fm(f);
-                const int width = fm.width(s);
-                const int height = fm.height();
-                if(width > 0 && height > 0) {
-                    QPixmap tmp(width, height);
-                    QPainter p(&tmp);
-                    p.fillRect(0, 0, tmp.width(), tmp.height(), Qt::color0);
-                    p.setPen(Qt::color1);
-                    p.setFont(f);
-                    p.drawText(0, fm.ascent(), s);
-                    p.end();
-                    //save it
-                    pix = tmp;
-                    hotspot = QPoint(tmp.width() / 2, tmp.height() / 2);
-                }
-            }
-        } else {
-            pix = QPixmap(default_pm);
-            hotspot = QPoint(default_pm_hotx, default_pm_hoty);
-        }
-    } else {
-        hotspot = dragPrivate()->hotspot;
-    }
-
-    //so we must fake an event
-    EventRecord fakeEvent;
-    GetGlobalMouse(&(fakeEvent.where));
-    fakeEvent.message = 0;
-    fakeEvent.what = mouseDown;
-    fakeEvent.when = EventTimeToTicks(GetCurrentEventTime());
-    fakeEvent.modifiers = GetCurrentKeyModifiers();
-    if(GetCurrentEventButtonState() & 2)
-        fakeEvent.modifiers |= controlKey;
-
-    //find the hotspot in relation to the pixmap
-    Point boundsPoint;
-    boundsPoint.h = fakeEvent.where.h - hotspot.x();
-    boundsPoint.v = fakeEvent.where.v - hotspot.y();
-    Rect boundsRect;
-    SetRect(&boundsRect, boundsPoint.h, boundsPoint.v, boundsPoint.h + pix.width(), boundsPoint.v + pix.height());
-
-    //set the drag image
-    QRegion dragRegion(boundsPoint.h, boundsPoint.v, pix.width(), pix.height()), pixRegion;
-    if(!pix.isNull()) {
-        HIPoint hipoint = { -hotspot.x(), -hotspot.y() };
-        CGImageRef img = (CGImageRef)pix.macCGHandle();
-        SetDragImageWithCGImage(dragRef, img, &hipoint, 0);
-        CGImageRelease(img);
-    }
-
-    SetDragItemBounds(dragRef, (ItemReference)1 , &boundsRect);
-    { //do the drag
-        qt_mac_in_drag = true;
-        qt_mac_dnd_update_action(dragRef);
-        result = TrackDrag(dragRef, &fakeEvent, QMacSmartQuickDrawRegion(dragRegion.toQDRgn()));
-        qt_mac_in_drag = false;
-    }
-    object = 0;
-    if(result == noErr) {
-        // Check if the receiver points us to
-        // a file location. If so, we need to do
-        // the file copy/move ourselves:
-        QCFType<CFURLRef> pasteLocation = 0;
-        PasteboardCopyPasteLocation(dragBoard.pasteBoard(), &pasteLocation);
-        if (pasteLocation){
-            Qt::DropAction action = o->d_func()->defaultDropAction;
-            if (action == Qt::IgnoreAction){
-                if (o->d_func()->possible_actions & Qt::MoveAction)
-                    action = Qt::MoveAction;
-                else if (o->d_func()->possible_actions & Qt::CopyAction)
-                    action = Qt::CopyAction;
-                
-            }
-            bool atleastOne = false;
-            QList<QUrl> urls = o->mimeData()->urls();
-            for (int i = 0; i < urls.size(); ++i){
-                QUrl fromUrl = urls.at(i);
-                QString filename = QFileInfo(fromUrl.path()).fileName();
-                QUrl toUrl(QCFString::toQString(CFURLGetString(pasteLocation)) + filename);
-                if (action == Qt::MoveAction){
-                    if (QFile::rename(fromUrl.path(), toUrl.path()))
-                        atleastOne = true;
-                } else if (action == Qt::CopyAction){
-                    if (QFile::copy(fromUrl.path(), toUrl.path()))
-                        atleastOne = true;
-                }
-            }
-            if (atleastOne){
-                DisposeDrag(dragRef);
-                o->setMimeData(0);
-                o->deleteLater();
-                return action;
-            }
-        }
-
-        DragActions ret = kDragActionNothing;
-        GetDragDropAction(dragRef, &ret);
-        DisposeDrag(dragRef); //cleanup
-        o->setMimeData(0);
-        o->deleteLater();
-        return qt_mac_dnd_map_mac_default_action(ret);
-    }
-    DisposeDrag(dragRef); //cleanup
-    return Qt::IgnoreAction;
-}
-#endif
-
-void QDragManager::updatePixmap()
-{
-}
-
-QCocoaDropData::QCocoaDropData(CFStringRef pasteboard)
-    : QInternalMimeData()
-{
-    NSString* pasteboardName = (NSString*)pasteboard;
-    [pasteboardName retain];
-    dropPasteboard = pasteboard;
-}
-
-QCocoaDropData::~QCocoaDropData()
-{
-    NSString* pasteboardName = (NSString*)dropPasteboard;
-    [pasteboardName release];
-}
-
-QStringList QCocoaDropData::formats_sys() const
-{
-    QStringList formats; 
-    OSPasteboardRef board;
-    if (PasteboardCreate(dropPasteboard, &board) != noErr) {
-        qDebug("DnD: Cannot get PasteBoard!");
-        return formats;
-    }
-    formats = QMacPasteboard(board, QMacPasteboardMime::MIME_DND).formats();
-    return formats;
-}
-
-QVariant QCocoaDropData::retrieveData_sys(const QString &mimeType, QVariant::Type type) const
-{
-    QVariant data;
-    OSPasteboardRef board;
-    if (PasteboardCreate(dropPasteboard, &board) != noErr) {
-        qDebug("DnD: Cannot get PasteBoard!");
-        return data;
-    }
-    data = QMacPasteboard(board, QMacPasteboardMime::MIME_DND).retrieveData(mimeType, type);
-    CFRelease(board);
-    return data;
-}
-
-bool QCocoaDropData::hasFormat_sys(const QString &mimeType) const
-{
-    bool has = false;
-    OSPasteboardRef board;
-    if (PasteboardCreate(dropPasteboard, &board) != noErr) {
-        qDebug("DnD: Cannot get PasteBoard!");
-        return has;
-    }
-    has = QMacPasteboard(board, QMacPasteboardMime::MIME_DND).hasFormat(mimeType);
-    CFRelease(board);
-    return has;
-}
-
-#include "moc_qdnd_p.h"
-
-#endif // QT_NO_DRAGANDDROP
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qdnd_win.cpp b/src/gui/kernel/qdnd_win.cpp
deleted file mode 100644 (file)
index 9e9d41c..0000000
+++ /dev/null
@@ -1,1045 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qapplication.h"
-
-#include "qapplication_p.h"
-#include "qevent.h"
-#include "qpainter.h"
-#include "qwidget.h"
-#include "qbuffer.h"
-#include "qdatastream.h"
-#include "qcursor.h"
-#include "qt_windows.h"
-#include <shlobj.h>
-#ifndef QT_NO_ACCESSIBILITY
-#include "qaccessible.h"
-#endif
-#include "qdnd_p.h"
-#include "qdebug.h"
-
-#if defined(Q_OS_WINCE)
-#include "qguifunctions_wince.h"
-#endif
-
-// support for xbuttons
-#ifndef MK_XBUTTON1
-#define MK_XBUTTON1         0x0020
-#define MK_XBUTTON2         0x0040
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#if !(defined(QT_NO_DRAGANDDROP) && defined(QT_NO_CLIPBOARD))
-
-//---------------------------------------------------------------------
-//                    QOleDataObject Constructor
-//---------------------------------------------------------------------
-
-QOleDataObject::QOleDataObject(QMimeData *mimeData)
-{
-    m_refs = 1;
-    data = mimeData;
-    CF_PERFORMEDDROPEFFECT = RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT);
-    performedEffect = DROPEFFECT_NONE;
-}
-
-QOleDataObject::~QOleDataObject()
-{
-}
-
-void QOleDataObject::releaseQt()
-{
-    data = 0;
-}
-
-const QMimeData *QOleDataObject::mimeData() const
-{
-    return data;
-}
-
-DWORD QOleDataObject::reportedPerformedEffect() const
-{
-    return performedEffect;
-}
-
-//---------------------------------------------------------------------
-//                    IUnknown Methods
-//---------------------------------------------------------------------
-
-STDMETHODIMP
-QOleDataObject::QueryInterface(REFIID iid, void FAR* FAR* ppv)
-{
-    if (iid == IID_IUnknown || iid == IID_IDataObject) {
-        *ppv = this;
-        AddRef();
-        return NOERROR;
-    }
-    *ppv = NULL;
-    return ResultFromScode(E_NOINTERFACE);
-}
-
-STDMETHODIMP_(ULONG)
-QOleDataObject::AddRef(void)
-{
-    return ++m_refs;
-}
-
-STDMETHODIMP_(ULONG)
-QOleDataObject::Release(void)
-{
-    if (--m_refs == 0) {
-        releaseQt();
-        delete this;
-        return 0;
-    }
-    return m_refs;
-}
-
-//---------------------------------------------------------------------
-//                    IDataObject Methods
-//
-// The following methods are NOT supported for data transfer using the
-// clipboard or drag-drop:
-//
-//      IDataObject::SetData    -- return E_NOTIMPL
-//      IDataObject::DAdvise    -- return OLE_E_ADVISENOTSUPPORTED
-//                 ::DUnadvise
-//                 ::EnumDAdvise
-//      IDataObject::GetCanonicalFormatEtc -- return E_NOTIMPL
-//                     (NOTE: must set pformatetcOut->ptd = NULL)
-//---------------------------------------------------------------------
-
-STDMETHODIMP
-QOleDataObject::GetData(LPFORMATETC pformatetc, LPSTGMEDIUM pmedium)
-{
-#ifdef QDND_DEBUG
-    qDebug("QOleDataObject::GetData(LPFORMATETC pformatetc, LPSTGMEDIUM pmedium)");
-#ifndef Q_OS_WINCE
-    wchar_t buf[256] = {0};
-    GetClipboardFormatName(pformatetc->cfFormat, buf, 255);
-    qDebug("CF = %d : %s", pformatetc->cfFormat, QString::fromWCharArray(buf));
-#endif
-#endif
-
-    if (!data)
-        return ResultFromScode(DATA_E_FORMATETC);
-
-    QWindowsMime *converter = QWindowsMime::converterFromMime(*pformatetc, data);
-
-    if (converter && converter->convertFromMime(*pformatetc, data, pmedium))
-        return ResultFromScode(S_OK);
-    else
-        return ResultFromScode(DATA_E_FORMATETC);
-}
-
-STDMETHODIMP
-QOleDataObject::GetDataHere(LPFORMATETC, LPSTGMEDIUM)
-{
-    return ResultFromScode(DATA_E_FORMATETC);
-}
-
-STDMETHODIMP
-QOleDataObject::QueryGetData(LPFORMATETC pformatetc)
-{
-#ifdef QDND_DEBUG
-    qDebug("QOleDataObject::QueryGetData(LPFORMATETC pformatetc)");
-#endif
-
-    if (!data)
-        return ResultFromScode(DATA_E_FORMATETC);
-
-    if (QWindowsMime::converterFromMime(*pformatetc, data))
-        return ResultFromScode(S_OK);
-    return ResultFromScode(S_FALSE);
-}
-
-STDMETHODIMP
-QOleDataObject::GetCanonicalFormatEtc(LPFORMATETC, LPFORMATETC pformatetcOut)
-{
-    pformatetcOut->ptd = NULL;
-    return ResultFromScode(E_NOTIMPL);
-}
-
-STDMETHODIMP
-QOleDataObject::SetData(LPFORMATETC pFormatetc, STGMEDIUM *pMedium, BOOL fRelease)
-{
-    if (pFormatetc->cfFormat == CF_PERFORMEDDROPEFFECT && pMedium->tymed == TYMED_HGLOBAL) {
-        DWORD * val = (DWORD*)GlobalLock(pMedium->hGlobal);
-        performedEffect = *val;
-        GlobalUnlock(pMedium->hGlobal);
-        if (fRelease)
-            ReleaseStgMedium(pMedium);
-        return ResultFromScode(S_OK);
-    }
-    return ResultFromScode(E_NOTIMPL);
-}
-
-
-STDMETHODIMP
-QOleDataObject::EnumFormatEtc(DWORD dwDirection, LPENUMFORMATETC FAR* ppenumFormatEtc)
-{
-#ifdef QDND_DEBUG
-    qDebug("QOleDataObject::EnumFormatEtc(DWORD dwDirection, LPENUMFORMATETC FAR* ppenumFormatEtc)");
-#endif
-
-    if (!data)
-        return ResultFromScode(DATA_E_FORMATETC);
-
-    SCODE sc = S_OK;
-
-    QVector<FORMATETC> fmtetcs;
-    if (dwDirection == DATADIR_GET) {
-        fmtetcs = QWindowsMime::allFormatsForMime(data);
-    } else {
-        FORMATETC formatetc;
-        formatetc.cfFormat = CF_PERFORMEDDROPEFFECT;
-        formatetc.dwAspect = DVASPECT_CONTENT;
-        formatetc.lindex = -1;
-        formatetc.ptd = NULL;
-        formatetc.tymed = TYMED_HGLOBAL;
-        fmtetcs.append(formatetc);
-    }
-
-    QOleEnumFmtEtc *enumFmtEtc = new QOleEnumFmtEtc(fmtetcs);
-    *ppenumFormatEtc = enumFmtEtc;
-    if (enumFmtEtc->isNull()) {
-        delete enumFmtEtc;
-        *ppenumFormatEtc = NULL;
-        sc = E_OUTOFMEMORY;
-    }
-
-    return ResultFromScode(sc);
-}
-
-STDMETHODIMP
-QOleDataObject::DAdvise(FORMATETC FAR*, DWORD,
-                       LPADVISESINK, DWORD FAR*)
-{
-    return ResultFromScode(OLE_E_ADVISENOTSUPPORTED);
-}
-
-
-STDMETHODIMP
-QOleDataObject::DUnadvise(DWORD)
-{
-    return ResultFromScode(OLE_E_ADVISENOTSUPPORTED);
-}
-
-STDMETHODIMP
-QOleDataObject::EnumDAdvise(LPENUMSTATDATA FAR*)
-{
-    return ResultFromScode(OLE_E_ADVISENOTSUPPORTED);
-}
-
-#endif // QT_NO_DRAGANDDROP && QT_NO_CLIPBOARD
-
-#ifndef QT_NO_DRAGANDDROP
-
-//#define QDND_DEBUG
-
-#ifdef QDND_DEBUG
-extern QString dragActionsToString(Qt::DropActions actions);
-#endif
-
-Qt::DropActions translateToQDragDropActions(DWORD pdwEffects)
-{
-    Qt::DropActions actions = Qt::IgnoreAction;
-    if (pdwEffects & DROPEFFECT_LINK)
-        actions |= Qt::LinkAction;
-    if (pdwEffects & DROPEFFECT_COPY)
-        actions |= Qt::CopyAction;
-    if (pdwEffects & DROPEFFECT_MOVE)
-        actions |= Qt::MoveAction;
-    return actions;
-}
-
-Qt::DropAction translateToQDragDropAction(DWORD pdwEffect)
-{
-    if (pdwEffect & DROPEFFECT_LINK)
-        return Qt::LinkAction;
-    if (pdwEffect & DROPEFFECT_COPY)
-        return Qt::CopyAction;
-    if (pdwEffect & DROPEFFECT_MOVE)
-        return Qt::MoveAction;
-    return Qt::IgnoreAction;
-}
-
-DWORD translateToWinDragEffects(Qt::DropActions action)
-{
-    DWORD effect = DROPEFFECT_NONE;
-    if (action & Qt::LinkAction)
-        effect |= DROPEFFECT_LINK;
-    if (action & Qt::CopyAction)
-        effect |= DROPEFFECT_COPY;
-    if (action & Qt::MoveAction)
-        effect |= DROPEFFECT_MOVE;
-    return effect;
-}
-
-Qt::KeyboardModifiers toQtKeyboardModifiers(DWORD keyState)
-{
-    Qt::KeyboardModifiers modifiers = Qt::NoModifier;
-
-    if (keyState & MK_SHIFT)
-        modifiers |= Qt::ShiftModifier;
-    if (keyState & MK_CONTROL)
-        modifiers |= Qt::ControlModifier;
-    if (keyState & MK_ALT)
-        modifiers |= Qt::AltModifier;
-
-    return modifiers;
-}
-
-Qt::MouseButtons toQtMouseButtons(DWORD keyState)
-{
-    Qt::MouseButtons buttons = Qt::NoButton;
-
-    if (keyState & MK_LBUTTON)
-        buttons |= Qt::LeftButton;
-    if (keyState & MK_RBUTTON)
-        buttons |= Qt::RightButton;
-    if (keyState & MK_MBUTTON)
-        buttons |= Qt::MidButton;
-
-    return buttons;
-}
-
-class QOleDropSource : public IDropSource
-{
-public:
-    QOleDropSource();
-    virtual ~QOleDropSource();
-
-    void createCursors();
-
-    // IUnknown methods
-    STDMETHOD(QueryInterface)(REFIID riid, void ** ppvObj);
-    STDMETHOD_(ULONG,AddRef)(void);
-    STDMETHOD_(ULONG,Release)(void);
-
-    // IDropSource methods
-    STDMETHOD(QueryContinueDrag)(BOOL fEscapePressed, DWORD grfKeyState);
-    STDMETHOD(GiveFeedback)(DWORD dwEffect);
-
-private:
-    Qt::MouseButtons currentButtons;
-    Qt::DropAction currentAction;
-    QMap <Qt::DropAction, QCursor> cursors;
-
-    ULONG m_refs;
-};
-
-
-QOleDropSource::QOleDropSource()
-{
-    currentButtons = Qt::NoButton;
-    m_refs = 1;
-    currentAction = Qt::IgnoreAction;
-}
-
-QOleDropSource::~QOleDropSource()
-{
-}
-
-void QOleDropSource::createCursors()
-{
-    QDragManager *manager = QDragManager::self();
-    if (manager && manager->object
-        && (!manager->object->pixmap().isNull()
-        || manager->hasCustomDragCursors())) {
-        QPixmap pm = manager->object->pixmap();
-        QList<Qt::DropAction> actions;
-        actions << Qt::MoveAction << Qt::CopyAction << Qt::LinkAction;
-        if (!manager->object->pixmap().isNull())
-            actions << Qt::IgnoreAction;
-        QPoint hotSpot = manager->object->hotSpot();
-        for (int cnum = 0; cnum < actions.size(); ++cnum) {
-            QPixmap cpm = manager->dragCursor(actions.at(cnum));
-            int w = cpm.width();
-            int h = cpm.height();
-
-            if (!pm.isNull()) {
-                int x1 = qMin(-hotSpot.x(), 0);
-                int x2 = qMax(pm.width() - hotSpot.x(), cpm.width());
-                int y1 = qMin(-hotSpot.y(), 0);
-                int y2 = qMax(pm.height() - hotSpot.y(), cpm.height());
-
-                w = x2 - x1 + 1;
-                h = y2 - y1 + 1;
-            }
-
-            QRect srcRect = pm.rect();
-            QPoint pmDest = QPoint(qMax(0, -hotSpot.x()), qMax(0, -hotSpot.y()));
-            QPoint newHotSpot = hotSpot;
-
-#if defined(Q_OS_WINCE)
-            // Limited cursor size
-            int reqw = GetSystemMetrics(SM_CXCURSOR);
-            int reqh = GetSystemMetrics(SM_CYCURSOR);
-
-            QPoint hotspotInPM = newHotSpot - pmDest;
-            if (reqw < w) {
-                // Not wide enough - move objectpm right
-                qreal r = qreal(newHotSpot.x()) / w;
-                newHotSpot = QPoint(int(r * reqw), newHotSpot.y());
-                if (newHotSpot.x() + cpm.width() > reqw)
-                    newHotSpot.setX(reqw - cpm.width());
-
-                srcRect = QRect(QPoint(hotspotInPM.x() - newHotSpot.x(), srcRect.top()), QSize(reqw, srcRect.height()));
-            }
-            if (reqh < h) {
-                qreal r = qreal(newHotSpot.y()) / h;
-                newHotSpot = QPoint(newHotSpot.x(), int(r * reqh));
-                if (newHotSpot.y() + cpm.height() > reqh)
-                    newHotSpot.setY(reqh - cpm.height());
-
-                srcRect = QRect(QPoint(srcRect.left(), hotspotInPM.y() - newHotSpot.y()), QSize(srcRect.width(), reqh));
-            }
-            // Always use system cursor size
-            w = reqw;
-            h = reqh;
-#endif
-
-            QPixmap newCursor(w, h);
-            if (!pm.isNull()) {
-                newCursor.fill(QColor(0, 0, 0, 0));
-                QPainter p(&newCursor);
-                p.drawPixmap(pmDest, pm, srcRect);
-                p.drawPixmap(qMax(0,newHotSpot.x()),qMax(0,newHotSpot.y()),cpm);
-            } else {
-                newCursor = cpm;
-            }
-
-#ifndef QT_NO_CURSOR
-            cursors[actions.at(cnum)] = QCursor(newCursor, pm.isNull() ? 0 : qMax(0,newHotSpot.x()),
-                                                pm.isNull() ? 0 : qMax(0,newHotSpot.y()));
-#endif
-        }
-    }
-}
-
-
-
-//---------------------------------------------------------------------
-//                    IUnknown Methods
-//---------------------------------------------------------------------
-
-
-STDMETHODIMP
-QOleDropSource::QueryInterface(REFIID iid, void FAR* FAR* ppv)
-{
-    if(iid == IID_IUnknown || iid == IID_IDropSource)
-    {
-      *ppv = this;
-      ++m_refs;
-      return NOERROR;
-    }
-    *ppv = NULL;
-    return ResultFromScode(E_NOINTERFACE);
-}
-
-
-STDMETHODIMP_(ULONG)
-QOleDropSource::AddRef(void)
-{
-    return ++m_refs;
-}
-
-
-STDMETHODIMP_(ULONG)
-QOleDropSource::Release(void)
-{
-    if(--m_refs == 0)
-    {
-      delete this;
-      return 0;
-    }
-    return m_refs;
-}
-
-static inline Qt::MouseButtons keystate_to_mousebutton(DWORD grfKeyState)
-{
-    Qt::MouseButtons result;
-    if (grfKeyState & MK_LBUTTON)
-        result |= Qt::LeftButton;
-    if (grfKeyState & MK_MBUTTON)
-        result |= Qt::MidButton;
-    if (grfKeyState & MK_RBUTTON)
-        result |= Qt::RightButton;
-    if (grfKeyState & MK_XBUTTON1)
-        result |= Qt::XButton1;
-    if (grfKeyState & MK_XBUTTON2)
-        result |= Qt::XButton2;
-    return result;
-}
-
-//---------------------------------------------------------------------
-//                    IDropSource Methods
-//---------------------------------------------------------------------
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropSource::QueryContinueDrag(BOOL fEscapePressed, DWORD grfKeyState)
-{
-#ifdef QDND_DEBUG
-    qDebug("QOleDropSource::QueryContinueDrag(fEscapePressed %d, grfKeyState %d)", fEscapePressed, grfKeyState);
-#endif
-
-    if (fEscapePressed) {
-        return ResultFromScode(DRAGDROP_S_CANCEL);
-    } else if ((GetAsyncKeyState(VK_LBUTTON) == 0)
-        && (GetAsyncKeyState(VK_MBUTTON) == 0)
-        && (GetAsyncKeyState(VK_RBUTTON) == 0))    {
-        // grfKeyState is broken on CE & some Windows XP versions,
-        // therefore we need to check the state manually
-        return ResultFromScode(DRAGDROP_S_DROP);
-    } else {
-#if !defined(Q_OS_WINCE)
-        if (currentButtons == Qt::NoButton) {
-            currentButtons = keystate_to_mousebutton(grfKeyState);
-        } else {
-            Qt::MouseButtons buttons = keystate_to_mousebutton(grfKeyState);
-            if (!(currentButtons & buttons))
-                return ResultFromScode(DRAGDROP_S_DROP);
-        }
-#else
-    Q_UNUSED(grfKeyState);
-#endif
-        QApplication::processEvents();
-        return NOERROR;
-    }
-}
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropSource::GiveFeedback(DWORD dwEffect)
-{
-    Qt::DropAction action = translateToQDragDropAction(dwEffect);
-
-#ifdef QDND_DEBUG
-    qDebug("QOleDropSource::GiveFeedback(DWORD dwEffect)");
-    qDebug("dwEffect = %s", dragActionsToString(action).toLatin1().data());
-#endif
-
-    if (currentAction != action) {
-        currentAction = action;
-        QDragManager::self()->emitActionChanged(currentAction);
-    }
-
-    if (cursors.contains(currentAction)) {
-#ifndef QT_NO_CURSOR
-        SetCursor(cursors[currentAction].handle());
-#endif
-        return ResultFromScode(S_OK);
-    }
-
-    return ResultFromScode(DRAGDROP_S_USEDEFAULTCURSORS);
-}
-
-//---------------------------------------------------------------------
-//                    QOleDropTarget
-//---------------------------------------------------------------------
-
-QOleDropTarget::QOleDropTarget(QWidget* w)
-:   widget(w)
-{
-   m_refs = 1;
-}
-
-void QOleDropTarget::releaseQt()
-{
-    widget = 0;
-}
-
-//---------------------------------------------------------------------
-//                    IUnknown Methods
-//---------------------------------------------------------------------
-
-
-STDMETHODIMP
-QOleDropTarget::QueryInterface(REFIID iid, void FAR* FAR* ppv)
-{
-    if(iid == IID_IUnknown || iid == IID_IDropTarget)
-    {
-      *ppv = this;
-      AddRef();
-      return NOERROR;
-    }
-    *ppv = NULL;
-    return ResultFromScode(E_NOINTERFACE);
-}
-
-
-STDMETHODIMP_(ULONG)
-QOleDropTarget::AddRef(void)
-{
-    return ++m_refs;
-}
-
-
-STDMETHODIMP_(ULONG)
-QOleDropTarget::Release(void)
-{
-    if(--m_refs == 0)
-    {
-      delete this;
-      return 0;
-    }
-    return m_refs;
-}
-
-//---------------------------------------------------------------------
-//                    IDropTarget Methods
-//---------------------------------------------------------------------
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropTarget::DragEnter(LPDATAOBJECT pDataObj, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect)
-{
-#ifdef QDND_DEBUG
-    qDebug("QOleDropTarget::DragEnter(grfKeyState %d, pt (%d,%d), pdwEffect %lu)",
-           grfKeyState, pt.x, pt.y, *pdwEffect);
-#endif
-
-    if (!QApplicationPrivate::tryModalHelper(widget)) {
-        *pdwEffect = DROPEFFECT_NONE;
-        return NOERROR;
-    }
-
-    QDragManager *manager = QDragManager::self();
-    manager->dropData->currentDataObject = pDataObj;
-    manager->dropData->currentDataObject->AddRef();
-    sendDragEnterEvent(widget, grfKeyState, pt, pdwEffect);
-    *pdwEffect = chosenEffect;
-
-    return NOERROR;
-}
-
-void QOleDropTarget::sendDragEnterEvent(QWidget *dragEnterWidget, DWORD grfKeyState,
-                                        POINTL pt, LPDWORD pdwEffect)
-{
-    Q_ASSERT(dragEnterWidget);
-    lastPoint = dragEnterWidget->mapFromGlobal(QPoint(pt.x,pt.y));
-    lastKeyState = grfKeyState;
-
-    chosenEffect = DROPEFFECT_NONE;
-    currentWidget = dragEnterWidget;
-
-    QDragManager *manager = QDragManager::self();
-    QMimeData * md = manager->source() ? manager->dragPrivate()->data : manager->dropData;
-    QDragEnterEvent enterEvent(lastPoint, translateToQDragDropActions(*pdwEffect), md,
-                      toQtMouseButtons(grfKeyState), toQtKeyboardModifiers(grfKeyState));
-    QApplication::sendEvent(dragEnterWidget, &enterEvent);
-    answerRect = enterEvent.answerRect();
-
-    if (enterEvent.isAccepted()) {
-        chosenEffect = translateToWinDragEffects(enterEvent.dropAction());
-    }
-
-    // Documentation states that a drag move event is sendt immidiatly after
-    // a drag enter event. This will honor widgets overriding dragMoveEvent only:
-    if (enterEvent.isAccepted()) {
-        QDragMoveEvent moveEvent(lastPoint, translateToQDragDropActions(*pdwEffect), md,
-                                 toQtMouseButtons(grfKeyState), toQtKeyboardModifiers(grfKeyState));
-        answerRect = enterEvent.answerRect();
-        moveEvent.setDropAction(enterEvent.dropAction());
-        moveEvent.accept(); // accept by default, since enter event was accepted.
-
-        QApplication::sendEvent(dragEnterWidget, &moveEvent);
-        if (moveEvent.isAccepted()) {
-            answerRect = moveEvent.answerRect();
-            chosenEffect = translateToWinDragEffects(moveEvent.dropAction());
-        } else {
-            chosenEffect = DROPEFFECT_NONE;
-        }
-    }
-
-}
-
-static inline bool acceptsDrop(const QWidget *w)
-{
-    return w->testAttribute(Qt::WA_DropSiteRegistered) && w->acceptDrops();
-}
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropTarget::DragOver(DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect)
-{
-#ifdef QDND_DEBUG
-    qDebug("QOleDropTarget::DragOver(grfKeyState %d, pt (%d,%d), pdwEffect %lu)",
-           grfKeyState, pt.x, pt.y, *pdwEffect);
-#endif
-
-    QWidget *dragOverWidget = widget->childAt(widget->mapFromGlobal(QPoint(pt.x, pt.y)));
-    if (!dragOverWidget)
-        dragOverWidget = widget;
-
-
-    if (!QApplicationPrivate::tryModalHelper(dragOverWidget)) {
-        *pdwEffect = DROPEFFECT_NONE;
-        return NOERROR;
-    }
-
-    // Try to find a drop-enabled target in the hierarchy. Go beyond 'widget' in case
-    // it is a native child window which has its own drop site registered (QTBUG-27265).
-    while (dragOverWidget && !dragOverWidget->isWindow() && !acceptsDrop(dragOverWidget))
-        dragOverWidget = dragOverWidget->parentWidget();
-
-    if (!dragOverWidget || !acceptsDrop(dragOverWidget)) {
-        *pdwEffect = DROPEFFECT_NONE;
-        return NOERROR;
-    }
-
-    QPoint tmpPoint = dragOverWidget->mapFromGlobal(QPoint(pt.x, pt.y));
-    // see if we should compress this event
-    if ((tmpPoint == lastPoint || answerRect.contains(tmpPoint)) && lastKeyState == grfKeyState) {
-        *pdwEffect = chosenEffect;
-        return NOERROR;
-    }
-
-    if (!dragOverWidget->internalWinId() && dragOverWidget != currentWidget) {
-        QPointer<QWidget> dragOverWidgetGuard(dragOverWidget);
-        // Send drag leave event to the previous drag widget.
-        QDragLeaveEvent dragLeave;
-        if (currentWidget)
-            QApplication::sendEvent(currentWidget, &dragLeave);
-        if (!dragOverWidgetGuard) {
-            dragOverWidget = widget->childAt(widget->mapFromGlobal(QPoint(pt.x, pt.y)));
-            if (!dragOverWidget)
-                dragOverWidget = widget;
-        }
-        // Send drag enter event to the current drag widget.
-        sendDragEnterEvent(dragOverWidget, grfKeyState, pt, pdwEffect);
-    }
-
-    QDragManager *manager = QDragManager::self();
-    QMimeData *md = manager->source() ? manager->dragPrivate()->data : manager->dropData;
-
-    QDragMoveEvent oldEvent(lastPoint, translateToQDragDropActions(*pdwEffect), md,
-                     toQtMouseButtons(lastKeyState), toQtKeyboardModifiers(lastKeyState));
-
-
-    lastPoint = tmpPoint;
-    lastKeyState = grfKeyState;
-
-    QDragMoveEvent e(lastPoint, translateToQDragDropActions(*pdwEffect), md,
-                     toQtMouseButtons(grfKeyState), toQtKeyboardModifiers(grfKeyState));
-    if (chosenEffect != DROPEFFECT_NONE) {
-        if (oldEvent.dropAction() == e.dropAction() &&
-            oldEvent.keyboardModifiers() == e.keyboardModifiers())
-            e.setDropAction(translateToQDragDropAction(chosenEffect));
-        e.accept();
-    }
-    QApplication::sendEvent(dragOverWidget, &e);
-
-    answerRect = e.answerRect();
-    if (e.isAccepted())
-        chosenEffect = translateToWinDragEffects(e.dropAction());
-    else
-        chosenEffect = DROPEFFECT_NONE;
-    *pdwEffect = chosenEffect;
-
-    return NOERROR;
-}
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropTarget::DragLeave()
-{
-#ifdef QDND_DEBUG
-    qDebug("QOleDropTarget::DragLeave()");
-#endif
-
-    if (!QApplicationPrivate::tryModalHelper(widget)) {
-        return NOERROR;
-    }
-
-    currentWidget = 0;
-    QDragLeaveEvent e;
-    QApplication::sendEvent(widget, &e);
-
-    QDragManager *manager = QDragManager::self();
-
-    if (manager->dropData->currentDataObject) { // Sanity
-        manager->dropData->currentDataObject->Release();
-        manager->dropData->currentDataObject = 0;
-    }
-
-    return NOERROR;
-}
-
-#define KEY_STATE_BUTTON_MASK (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)
-
-QT_ENSURE_STACK_ALIGNED_FOR_SSE STDMETHODIMP
-QOleDropTarget::Drop(LPDATAOBJECT /*pDataObj*/, DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect)
-{
-#ifdef QDND_DEBUG
-    qDebug("QOleDropTarget::Drop(LPDATAOBJECT /*pDataObj*/, grfKeyState %d, POINTL pt, LPDWORD pdwEffect)", grfKeyState);
-#endif
-
-    QWidget *dropWidget = widget->childAt(widget->mapFromGlobal(QPoint(pt.x, pt.y)));
-    if (!dropWidget)
-        dropWidget = widget;
-
-    if (!QApplicationPrivate::tryModalHelper(dropWidget)
-            || !dropWidget->testAttribute(Qt::WA_DropSiteRegistered)) {
-        *pdwEffect = DROPEFFECT_NONE;
-        return NOERROR;
-    }
-
-    lastPoint = dropWidget->mapFromGlobal(QPoint(pt.x,pt.y));
-    // grfKeyState does not all ways contain button state in the drop so if
-    // it doesn't then use the last known button state;
-    if ((grfKeyState & KEY_STATE_BUTTON_MASK) == 0)
-        grfKeyState |= lastKeyState & KEY_STATE_BUTTON_MASK;
-    lastKeyState = grfKeyState;
-
-    QDragManager *manager = QDragManager::self();
-    QMimeData *md = manager->source() ? manager->dragPrivate()->data : manager->dropData;
-    QDropEvent e(lastPoint, translateToQDragDropActions(*pdwEffect), md,
-                 toQtMouseButtons(grfKeyState), toQtKeyboardModifiers(grfKeyState));
-    if (chosenEffect != DROPEFFECT_NONE) {
-        e.setDropAction(translateToQDragDropAction(chosenEffect));
-    }
-    QApplication::sendEvent(dropWidget, &e);
-
-    if (chosenEffect != DROPEFFECT_NONE) {
-        e.accept();
-    }
-
-
-    if (e.isAccepted()) {
-        if (e.dropAction() == Qt::MoveAction || e.dropAction() == Qt::TargetMoveAction) {
-            if (e.dropAction() == Qt::MoveAction)
-                chosenEffect = DROPEFFECT_MOVE;
-            else
-                chosenEffect = DROPEFFECT_COPY;
-            HGLOBAL hData = GlobalAlloc(0, sizeof(DWORD));
-            if (hData) {
-                DWORD *moveEffect = (DWORD *)GlobalLock(hData);;
-                *moveEffect = DROPEFFECT_MOVE;
-                GlobalUnlock(hData);
-                STGMEDIUM medium;
-                memset(&medium, 0, sizeof(STGMEDIUM));
-                medium.tymed = TYMED_HGLOBAL;
-                medium.hGlobal = hData;
-                FORMATETC format;
-                format.cfFormat = RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT);
-                format.tymed = TYMED_HGLOBAL;
-                format.ptd = 0;
-                format.dwAspect = 1;
-                format.lindex = -1;
-                manager->dropData->currentDataObject->SetData(&format, &medium, true);
-            }
-        } else {
-            chosenEffect = translateToWinDragEffects(e.dropAction());
-        }
-    } else {
-        chosenEffect = DROPEFFECT_NONE;
-    }
-    *pdwEffect = chosenEffect;
-
-
-    if (manager->dropData->currentDataObject) {
-        manager->dropData->currentDataObject->Release();
-        manager->dropData->currentDataObject = 0;
-    }
-
-    return NOERROR;
-
-        // We won't get any mouserelease-event, so manually adjust qApp state:
-///### test this        QApplication::winMouseButtonUp();
-}
-
-//---------------------------------------------------------------------
-//                    QDropData
-//---------------------------------------------------------------------
-
-bool QDropData::hasFormat_sys(const QString &mimeType) const
-{
-    if (!currentDataObject) // Sanity
-        return false;
-
-    return QWindowsMime::converterToMime(mimeType, currentDataObject) != 0;
-}
-
-QStringList QDropData::formats_sys() const
-{
-    QStringList fmts;
-    if (!currentDataObject) // Sanity
-        return fmts;
-
-    fmts = QWindowsMime::allMimesForFormats(currentDataObject);
-
-    return fmts;
-}
-
-QVariant QDropData::retrieveData_sys(const QString &mimeType, QVariant::Type type) const
-{
-    QVariant result;
-
-    if (!currentDataObject) // Sanity
-        return result;
-
-    QWindowsMime *converter = QWindowsMime::converterToMime(mimeType, currentDataObject);
-
-    if (converter)
-        result = converter->convertToMime(mimeType, currentDataObject, type);
-
-    return result;
-}
-
-Qt::DropAction QDragManager::drag(QDrag *o)
-
-{
-#ifdef QDND_DEBUG
-    qDebug("QDragManager::drag(QDrag *drag)");
-#endif
-
-    if (object == o || !o || !o->d_func()->source)
-        return Qt::IgnoreAction;
-
-    if (object) {
-        cancel();
-        qApp->removeEventFilter(this);
-        beingCancelled = false;
-    }
-
-    object = o;
-
-#ifdef QDND_DEBUG
-    qDebug("actions = %s", dragActionsToString(dragPrivate()->possible_actions).toLatin1().data());
-#endif
-
-    dragPrivate()->target = 0;
-
-#ifndef QT_NO_ACCESSIBILITY
-    QAccessible::updateAccessibility(this, 0, QAccessible::DragDropStart);
-#endif
-
-    DWORD resultEffect;
-    QOleDropSource *src = new QOleDropSource();
-    src->createCursors();
-    QOleDataObject *obj = new QOleDataObject(o->mimeData());
-    DWORD allowedEffects = translateToWinDragEffects(dragPrivate()->possible_actions);
-
-#if !defined(Q_OS_WINCE) || defined(GWES_ICONCURS)
-    HRESULT r = DoDragDrop(obj, src, allowedEffects, &resultEffect);
-#else
-    HRESULT r = DRAGDROP_S_CANCEL;
-    resultEffect = DROPEFFECT_MOVE;
-#endif
-
-    Qt::DropAction ret = Qt::IgnoreAction;
-    if (r == DRAGDROP_S_DROP) {
-        if (obj->reportedPerformedEffect() == DROPEFFECT_MOVE && resultEffect != DROPEFFECT_MOVE) {
-            ret = Qt::TargetMoveAction;
-            resultEffect = DROPEFFECT_MOVE;
-        } else {
-            ret = translateToQDragDropAction(resultEffect);
-        }
-        // Force it to be a copy if an unsupported operation occurred.
-        // This indicates a bug in the drop target.
-        if (resultEffect != DROPEFFECT_NONE && !(resultEffect & allowedEffects))
-            ret = Qt::CopyAction;
-    } else {
-        dragPrivate()->target = 0;
-    }
-
-    // clean up
-    obj->releaseQt();
-    obj->Release();        // Will delete obj if refcount becomes 0
-    src->Release();        // Will delete src if refcount becomes 0
-    object = 0;
-    o->setMimeData(0);
-    o->deleteLater();
-
-#ifndef QT_NO_ACCESSIBILITY
-    QAccessible::updateAccessibility(this, 0, QAccessible::DragDropEnd);
-#endif
-
-    return ret;
-}
-
-void QDragManager::cancel(bool /* deleteSource */)
-{
-    if (object) {
-        beingCancelled = true;
-        object = 0;
-    }
-
-#ifndef QT_NO_CURSOR
-    // insert cancel code here ######## todo
-
-    if (restoreCursor) {
-        QApplication::restoreOverrideCursor();
-        restoreCursor = false;
-    }
-#endif
-#ifndef QT_NO_ACCESSIBILITY
-    QAccessible::updateAccessibility(this, 0, QAccessible::DragDropEnd);
-#endif
-}
-
-void QDragManager::updatePixmap()
-{
-    // not used in windows implementation
-}
-
-bool QDragManager::eventFilter(QObject *, QEvent *)
-{
-    // not used in windows implementation
-    return false;
-}
-
-void QDragManager::timerEvent(QTimerEvent*)
-{
-    // not used in windows implementation
-}
-
-void QDragManager::move(const QPoint &)
-{
-    // not used in windows implementation
-}
-
-void QDragManager::drop()
-{
-    // not used in windows implementation
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DRAGANDDROP
diff --git a/src/gui/kernel/qeventdispatcher_mac.mm b/src/gui/kernel/qeventdispatcher_mac.mm
deleted file mode 100644 (file)
index 1e7b551..0000000
+++ /dev/null
@@ -1,1204 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#include "qplatformdefs.h"
-#include "qt_mac_p.h"
-#include "qeventdispatcher_mac_p.h"
-#include "qapplication.h"
-#include "qevent.h"
-#include "qdialog.h"
-#include "qhash.h"
-#include "qsocketnotifier.h"
-#include "qwidget_p.h"
-#include "qthread_p.h"
-#include "qapplication_p.h"
-
-#include <qcocoaapplication_mac_p.h>
-#include "qt_cocoa_helpers_mac_p.h"
-
-#ifndef QT_NO_THREAD
-#  include "qmutex.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-/*****************************************************************************
-  Externals
- *****************************************************************************/
-extern void qt_event_request_timer(MacTimerInfo *); //qapplication_mac.cpp
-extern MacTimerInfo *qt_event_get_timer(EventRef); //qapplication_mac.cpp
-extern void qt_event_request_select(QEventDispatcherMac *); //qapplication_mac.cpp
-extern void qt_event_request_updates(); //qapplication_mac.cpp
-extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
-extern bool qt_is_gui_used; //qapplication.cpp
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
-extern bool qt_mac_is_macsheet(const QWidget *); //qwidget_mac.cpp
-
-static inline CFRunLoopRef mainRunLoop()
-{
-#ifndef QT_MAC_USE_COCOA
-    return reinterpret_cast<CFRunLoopRef>(const_cast<void *>(GetCFRunLoopFromEventLoop(GetMainEventLoop())));
-#else
-    return CFRunLoopGetMain();
-#endif
-}
-
-/*****************************************************************************
-  Timers stuff
- *****************************************************************************/
-
-/* timer call back */
-void QEventDispatcherMacPrivate::activateTimer(CFRunLoopTimerRef, void *info)
-{
-    int timerID =
-#ifdef Q_OS_MAC64
-    qint64(info);
-#else
-    int(info);
-#endif
-
-    MacTimerInfo *tmr;
-    tmr = macTimerHash.value(timerID);
-    if (tmr == 0 || tmr->pending == true)
-        return; // Can't send another timer event if it's pending.
-
-
-    if (blockSendPostedEvents) {
-        QCoreApplication::postEvent(tmr->obj, new QTimerEvent(tmr->id));
-    } else {
-        tmr->pending = true;
-        QTimerEvent e(tmr->id);
-        qt_sendSpontaneousEvent(tmr->obj, &e);
-        // Get the value again in case the timer gets unregistered during the sendEvent.
-        tmr = macTimerHash.value(timerID);
-        if (tmr != 0)
-            tmr->pending = false;
-    }
-
-}
-
-void QEventDispatcherMac::registerTimer(int timerId, int interval, QObject *obj)
-{
-#ifndef QT_NO_DEBUG
-    if (timerId < 1 || interval < 0 || !obj) {
-        qWarning("QEventDispatcherMac::registerTimer: invalid arguments");
-        return;
-    } else if (obj->thread() != thread() || thread() != QThread::currentThread()) {
-        qWarning("QObject::startTimer: timers cannot be started from another thread");
-        return;
-    }
-#endif
-
-    MacTimerInfo *t = new MacTimerInfo();
-    t->id = timerId;
-    t->interval = interval;
-    t->obj = obj;
-    t->runLoopTimer = 0;
-    t->pending = false;
-
-    CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent();
-    CFTimeInterval cfinterval = qMax(CFTimeInterval(interval) / 1000, 0.0000001);
-    fireDate += cfinterval;
-    QEventDispatcherMacPrivate::macTimerHash.insert(timerId, t);
-    CFRunLoopTimerContext info = { 0, (void *)timerId, 0, 0, 0 };
-    t->runLoopTimer = CFRunLoopTimerCreate(0, fireDate, cfinterval, 0, 0,
-                                           QEventDispatcherMacPrivate::activateTimer, &info);
-    if (t->runLoopTimer == 0) {
-        qFatal("QEventDispatcherMac::registerTimer: Cannot create timer");
-    }
-    CFRunLoopAddTimer(mainRunLoop(), t->runLoopTimer, kCFRunLoopCommonModes);
-}
-
-bool QEventDispatcherMac::unregisterTimer(int identifier)
-{
-#ifndef QT_NO_DEBUG
-    if (identifier < 1) {
-        qWarning("QEventDispatcherMac::unregisterTimer: invalid argument");
-        return false;
-    } else if (thread() != QThread::currentThread()) {
-        qWarning("QObject::killTimer: timers cannot be stopped from another thread");
-        return false;
-    }
-#endif
-    if (identifier <= 0)
-        return false;                                // not init'd or invalid timer
-
-    MacTimerInfo *timerInfo = QEventDispatcherMacPrivate::macTimerHash.take(identifier);
-    if (timerInfo == 0)
-        return false;
-
-    if (!QObjectPrivate::get(timerInfo->obj)->inThreadChangeEvent)
-        QAbstractEventDispatcherPrivate::releaseTimerId(identifier);
-    CFRunLoopTimerInvalidate(timerInfo->runLoopTimer);
-    CFRelease(timerInfo->runLoopTimer);
-    delete timerInfo;
-
-    return true;
-}
-
-bool QEventDispatcherMac::unregisterTimers(QObject *obj)
-{
-#ifndef QT_NO_DEBUG
-    if (!obj) {
-        qWarning("QEventDispatcherMac::unregisterTimers: invalid argument");
-        return false;
-    } else if (obj->thread() != thread() || thread() != QThread::currentThread()) {
-        qWarning("QObject::killTimers: timers cannot be stopped from another thread");
-        return false;
-    }
-#endif
-
-    MacTimerHash::iterator it = QEventDispatcherMacPrivate::macTimerHash.begin();
-    while (it != QEventDispatcherMacPrivate::macTimerHash.end()) {
-        MacTimerInfo *timerInfo = it.value();
-        if (timerInfo->obj != obj) {
-            ++it;
-        } else {
-            if (!QObjectPrivate::get(timerInfo->obj)->inThreadChangeEvent)
-                QAbstractEventDispatcherPrivate::releaseTimerId(timerInfo->id);
-            CFRunLoopTimerInvalidate(timerInfo->runLoopTimer);
-            CFRelease(timerInfo->runLoopTimer);
-            delete timerInfo;
-            it = QEventDispatcherMacPrivate::macTimerHash.erase(it);
-        }
-    }
-    return true;
-}
-
-QList<QEventDispatcherMac::TimerInfo>
-QEventDispatcherMac::registeredTimers(QObject *object) const
-{
-    if (!object) {
-        qWarning("QEventDispatcherMac:registeredTimers: invalid argument");
-        return QList<TimerInfo>();
-    }
-
-    QList<TimerInfo> list;
-
-    MacTimerHash::const_iterator it = QEventDispatcherMacPrivate::macTimerHash.constBegin();
-    while (it != QEventDispatcherMacPrivate::macTimerHash.constEnd()) {
-        MacTimerInfo *t = it.value();
-        if (t->obj == object)
-            list << TimerInfo(t->id, t->interval);
-        ++it;
-    }
-    return list;
-}
-
-/**************************************************************************
-    Socket Notifiers
- *************************************************************************/
-void qt_mac_socket_callback(CFSocketRef s, CFSocketCallBackType callbackType, CFDataRef,
-                            const void *,  void *info) {
-    QEventDispatcherMacPrivate *const eventDispatcher
-                                    = static_cast<QEventDispatcherMacPrivate *>(info);
-    int nativeSocket = CFSocketGetNative(s);
-    MacSocketInfo *socketInfo = eventDispatcher->macSockets.value(nativeSocket);
-    QEvent notifierEvent(QEvent::SockAct);
-
-    // There is a race condition that happen where we disable the notifier and
-    // the kernel still has a notification to pass on. We then get this
-    // notification after we've successfully disabled the CFSocket, but our Qt
-    // notifier is now gone. The upshot is we have to check the notifier
-    // everytime.
-    if (callbackType == kCFSocketReadCallBack) {
-        if (socketInfo->readNotifier)
-            QApplication::sendEvent(socketInfo->readNotifier, &notifierEvent);
-    } else if (callbackType == kCFSocketWriteCallBack) {
-        if (socketInfo->writeNotifier)
-            QApplication::sendEvent(socketInfo->writeNotifier, &notifierEvent);
-    }
-}
-
-/*
-    Adds a loop source for the given socket to the current run loop.
-*/
-CFRunLoopSourceRef qt_mac_add_socket_to_runloop(const CFSocketRef socket)
-{
-    CFRunLoopSourceRef loopSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
-    if (!loopSource)
-        return 0;
-
-    CFRunLoopAddSource(mainRunLoop(), loopSource, kCFRunLoopCommonModes);
-    return loopSource;
-}
-
-/*
-    Removes the loop source for the given socket from the current run loop.
-*/
-void qt_mac_remove_socket_from_runloop(const CFSocketRef socket, CFRunLoopSourceRef runloop)
-{
-    Q_ASSERT(runloop);
-    CFRunLoopRemoveSource(mainRunLoop(), runloop, kCFRunLoopCommonModes);
-    CFSocketDisableCallBacks(socket, kCFSocketReadCallBack);
-    CFSocketDisableCallBacks(socket, kCFSocketWriteCallBack);
-    CFRunLoopSourceInvalidate(runloop);
-}
-
-/*
-    Register a QSocketNotifier with the mac event system by creating a CFSocket with
-    with a read/write callback.
-
-    Qt has separate socket notifiers for reading and writing, but on the mac there is
-    a limitation of one CFSocket object for each native socket.
-*/
-void QEventDispatcherMac::registerSocketNotifier(QSocketNotifier *notifier)
-{
-    Q_ASSERT(notifier);
-    int nativeSocket = notifier->socket();
-    int type = notifier->type();
-#ifndef QT_NO_DEBUG
-    if (nativeSocket < 0 || nativeSocket > FD_SETSIZE) {
-        qWarning("QSocketNotifier: Internal error");
-        return;
-    } else if (notifier->thread() != thread()
-               || thread() != QThread::currentThread()) {
-        qWarning("QSocketNotifier: socket notifiers cannot be enabled from another thread");
-        return;
-    }
-#endif
-
-    Q_D(QEventDispatcherMac);
-
-    if (type == QSocketNotifier::Exception) {
-        qWarning("QSocketNotifier::Exception is not supported on Mac OS X");
-        return;
-    }
-
-    // Check if we have a CFSocket for the native socket, create one if not.
-    MacSocketInfo *socketInfo = d->macSockets.value(nativeSocket);
-    if (!socketInfo) {
-        socketInfo = new MacSocketInfo();
-
-        // Create CFSocket, specify that we want both read and write callbacks (the callbacks
-        // are enabled/disabled later on).
-        const int callbackTypes = kCFSocketReadCallBack | kCFSocketWriteCallBack;
-        CFSocketContext context = {0, d, 0, 0, 0};
-        socketInfo->socket = CFSocketCreateWithNative(kCFAllocatorDefault, nativeSocket, callbackTypes, qt_mac_socket_callback, &context);
-        if (CFSocketIsValid(socketInfo->socket) == false) {
-            qWarning("QEventDispatcherMac::registerSocketNotifier: Failed to create CFSocket");
-            return;
-        }
-
-        CFOptionFlags flags = CFSocketGetSocketFlags(socketInfo->socket);
-        flags |= kCFSocketAutomaticallyReenableWriteCallBack; //QSocketNotifier stays enabled after a write
-        flags &= ~kCFSocketCloseOnInvalidate; //QSocketNotifier doesn't close the socket upon destruction/invalidation
-        CFSocketSetSocketFlags(socketInfo->socket, flags);
-
-        // Add CFSocket to runloop.
-        if(!(socketInfo->runloop = qt_mac_add_socket_to_runloop(socketInfo->socket))) {
-            qWarning("QEventDispatcherMac::registerSocketNotifier: Failed to add CFSocket to runloop");
-            CFSocketInvalidate(socketInfo->socket);
-            CFRelease(socketInfo->socket);
-            return;
-        }
-
-        // Disable both callback types by default. This must be done after
-        // we add the CFSocket to the runloop, or else these calls will have
-        // no effect.
-        CFSocketDisableCallBacks(socketInfo->socket, kCFSocketReadCallBack);
-        CFSocketDisableCallBacks(socketInfo->socket, kCFSocketWriteCallBack);
-
-        d->macSockets.insert(nativeSocket, socketInfo);
-    }
-
-    // Increment read/write counters and select enable callbacks if necessary.
-    if (type == QSocketNotifier::Read) {
-        Q_ASSERT(socketInfo->readNotifier == 0);
-        socketInfo->readNotifier = notifier;
-        CFSocketEnableCallBacks(socketInfo->socket, kCFSocketReadCallBack);
-    } else if (type == QSocketNotifier::Write) {
-        Q_ASSERT(socketInfo->writeNotifier == 0);
-        socketInfo->writeNotifier = notifier;
-        CFSocketEnableCallBacks(socketInfo->socket, kCFSocketWriteCallBack);
-    }
-}
-
-/*
-    Unregister QSocketNotifer. The CFSocket correspoding to this notifier is
-    removed from the runloop of this is the last notifier that users
-    that CFSocket.
-*/
-void QEventDispatcherMac::unregisterSocketNotifier(QSocketNotifier *notifier)
-{
-    Q_ASSERT(notifier);
-    int nativeSocket = notifier->socket();
-    int type = notifier->type();
-#ifndef QT_NO_DEBUG
-    if (nativeSocket < 0 || nativeSocket > FD_SETSIZE) {
-        qWarning("QSocketNotifier: Internal error");
-        return;
-    } else if (notifier->thread() != thread() || thread() != QThread::currentThread()) {
-        qWarning("QSocketNotifier: socket notifiers cannot be disabled from another thread");
-        return;
-    }
-#endif
-
-    Q_D(QEventDispatcherMac);
-
-    if (type == QSocketNotifier::Exception) {
-        qWarning("QSocketNotifier::Exception is not supported on Mac OS X");
-        return;
-    }
-    MacSocketInfo *socketInfo = d->macSockets.value(nativeSocket);
-    if (!socketInfo) {
-        qWarning("QEventDispatcherMac::unregisterSocketNotifier: Tried to unregister a not registered notifier");
-        return;
-    }
-
-    // Decrement read/write counters and disable callbacks if necessary.
-    if (type == QSocketNotifier::Read) {
-        Q_ASSERT(notifier == socketInfo->readNotifier);
-        socketInfo->readNotifier = 0;
-        CFSocketDisableCallBacks(socketInfo->socket, kCFSocketReadCallBack);
-    } else if (type == QSocketNotifier::Write) {
-        Q_ASSERT(notifier == socketInfo->writeNotifier);
-        socketInfo->writeNotifier = 0;
-        CFSocketDisableCallBacks(socketInfo->socket, kCFSocketWriteCallBack);
-    }
-
-    // Remove CFSocket from runloop if this was the last QSocketNotifier.
-    if (socketInfo->readNotifier == 0 && socketInfo->writeNotifier == 0) {
-        if (CFSocketIsValid(socketInfo->socket))
-            qt_mac_remove_socket_from_runloop(socketInfo->socket, socketInfo->runloop);
-        CFRunLoopSourceInvalidate(socketInfo->runloop);
-        CFRelease(socketInfo->runloop);
-        CFSocketInvalidate(socketInfo->socket);
-        CFRelease(socketInfo->socket);
-        delete socketInfo;
-        d->macSockets.remove(nativeSocket);
-    }
-}
-
-bool QEventDispatcherMac::hasPendingEvents()
-{
-    extern uint qGlobalPostedEventsCount();
-    return qGlobalPostedEventsCount() || (qt_is_gui_used && GetNumEventsInQueue(GetMainEventQueue()));
-}
-
-
-static bool qt_mac_send_event(QEventLoop::ProcessEventsFlags, OSEventRef event, OSWindowRef pt)
-{
-#ifndef QT_MAC_USE_COCOA
-    if(pt && SendEventToWindow(event, pt) != eventNotHandledErr)
-        return true;
-    return !SendEventToEventTarget(event, GetEventDispatcherTarget());
-#else // QT_MAC_USE_COCOA
-    if (pt)
-        [pt sendEvent:event];
-    else
-        [[NSApplication sharedApplication] sendEvent:event];
-    return true;
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-static bool IsMouseOrKeyEvent( NSEvent* event )
-{
-    bool    result    = false;
-    
-    switch( [event type] )
-    {
-        case NSLeftMouseDown:              
-        case NSLeftMouseUp:      
-        case NSRightMouseDown:   
-        case NSRightMouseUp:     
-        case NSMouseMoved:                // ??
-        case NSLeftMouseDragged: 
-        case NSRightMouseDragged:
-        case NSMouseEntered:     
-        case NSMouseExited:      
-        case NSKeyDown:          
-        case NSKeyUp:            
-        case NSFlagsChanged:            // key modifiers changed?
-        case NSCursorUpdate:            // ??
-        case NSScrollWheel:      
-        case NSTabletPoint:      
-        case NSTabletProximity:  
-        case NSOtherMouseDown:   
-        case NSOtherMouseUp:     
-        case NSOtherMouseDragged:
-#ifndef QT_NO_GESTURES
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-        case NSEventTypeGesture: // touch events
-        case NSEventTypeMagnify:
-        case NSEventTypeSwipe:
-        case NSEventTypeRotate:
-        case NSEventTypeBeginGesture:
-        case NSEventTypeEndGesture:
-#endif
-#endif // QT_NO_GESTURES
-            result    = true;
-        break;
-
-        default:
-        break;
-    }
-    return result;
-}
-#endif
-
-static inline void qt_mac_waitForMoreEvents()
-{
-#ifndef QT_MAC_USE_COCOA
-    while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e20, true) == kCFRunLoopRunTimedOut) ;
-#else
-    // If no event exist in the cocoa event que, wait
-    // (and free up cpu time) until at least one event occur.
-    // This implementation is a bit on the edge, but seems to
-    // work fine:
-    NSEvent* event = [[NSApplication sharedApplication] nextEventMatchingMask:NSAnyEventMask
-        untilDate:[NSDate distantFuture]
-        inMode:NSDefaultRunLoopMode
-        dequeue:YES];
-    if (event)
-        [[NSApplication sharedApplication] postEvent:event atStart:YES];
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-static inline void qt_mac_waitForMoreModalSessionEvents()
-{
-    // If no event exist in the cocoa event que, wait
-    // (and free up cpu time) until at least one event occur.
-    // This implementation is a bit on the edge, but seems to
-    // work fine:
-    NSEvent* event = [[NSApplication sharedApplication] nextEventMatchingMask:NSAnyEventMask
-        untilDate:[NSDate distantFuture]
-        inMode:NSModalPanelRunLoopMode
-        dequeue:YES];
-    if (event)
-        [[NSApplication sharedApplication] postEvent:event atStart:YES];
-}
-#endif
-
-bool QEventDispatcherMac::processEvents(QEventLoop::ProcessEventsFlags flags)
-{
-    Q_D(QEventDispatcherMac);
-    d->interrupt = false;
-
-#ifdef QT_MAC_USE_COCOA
-    bool interruptLater = false;
-    QtMacInterruptDispatcherHelp::cancelInterruptLater();
-#endif
-
-    // In case we end up recursing while we now process events, make sure
-    // that we send remaining posted Qt events before this call returns:
-    wakeUp();
-    emit awake();
-
-#ifdef QT_MAC_USE_COCOA
-    bool excludeUserEvents = flags & QEventLoop::ExcludeUserInputEvents;
-#endif
-    bool retVal = false;
-    forever {
-        if (d->interrupt)
-            break;
-
-#ifdef QT_MAC_USE_COCOA
-        QMacCocoaAutoReleasePool pool;
-        NSEvent* event = 0;
-
-        // First, send all previously excluded input events, if any:
-        if (!excludeUserEvents) {
-            while (!d->queuedUserInputEvents.isEmpty()) {
-                event = static_cast<NSEvent *>(d->queuedUserInputEvents.takeFirst());
-                if (!filterEvent(event)) {
-                    qt_mac_send_event(flags, event, 0);
-                    retVal = true;
-                }
-                [event release];
-            }
-        }
-
-        // If Qt is used as a plugin, or as an extension in a native cocoa
-        // application, we should not run or stop NSApplication; This will be
-        // done from the application itself. And if processEvents is called
-        // manually (rather than from a QEventLoop), we cannot enter a tight
-        // loop and block this call, but instead we need to return after one flush.
-        // Finally, if we are to exclude user input events, we cannot call [NSApplication run]
-        // as we then loose control over which events gets dispatched:
-        const bool canExec_3rdParty = d->nsAppRunCalledByQt || ![[NSApplication sharedApplication] isRunning];
-        const bool canExec_Qt = !excludeUserEvents &&
-                (flags & QEventLoop::DialogExec || flags & QEventLoop::EventLoopExec) ;
-
-        if (canExec_Qt && canExec_3rdParty) {
-            // We can use exec-mode, meaning that we can stay in a tight loop until
-            // interrupted. This is mostly an optimization, but it allow us to use
-            // [NSApplication run], which is the normal code path for cocoa applications.
-            if (NSModalSession session = d->currentModalSession()) {
-                QBoolBlocker execGuard(d->currentExecIsNSAppRun, false);
-                while ([[NSApplication sharedApplication] runModalSession:session] == NSRunContinuesResponse && !d->interrupt)
-                    qt_mac_waitForMoreModalSessionEvents();
-
-                if (!d->interrupt && session == d->currentModalSessionCached) {
-                    // Someone called [[NSApplication sharedApplication] stopModal:] from outside the event
-                    // dispatcher (e.g to stop a native dialog). But that call wrongly stopped
-                    // 'session' as well. As a result, we need to restart all internal sessions:
-                    d->temporarilyStopAllModalSessions();
-                }
-            } else {
-                d->nsAppRunCalledByQt = true;
-                QBoolBlocker execGuard(d->currentExecIsNSAppRun, true);
-                [[NSApplication sharedApplication] run];
-            }
-            retVal = true;
-        } else {
-            // We cannot block the thread (and run in a tight loop).
-            // Instead we will process all current pending events and return.
-            d->ensureNSAppInitialized();
-            if (NSModalSession session = d->currentModalSession()) {
-                // INVARIANT: a modal window is executing.
-                if (!excludeUserEvents) {
-                    // Since we can dispatch all kinds of events, we choose
-                    // to use cocoa's native way of running modal sessions:
-                    if (flags & QEventLoop::WaitForMoreEvents)
-                        qt_mac_waitForMoreModalSessionEvents();
-                    NSInteger status = [[NSApplication sharedApplication] runModalSession:session];
-                    if (status != NSRunContinuesResponse && session == d->currentModalSessionCached) {
-                        // INVARIANT: Someone called [NSApplication stopModal:] from outside the event
-                        // dispatcher (e.g to stop a native dialog). But that call wrongly stopped
-                        // 'session' as well. As a result, we need to restart all internal sessions:
-                        d->temporarilyStopAllModalSessions();
-                    }
-                    retVal = true;
-                } else do {
-                    // Dispatch all non-user events (but que non-user events up for later). In
-                    // this case, we need more control over which events gets dispatched, and
-                    // cannot use [NSApplication runModalSession:session]:
-                    event = [[NSApplication sharedApplication] nextEventMatchingMask:NSAnyEventMask
-                    untilDate:nil
-                    inMode:NSModalPanelRunLoopMode
-                    dequeue: YES];
-
-                    if (event) {
-                        if (IsMouseOrKeyEvent(event)) {
-                            [event retain];
-                            d->queuedUserInputEvents.append(event);
-                            continue;
-                        }
-                        if (!filterEvent(event) && qt_mac_send_event(flags, event, 0))
-                            retVal = true;
-                    }
-                } while (!d->interrupt && event != nil);
-            } else do {
-                // INVARIANT: No modal window is executing.
-                event = [[NSApplication sharedApplication] nextEventMatchingMask:NSAnyEventMask
-                untilDate:nil
-                inMode:NSDefaultRunLoopMode
-                dequeue: YES];
-
-                if (event) {
-                    if (flags & QEventLoop::ExcludeUserInputEvents) {
-                        if (IsMouseOrKeyEvent(event)) {
-                            [event retain];
-                            d->queuedUserInputEvents.append(event);
-                            continue;
-                        }
-                    }
-                    if (!filterEvent(event) && qt_mac_send_event(flags, event, 0))
-                        retVal = true;
-                }
-            } while (!d->interrupt && event != nil);
-
-            // Be sure to flush the Qt posted events when not using exec mode
-            // (exec mode will always do this call from the event loop source):
-            if (!d->interrupt)
-                QCoreApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
-
-            // Since the window that holds modality might have changed while processing
-            // events, we we need to interrupt when we return back the previous process
-            // event recursion to ensure that we spin the correct modal session.
-            // We do the interruptLater at the end of the function to ensure that we don't
-            // disturb the 'wait for more events' below (as deleteLater will post an event):
-            interruptLater = true;
-        }
-#else
-        do {
-            EventRef event;
-            if (!(flags & QEventLoop::ExcludeUserInputEvents)
-                    && !d->queuedUserInputEvents.isEmpty()) {
-                // process a pending user input event
-                event = static_cast<EventRef>(d->queuedUserInputEvents.takeFirst());
-            } else {
-                OSStatus err = ReceiveNextEvent(0,0, kEventDurationNoWait, true, &event);
-                if(err != noErr)
-                    continue;
-                // else
-                if (flags & QEventLoop::ExcludeUserInputEvents) {
-                    UInt32 ekind = GetEventKind(event),
-                           eclass = GetEventClass(event);
-                    switch(eclass) {
-                        case kEventClassQt:
-                            if(ekind != kEventQtRequestContext)
-                                break;
-                            // fall through
-                        case kEventClassMouse:
-                        case kEventClassKeyboard:
-                            d->queuedUserInputEvents.append(event);
-                            continue;
-                    }
-                }
-            }
-
-            if (!filterEvent(&event) && qt_mac_send_event(flags, event, 0))
-                retVal = true;
-            ReleaseEvent(event);
-        } while(!d->interrupt && GetNumEventsInQueue(GetMainEventQueue()) > 0);
-
-#endif
-
-        bool canWait = (d->threadData->canWait
-                && !retVal
-                && !d->interrupt
-                && (flags & QEventLoop::WaitForMoreEvents));
-        if (canWait) {
-            // INVARIANT: We haven't processed any events yet. And we're told
-            // to stay inside this function until at least one event is processed.
-            qt_mac_waitForMoreEvents();
-            flags &= ~QEventLoop::WaitForMoreEvents;
-        } else {
-            // Done with event processing for now.
-            // Leave the function:
-            break;
-        }
-    }
-
-    // If we're interrupted, we need to interrupt the _current_
-    // recursion as well to check if it is  still supposed to be
-    // executing. This way we wind down the stack until we land
-    // on a recursion that again calls processEvents (typically
-    // from QEventLoop), and set interrupt to false:
-    if (d->interrupt)
-        interrupt();
-
-#ifdef QT_MAC_USE_COCOA
-    if (interruptLater)
-        QtMacInterruptDispatcherHelp::interruptLater();
-#endif
-
-    return retVal;
-}
-
-void QEventDispatcherMac::wakeUp()
-{
-    Q_D(QEventDispatcherMac);
-    d->serialNumber.ref();
-    CFRunLoopSourceSignal(d->postedEventsSource);
-    CFRunLoopWakeUp(mainRunLoop());
-}
-
-void QEventDispatcherMac::flush()
-{
-    if(qApp) {
-        QWidgetList tlws = QApplication::topLevelWidgets();
-        for(int i = 0; i < tlws.size(); i++) {
-            QWidget *tlw = tlws.at(i);
-            if(tlw->isVisible())
-                macWindowFlush(qt_mac_window_for(tlw));
-        }
-    }
-}
-
-/*****************************************************************************
-  QEventDispatcherMac Implementation
- *****************************************************************************/
-MacTimerHash QEventDispatcherMacPrivate::macTimerHash;
-bool QEventDispatcherMacPrivate::blockSendPostedEvents = false;
-bool QEventDispatcherMacPrivate::interrupt = false;
-
-#ifdef QT_MAC_USE_COCOA
-QStack<QCocoaModalSessionInfo> QEventDispatcherMacPrivate::cocoaModalSessionStack;
-bool QEventDispatcherMacPrivate::currentExecIsNSAppRun = false;
-bool QEventDispatcherMacPrivate::nsAppRunCalledByQt = false;
-bool QEventDispatcherMacPrivate::cleanupModalSessionsNeeded = false;
-NSModalSession QEventDispatcherMacPrivate::currentModalSessionCached = 0;
-
-void QEventDispatcherMacPrivate::ensureNSAppInitialized()
-{
-    // Some elements in Cocoa require NSApplication to be running before
-    // they get fully initialized, in particular the menu bar. This
-    // function is intended for cases where a dialog is told to execute before
-    // QApplication::exec is called, or the application spins the events loop
-    // manually rather than calling QApplication:exec.
-    // The function makes sure that NSApplication starts running, but stops
-    // it again as soon as the send posted events callback is called. That way
-    // we let Cocoa finish the initialization it seems to need. We'll only
-    // apply this trick at most once for any application, and we avoid doing it
-    // for the common case where main just starts QApplication::exec.
-    if (nsAppRunCalledByQt || [[NSApplication sharedApplication] isRunning])
-        return;
-    nsAppRunCalledByQt = true;
-    QBoolBlocker block1(interrupt, true);
-    QBoolBlocker block2(currentExecIsNSAppRun, true);
-    [[NSApplication sharedApplication] run];
-}
-
-void QEventDispatcherMacPrivate::temporarilyStopAllModalSessions()
-{
-    // Flush, and Stop, all created modal session, and as
-    // such, make them pending again. The next call to
-    // currentModalSession will recreate them again. The
-    // reason to stop all session like this is that otherwise
-    // a call [NSApplication stop] would not stop NSApplication, but rather
-    // the current modal session. So if we need to stop NSApplication
-    // we need to stop all the modal session first. To avoid changing
-    // the stacking order of the windows while doing so, we put
-    // up a block that is used in QCocoaWindow and QCocoaPanel:
-    int stackSize = cocoaModalSessionStack.size();
-    for (int i=0; i<stackSize; ++i) {
-        QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
-        if (info.session) {
-            [[NSApplication sharedApplication] endModalSession:info.session];
-            info.session = 0;
-        }
-    }
-    currentModalSessionCached = 0;
-}
-
-NSModalSession QEventDispatcherMacPrivate::currentModalSession()
-{
-    // If we have one or more modal windows, this function will create
-    // a session for each of those, and return the one for the top.
-    if (currentModalSessionCached)
-        return currentModalSessionCached;
-
-    if (cocoaModalSessionStack.isEmpty())
-        return 0;
-
-    int sessionCount = cocoaModalSessionStack.size();
-    for (int i=0; i<sessionCount; ++i) {
-        QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
-        if (!info.widget)
-            continue;
-        if (info.widget->testAttribute(Qt::WA_DontShowOnScreen))
-            continue;
-        if (!info.session) {
-            QMacCocoaAutoReleasePool pool;
-            NSWindow *window = qt_mac_window_for(info.widget);
-            if (!window)
-                continue;
-
-            ensureNSAppInitialized();
-            QBoolBlocker block1(blockSendPostedEvents, true);
-            info.nswindow = window;
-            [(NSWindow*) info.nswindow retain];
-            int levelBeforeEnterModal = [window level];
-            info.session = [[NSApplication sharedApplication] beginModalSessionForWindow:window];
-            // Make sure we don't stack the window lower that it was before
-            // entering modal, in case it e.g. had the stays-on-top flag set:
-            if (levelBeforeEnterModal > [window level])
-                [window setLevel:levelBeforeEnterModal];
-        }
-        currentModalSessionCached = info.session;
-        cleanupModalSessionsNeeded = false;
-    }
-    return currentModalSessionCached;
-}
-
-static void setChildrenWorksWhenModal(QWidget *widget, bool worksWhenModal)
-{
-    // For NSPanels (but not NSWindows, sadly), we can set the flag
-    // worksWhenModal, so that they are active even when they are not modal. 
-    QList<QDialog *> dialogs = widget->findChildren<QDialog *>();
-    for (int i=0; i<dialogs.size(); ++i){
-        NSWindow *window = qt_mac_window_for(dialogs[i]);
-        if (window && [window isKindOfClass:[NSPanel class]]) {
-            [static_cast<NSPanel *>(window) setWorksWhenModal:worksWhenModal];
-            if (worksWhenModal && [window isVisible]){
-                [window orderFront:window];
-            }
-        }
-    }
-}
-
-void QEventDispatcherMacPrivate::updateChildrenWorksWhenModal()
-{
-    // Make the dialog children of the widget
-    // active. And make the dialog children of
-    // the previous modal dialog unactive again:
-    QMacCocoaAutoReleasePool pool;
-    int size = cocoaModalSessionStack.size();
-    if (size > 0){
-        if (QWidget *prevModal = cocoaModalSessionStack[size-1].widget)
-            setChildrenWorksWhenModal(prevModal, true);
-        if (size > 1){
-            if (QWidget *prevModal = cocoaModalSessionStack[size-2].widget)
-                setChildrenWorksWhenModal(prevModal, false);
-        }
-    }
-}
-
-void QEventDispatcherMacPrivate::cleanupModalSessions()
-{
-    // Go through the list of modal sessions, and end those
-    // that no longer has a widget assosiated; no widget means
-    // the the session has logically ended. The reason we wait like
-    // this to actually end the sessions for real (rather than at the
-    // point they were marked as stopped), is that ending a session
-    // when no other session runs below it on the stack will make cocoa
-    // drop some events on the floor. 
-    QMacCocoaAutoReleasePool pool;
-    int stackSize = cocoaModalSessionStack.size();
-
-    for (int i=stackSize-1; i>=0; --i) {
-        QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
-        if (info.widget) {
-            // This session has a widget, and is therefore not marked
-            // as stopped. So just make it current. There might still be other
-            // stopped sessions on the stack, but those will be stopped on
-            // a later "cleanup" call.
-            currentModalSessionCached = info.session;
-            break;
-        }
-        cocoaModalSessionStack.remove(i);
-        currentModalSessionCached = 0;
-        if (info.session) {
-            [[NSApplication sharedApplication] endModalSession:info.session];
-            [(NSWindow *)info.nswindow release];
-        }
-    }
-
-    updateChildrenWorksWhenModal();
-    cleanupModalSessionsNeeded = false;
-}
-
-void QEventDispatcherMacPrivate::beginModalSession(QWidget *widget)
-{
-    // Add a new, empty (null), NSModalSession to the stack.
-    // It will become active the next time QEventDispatcher::processEvents is called.
-    // A QCocoaModalSessionInfo is considered pending to become active if the widget pointer 
-    // is non-zero, and the session pointer is zero (it will become active upon a call to
-    // currentModalSession). A QCocoaModalSessionInfo is considered pending to be stopped if
-    // the widget pointer is zero, and the session pointer is non-zero (it will be fully
-    // stopped in cleanupModalSessions()).
-    QCocoaModalSessionInfo info = {widget, 0, 0};
-    cocoaModalSessionStack.push(info);
-    updateChildrenWorksWhenModal();
-    currentModalSessionCached = 0;
-}
-
-void QEventDispatcherMacPrivate::endModalSession(QWidget *widget)
-{
-    // Mark all sessions attached to widget as pending to be stopped. We do this
-    // by setting the widget pointer to zero, but leave the session pointer.
-    // We don't tell cocoa to stop any sessions just yet, because cocoa only understands
-    // when we stop the _current_ modal session (which is the session on top of
-    // the stack, and might not belong to 'widget'). 
-    int stackSize = cocoaModalSessionStack.size();
-    for (int i=stackSize-1; i>=0; --i) {
-        QCocoaModalSessionInfo &info = cocoaModalSessionStack[i];
-        if (info.widget == widget) {
-            info.widget = 0;
-            if (i == stackSize-1) {
-                // The top sessions ended. Interrupt the event dispatcher
-                // to start spinning the correct session immidiatly: 
-                currentModalSessionCached = 0;
-                cleanupModalSessionsNeeded = true;
-                QEventDispatcherMac::instance()->interrupt();
-            }
-        }
-    }
-}
-
-#endif
-
-QEventDispatcherMacPrivate::QEventDispatcherMacPrivate()
-{
-}
-
-QEventDispatcherMac::QEventDispatcherMac(QObject *parent)
-    : QAbstractEventDispatcher(*new QEventDispatcherMacPrivate, parent)
-{
-    Q_D(QEventDispatcherMac);
-    CFRunLoopSourceContext context;
-    bzero(&context, sizeof(CFRunLoopSourceContext));
-    context.info = d;
-    context.equal = QEventDispatcherMacPrivate::postedEventSourceEqualCallback;
-    context.perform = QEventDispatcherMacPrivate::postedEventsSourcePerformCallback;
-    d->postedEventsSource = CFRunLoopSourceCreate(0, 0, &context);
-    Q_ASSERT(d->postedEventsSource);
-    CFRunLoopAddSource(mainRunLoop(), d->postedEventsSource, kCFRunLoopCommonModes);
-
-    CFRunLoopObserverContext observerContext;
-    bzero(&observerContext, sizeof(CFRunLoopObserverContext));
-    observerContext.info = this;
-    d->waitingObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
-                                                 kCFRunLoopBeforeWaiting | kCFRunLoopAfterWaiting,
-                                                 true, 0,
-                                                 QEventDispatcherMacPrivate::waitingObserverCallback,
-                                                 &observerContext);
-    CFRunLoopAddObserver(mainRunLoop(), d->waitingObserver, kCFRunLoopCommonModes);
-
-    /* The first cycle in the loop adds the source and the events of the source
-       are not processed.
-       We use an observer to process the posted events for the first
-       execution of the loop. */
-    CFRunLoopObserverContext firstTimeObserverContext;
-    bzero(&firstTimeObserverContext, sizeof(CFRunLoopObserverContext));
-    firstTimeObserverContext.info = d;
-    d->firstTimeObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
-                                                   kCFRunLoopEntry,
-                                                   /* repeats = */ false,
-                                                   0,
-                                                   QEventDispatcherMacPrivate::firstLoopEntry,
-                                                   &firstTimeObserverContext);
-    CFRunLoopAddObserver(mainRunLoop(), d->firstTimeObserver, kCFRunLoopCommonModes);
-}
-
-void QEventDispatcherMacPrivate::waitingObserverCallback(CFRunLoopObserverRef,
-                                                          CFRunLoopActivity activity, void *info)
-{
-    if (activity == kCFRunLoopBeforeWaiting)
-        emit static_cast<QEventDispatcherMac*>(info)->aboutToBlock();
-    else
-        emit static_cast<QEventDispatcherMac*>(info)->awake();
-}
-
-Boolean QEventDispatcherMacPrivate::postedEventSourceEqualCallback(const void *info1, const void *info2)
-{
-    return info1 == info2;
-}
-
-inline static void processPostedEvents(QEventDispatcherMacPrivate *const d, const bool blockSendPostedEvents)
-{
-    if (blockSendPostedEvents) {
-        // We're told to not send posted events (because the event dispatcher
-        // is currently working on setting up the correct session to run). But
-        // we still need to make sure that we don't fall asleep until pending events
-        // are sendt, so we just signal this need, and return:
-        CFRunLoopSourceSignal(d->postedEventsSource);
-        return;
-    }
-
-#ifdef QT_MAC_USE_COCOA
-    if (d->cleanupModalSessionsNeeded)
-        d->cleanupModalSessions();
-#endif
-
-    if (d->interrupt) {
-#ifdef QT_MAC_USE_COCOA
-        if (d->currentExecIsNSAppRun) {
-            // The event dispatcher has been interrupted. But since
-            // [NSApplication run] is running the event loop, we
-            // delayed stopping it until now (to let cocoa process 
-            // pending cocoa events first).
-            if (d->currentModalSessionCached)
-                d->temporarilyStopAllModalSessions();
-            [[NSApplication sharedApplication] stop:[NSApplication sharedApplication]];
-            d->cancelWaitForMoreEvents();
-        }
-#endif
-        return;
-    }
-
-    if (!d->threadData->canWait || (d->serialNumber != d->lastSerial)) {
-        d->lastSerial = d->serialNumber;
-        QApplicationPrivate::sendPostedEvents(0, 0, d->threadData);
-    }
-}
-
-void QEventDispatcherMacPrivate::firstLoopEntry(CFRunLoopObserverRef ref,
-                                                CFRunLoopActivity activity,
-                                                void *info)
-{
-    Q_UNUSED(ref);
-    Q_UNUSED(activity);
-#ifdef QT_MAC_USE_COCOA
-    QApplicationPrivate::qt_initAfterNSAppStarted();
-#endif
-    processPostedEvents(static_cast<QEventDispatcherMacPrivate *>(info), blockSendPostedEvents);
-}
-
-void QEventDispatcherMacPrivate::postedEventsSourcePerformCallback(void *info)
-{
-    processPostedEvents(static_cast<QEventDispatcherMacPrivate *>(info), blockSendPostedEvents);
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QEventDispatcherMacPrivate::cancelWaitForMoreEvents()
-{
-    // In case the event dispatcher is waiting for more
-    // events somewhere, we post a dummy event to wake it up:
-    QMacCocoaAutoReleasePool pool;
-    [[NSApplication sharedApplication] postEvent:[NSEvent otherEventWithType:NSApplicationDefined
-        location:NSZeroPoint
-        modifierFlags:0 timestamp:0. windowNumber:0 context:0
-        subtype:QtCocoaEventSubTypeWakeup data1:0 data2:0] atStart:NO];
-}
-#endif
-
-void QEventDispatcherMac::interrupt()
-{
-    Q_D(QEventDispatcherMac);
-    d->interrupt = true;
-    wakeUp();
-
-#ifndef QT_MAC_USE_COCOA
-    CFRunLoopStop(mainRunLoop());
-#else
-    // We do nothing more here than setting d->interrupt = true, and
-    // poke the event loop if it is sleeping. Actually stopping
-    // NSApplication, or the current modal session, is done inside the send
-    // posted events callback. We do this to ensure that all current pending
-    // cocoa events gets delivered before we stop. Otherwise, if we now stop
-    // the last event loop recursion, cocoa will just drop pending posted
-    // events on the floor before we get a chance to reestablish a new session.
-    d->cancelWaitForMoreEvents();
-#endif
-}
-
-QEventDispatcherMac::~QEventDispatcherMac()
-{
-    Q_D(QEventDispatcherMac);
-    //timer cleanup
-    MacTimerHash::iterator it = QEventDispatcherMacPrivate::macTimerHash.begin();
-    while (it != QEventDispatcherMacPrivate::macTimerHash.end()) {
-        MacTimerInfo *t = it.value();
-        if (t->runLoopTimer) {
-            CFRunLoopTimerInvalidate(t->runLoopTimer);
-            CFRelease(t->runLoopTimer);
-        }
-        delete t;
-        ++it;
-    }
-    QEventDispatcherMacPrivate::macTimerHash.clear();
-
-    // Remove CFSockets from the runloop.
-    for (MacSocketHash::ConstIterator it = d->macSockets.constBegin(); it != d->macSockets.constEnd(); ++it) {
-        MacSocketInfo *socketInfo = (*it);
-        if (CFSocketIsValid(socketInfo->socket)) {
-            qt_mac_remove_socket_from_runloop(socketInfo->socket, socketInfo->runloop);
-            CFRunLoopSourceInvalidate(socketInfo->runloop);
-            CFRelease(socketInfo->runloop);
-            CFSocketInvalidate(socketInfo->socket);
-            CFRelease(socketInfo->socket);
-        }
-    }
-    CFRunLoopRemoveSource(mainRunLoop(), d->postedEventsSource, kCFRunLoopCommonModes);
-    CFRelease(d->postedEventsSource);
-
-    CFRunLoopObserverInvalidate(d->waitingObserver);
-    CFRelease(d->waitingObserver);
-
-    CFRunLoopObserverInvalidate(d->firstTimeObserver);
-    CFRelease(d->firstTimeObserver);
-}
-
-#ifdef QT_MAC_USE_COCOA
-
-QtMacInterruptDispatcherHelp* QtMacInterruptDispatcherHelp::instance = 0;
-
-QtMacInterruptDispatcherHelp::QtMacInterruptDispatcherHelp() : cancelled(false)
-{
-    // The whole point of this class is that we enable a way to interrupt
-    // the event dispatcher when returning back to a lower recursion level
-    // than where interruptLater was called. This is needed to detect if
-    // [NSApplication run] should still be running at the recursion level it is at.
-    // Since the interrupt is canceled if processEvents is called before
-    // this object gets deleted, we also avoid interrupting unnecessary.
-    deleteLater();
-}
-
-QtMacInterruptDispatcherHelp::~QtMacInterruptDispatcherHelp()
-{
-    if (cancelled)
-        return;
-    instance = 0;
-    QEventDispatcherMac::instance()->interrupt();
-}
-
-void QtMacInterruptDispatcherHelp::cancelInterruptLater()
-{
-    if (!instance)
-        return;
-    instance->cancelled = true;
-    delete instance;
-    instance = 0;
-}
-
-void QtMacInterruptDispatcherHelp::interruptLater()
-{
-    cancelInterruptLater();
-    instance = new QtMacInterruptDispatcherHelp;
-}
-
-#endif
-
-QT_END_NAMESPACE
-
-#include "moc_qeventdispatcher_mac_p.h"
diff --git a/src/gui/kernel/qeventdispatcher_mac_p.h b/src/gui/kernel/qeventdispatcher_mac_p.h
deleted file mode 100644 (file)
index 0f4cb05..0000000
+++ /dev/null
@@ -1,224 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#ifndef QEVENTDISPATCHER_MAC_P_H
-#define QEVENTDISPATCHER_MAC_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/qwindowdefs.h>
-#include <QtCore/qhash.h>
-#include <QtCore/qstack.h>
-#include "qabstracteventdispatcher_p.h"
-#include "qt_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-typedef struct _NSModalSession *NSModalSession;
-typedef struct _QCocoaModalSessionInfo {
-    QPointer<QWidget> widget;
-    NSModalSession session;
-    void *nswindow;
-} QCocoaModalSessionInfo;
-#endif
-
-class QEventDispatcherMacPrivate;
-
-class QEventDispatcherMac : public QAbstractEventDispatcher
-{
-    Q_OBJECT
-    Q_DECLARE_PRIVATE(QEventDispatcherMac)
-
-public:
-    explicit QEventDispatcherMac(QObject *parent = 0);
-    ~QEventDispatcherMac();
-
-    bool processEvents(QEventLoop::ProcessEventsFlags flags);
-    bool hasPendingEvents();
-
-    void registerSocketNotifier(QSocketNotifier *notifier);
-    void unregisterSocketNotifier(QSocketNotifier *notifier);
-
-    void registerTimer(int timerId, int interval, QObject *object);
-    bool unregisterTimer(int timerId);
-    bool unregisterTimers(QObject *object);
-    QList<TimerInfo> registeredTimers(QObject *object) const;
-
-    void wakeUp();
-    void flush();
-    void interrupt();
-
-private:
-    friend void qt_mac_select_timer_callbk(__EventLoopTimer*, void*);
-    friend class QApplicationPrivate;
-};
-
-struct MacTimerInfo {
-    int id;
-    int interval;
-    QObject *obj;
-    bool pending;
-    CFRunLoopTimerRef runLoopTimer;
-    bool operator==(const MacTimerInfo &other)
-    {
-        return (id == other.id);
-    }
-};
-typedef QHash<int, MacTimerInfo *> MacTimerHash;
-
-struct MacSocketInfo {
-    MacSocketInfo() : socket(0), runloop(0), readNotifier(0), writeNotifier(0) {}
-    CFSocketRef socket;
-    CFRunLoopSourceRef runloop;
-    QObject *readNotifier;
-    QObject *writeNotifier;
-};
-typedef QHash<int, MacSocketInfo *> MacSocketHash;
-
-class QEventDispatcherMacPrivate : public QAbstractEventDispatcherPrivate
-{
-    Q_DECLARE_PUBLIC(QEventDispatcherMac)
-
-public:
-    QEventDispatcherMacPrivate();
-
-    static MacTimerHash macTimerHash;
-    // Set 'blockSendPostedEvents' to true if you _really_ need
-    // to make sure that qt events are not posted while calling
-    // low-level cocoa functions (like beginModalForWindow). And
-    // use a QBoolBlocker to be safe:
-    static bool blockSendPostedEvents;
-#ifdef QT_MAC_USE_COCOA
-    // The following variables help organizing modal sessions:
-    static QStack<QCocoaModalSessionInfo> cocoaModalSessionStack;
-    static bool currentExecIsNSAppRun;
-    static bool nsAppRunCalledByQt;
-    static bool cleanupModalSessionsNeeded;
-    static NSModalSession currentModalSessionCached;
-    static NSModalSession currentModalSession();
-    static void updateChildrenWorksWhenModal();
-    static void temporarilyStopAllModalSessions();
-    static void beginModalSession(QWidget *widget);
-    static void endModalSession(QWidget *widget);
-    static void cancelWaitForMoreEvents();
-    static void cleanupModalSessions();
-    static void ensureNSAppInitialized();
-#endif
-
-    MacSocketHash macSockets;
-    QList<void *> queuedUserInputEvents; // List of EventRef in Carbon, and NSEvent * in Cocoa
-    CFRunLoopSourceRef postedEventsSource;
-    CFRunLoopObserverRef waitingObserver;
-    CFRunLoopObserverRef firstTimeObserver;
-    QAtomicInt serialNumber;
-    int lastSerial;
-    static bool interrupt;
-private:
-    static Boolean postedEventSourceEqualCallback(const void *info1, const void *info2);
-    static void postedEventsSourcePerformCallback(void *info);
-    static void activateTimer(CFRunLoopTimerRef, void *info);
-    static void waitingObserverCallback(CFRunLoopObserverRef observer,
-                                        CFRunLoopActivity activity, void *info);
-    static void firstLoopEntry(CFRunLoopObserverRef ref, CFRunLoopActivity activity, void *info);
-};
-
-#ifdef QT_MAC_USE_COCOA
-class QtMacInterruptDispatcherHelp : public QObject
-{
-    static QtMacInterruptDispatcherHelp *instance;
-    bool cancelled;
-
-    QtMacInterruptDispatcherHelp();
-    ~QtMacInterruptDispatcherHelp();
-
-    public:
-    static void interruptLater();
-    static void cancelInterruptLater();
-};
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QEVENTDISPATCHER_MAC_P_H
diff --git a/src/gui/kernel/qguifunctions_wince.cpp b/src/gui/kernel/qguifunctions_wince.cpp
deleted file mode 100644 (file)
index 7489113..0000000
+++ /dev/null
@@ -1,407 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include "qguifunctions_wince.h"
-#include <shellapi.h>
-#include <QtCore/qlibrary.h>
-
-QT_USE_NAMESPACE
-
-struct AygSHINITDLGINFO
-{
-    DWORD dwMask;
-    HWND  hDlg;
-    DWORD dwFlags;
-};
-
-struct AygSIPINFO
-{
-    DWORD   cbSize;
-    DWORD   fdwFlags;
-    RECT    rcVisibleDesktop;
-    RECT    rcSipRect;
-    DWORD   dwImDataSize;
-    void   *pvImData;
-};
-
-#ifndef SHIDIF_CANCELBUTTON
-#define SHIDIF_CANCELBUTTON 0x0080
-#endif
-
-#ifndef SHIDIM_FLAGS
-#define SHIDIM_FLAGS 0x0001
-#endif
-
-#ifndef SHIDIF_DONEBUTTON
-#define SHIDIF_DONEBUTTON 0x0001
-#endif
-#ifndef SHIDIF_SIZEDLGFULLSCREEN
-#define SHIDIF_SIZEDLGFULLSCREEN 0x0004
-#endif
-
-#ifndef SHDB_HIDE
-#define SHDB_HIDE 0x0002
-#endif
-
-#ifndef SHFS_SHOWTASKBAR
-#define SHFS_SHOWTASKBAR 0x0001
-#endif
-#ifndef SHFS_HIDETASKBAR
-#define SHFS_HIDETASKBAR 0x0002
-#endif
-#ifndef SHFS_SHOWSIPBUTTON
-#define SHFS_SHOWSIPBUTTON 0x0004
-#endif
-#ifndef SHFS_HIDESIPBUTTON
-#define SHFS_HIDESIPBUTTON 0x0008
-#endif
-#ifndef SHFS_SHOWSTARTICON
-#define SHFS_SHOWSTARTICON 0x0010
-#endif
-#ifndef SHFS_HIDESTARTICON
-#define SHFS_HIDESTARTICON 0x0020
-#endif
-
-#ifndef SIPF_OFF
-#define SIPF_OFF 0x00000000
-#endif
-#ifndef SIPF_ON
-#define SIPF_ON 0x00000001
-#endif
-
-#ifndef SPI_SETSIPINFO
-#define SPI_SETSIPINFO 224
-#endif
-#ifndef SPI_GETSIPINFO
-#define SPI_GETSIPINFO 225
-#endif
-#ifndef SPI_GETPLATFORMTYPE
-#define SPI_GETPLATFORMTYPE 257
-#endif
-
-typedef BOOL (*AygInitDialog)(AygSHINITDLGINFO*);
-typedef BOOL (*AygFullScreen)(HWND, DWORD);
-typedef BOOL (*AygSHSipInfo)(UINT, UINT, PVOID, UINT);
-typedef BOOL (*AygSHDoneButton)(HWND, DWORD);
-
-static AygInitDialog ptrAygInitDialog = 0;
-static AygFullScreen ptrAygFullScreen = 0;
-static AygSHSipInfo  ptrAygSHSipInfo  = 0;
-static AygSHDoneButton ptrAygSHDoneButton = 0;
-static void resolveAygLibs()
-{
-    static bool aygResolved = false;
-    if (!aygResolved) {
-        QLibrary ayglib(QLatin1String("aygshell"));
-        ptrAygInitDialog = (AygInitDialog) ayglib.resolve("SHInitDialog");
-        ptrAygFullScreen = (AygFullScreen) ayglib.resolve("SHFullScreen");
-        ptrAygSHSipInfo  = (AygSHSipInfo)  ayglib.resolve("SHSipInfo");
-        ptrAygSHDoneButton = (AygSHDoneButton) ayglib.resolve("SHDoneButton");
-        aygResolved = true;
-    }
-}
-
-int qt_wince_GetDIBits(HDC /*hdc*/ , HBITMAP hSourceBitmap, uint, uint, LPVOID lpvBits, LPBITMAPINFO, uint)
-{
-    if (!lpvBits) {
-        qWarning("::GetDIBits(), lpvBits NULL");
-        return 0;
-    }
-    BITMAP bm;
-    GetObject(hSourceBitmap, sizeof(BITMAP), &bm);
-    bm.bmHeight = qAbs(bm.bmHeight);
-
-    HBITMAP hTargetBitmap;
-    void *pixels;
-
-    BITMAPINFO dibInfo;
-    memset(&dibInfo, 0, sizeof(dibInfo));
-    dibInfo.bmiHeader.biBitCount = 32;
-    dibInfo.bmiHeader.biClrImportant = 0;
-    dibInfo.bmiHeader.biClrUsed = 0;
-    dibInfo.bmiHeader.biCompression = BI_RGB;;
-    dibInfo.bmiHeader.biHeight = -bm.bmHeight;
-    dibInfo.bmiHeader.biWidth = bm.bmWidth;
-    dibInfo.bmiHeader.biPlanes = 1;
-    dibInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
-    dibInfo.bmiHeader.biSizeImage = bm.bmWidth * bm.bmHeight * 4;
-
-    HDC displayDC = GetDC(NULL);
-    if (!displayDC) {
-        qWarning("::GetDIBits(), failed to GetDC");
-        return 0;
-    }
-
-    int ret = bm.bmHeight;
-
-    hTargetBitmap = CreateDIBSection(displayDC, (const BITMAPINFO*) &dibInfo, DIB_RGB_COLORS,
-                                    (void**)&pixels, NULL, 0);
-    if (!hTargetBitmap) {
-        qWarning("::GetDIBits(), failed to CreateDIBSection");
-        return 0;
-    }
-
-    HDC hdcSrc = CreateCompatibleDC(displayDC);
-    HDC hdcDst = CreateCompatibleDC(displayDC);
-
-    if (!(hdcDst && hdcSrc)) {
-        qWarning("::GetDIBits(), failed to CreateCompatibleDC");
-        ret = 0;
-    }
-
-    HBITMAP hOldBitmap1 = (HBITMAP) SelectObject(hdcSrc, hSourceBitmap);
-    HBITMAP hOldBitmap2 = (HBITMAP) SelectObject(hdcDst, hTargetBitmap);
-
-    if (!(hOldBitmap1 && hOldBitmap2)) {
-        qWarning("::GetDIBits(), failed to SelectObject for bitmaps");
-        ret = 0;
-    }
-
-    if (!BitBlt(hdcDst, 0, 0, bm.bmWidth, bm.bmHeight, hdcSrc, 0, 0, SRCCOPY)) {
-        qWarning("::GetDIBits(), BitBlt failed");
-        ret = 0;
-    }
-
-    SelectObject(hdcSrc, hOldBitmap1);
-    SelectObject(hdcDst, hOldBitmap2);
-
-    DeleteDC(hdcSrc);
-    DeleteDC(hdcDst);
-
-    ReleaseDC(NULL, displayDC);
-
-    memcpy(lpvBits, pixels, dibInfo.bmiHeader.biSizeImage);
-
-    DeleteObject(hTargetBitmap);
-    return ret;
-}
-
-HINSTANCE qt_wince_ShellExecute(HWND hwnd, LPCWSTR, LPCWSTR file, LPCWSTR params, LPCWSTR dir, int showCmd)
-{
-    SHELLEXECUTEINFO info;
-    info.hwnd = hwnd;
-    info.lpVerb = L"Open";
-    info.lpFile = file;
-    info.lpParameters = params;
-    info.lpDirectory = dir;
-    info.nShow = showCmd;
-    info.cbSize = sizeof(info);
-    ShellExecuteEx(&info);
-    return info.hInstApp;
-}
-
-// Clipboard --------------------------------------------------------
-BOOL qt_wince_ChangeClipboardChain( HWND /*hWndRemove*/, HWND /*hWndNewNext*/ )
-{
-    return FALSE;
-}
-
-HWND qt_wince_SetClipboardViewer( HWND /*hWndNewViewer*/ )
-{
-    return NULL;
-}
-
-
-// Graphics ---------------------------------------------------------
-COLORREF qt_wince_PALETTEINDEX( WORD /*wPaletteIndex*/)
-{
-    return 0;
-}
-
-// Internal Qt -----------------------------------------------------
-bool qt_wince_is_platform(const QString &platformString) {
-    wchar_t tszPlatform[64];
-    if (SystemParametersInfo(SPI_GETPLATFORMTYPE, sizeof(tszPlatform) / sizeof(wchar_t), tszPlatform, 0))
-        if (0 == _tcsicmp(reinterpret_cast<const wchar_t *> (platformString.utf16()), tszPlatform))
-            return true;
-    return false;
-}
-
-int qt_wince_get_build()
-{
-    OSVERSIONINFO osvi;
-    osvi.dwOSVersionInfoSize = sizeof(osvi);
-    if (GetVersionEx(&osvi)) {
-        return osvi.dwBuildNumber;
-    } 
-    return 0;
-}
-
-int qt_wince_get_version()
-{
-    OSVERSIONINFO osvi;
-    osvi.dwOSVersionInfoSize = sizeof(osvi);
-    if (GetVersionEx(&osvi)) {
-        return (osvi.dwMajorVersion * 10 + osvi.dwMinorVersion);
-    } 
-    return 0;
-}
-
-bool qt_wince_is_windows_mobile_65()
-{
-    const DWORD dwFirstWM65BuildNumber = 21139;
-    OSVERSIONINFO osvi;
-    osvi.dwOSVersionInfoSize = sizeof(osvi);
-    if (!GetVersionEx(&osvi))
-        return false;
-    return osvi.dwMajorVersion > 5
-        || (osvi.dwMajorVersion == 5 && (osvi.dwMinorVersion > 2 ||
-            (osvi.dwMinorVersion == 2 && osvi.dwBuildNumber >= dwFirstWM65BuildNumber)));
-}
-
-bool qt_wince_is_pocket_pc() {
-    return qt_wince_is_platform(QString::fromLatin1("PocketPC"));
-}
-
-bool qt_wince_is_smartphone() {
-       return qt_wince_is_platform(QString::fromLatin1("Smartphone"));
-}
-bool qt_wince_is_mobile() {
-     return (qt_wince_is_smartphone() || qt_wince_is_pocket_pc());
-}
-
-bool qt_wince_is_high_dpi() {
-    if (!qt_wince_is_pocket_pc())
-        return false;
-    HDC deviceContext = GetDC(0);
-    int dpi = GetDeviceCaps(deviceContext, LOGPIXELSX);
-    ReleaseDC(0, deviceContext);
-    if ((dpi < 1000) && (dpi > 0))
-        return dpi > 96;
-    else
-        return false;
-}
-
-void qt_wince_maximize(QWidget *widget)
-{
-    HWND hwnd = widget->winId();
-    if (qt_wince_is_mobile()) {
-        AygSHINITDLGINFO shidi;
-        shidi.dwMask = SHIDIM_FLAGS;
-        shidi.hDlg = hwnd;
-        shidi.dwFlags = SHIDIF_SIZEDLGFULLSCREEN;
-        if (widget->windowFlags() & Qt::WindowCancelButtonHint)
-            shidi.dwFlags |= SHIDIF_CANCELBUTTON;
-        if (widget->windowFlags() & Qt::WindowOkButtonHint)
-            shidi.dwFlags |= SHIDIF_DONEBUTTON;
-        if (!(widget->windowFlags() & (Qt::WindowCancelButtonHint | Qt::WindowOkButtonHint)))
-            shidi.dwFlags |= SHIDIF_CANCELBUTTON;
-        resolveAygLibs();
-        if (ptrAygInitDialog)
-            ptrAygInitDialog(&shidi);
-    } else {
-        RECT r;
-        SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
-        MoveWindow(hwnd, r.top, r.left, r.right - r.left, r.bottom - r.top, true);
-        SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_NODRAG);
-    }
-}
-
-void qt_wince_unmaximize(QWidget *widget)
-{
-    if (ptrAygSHDoneButton && qt_wince_is_mobile()
-        && !(widget->windowFlags() & (Qt::WindowCancelButtonHint | Qt::WindowOkButtonHint)))
-    {
-        // Hide the [X] button, we've added in qt_wince_maximize.
-        ptrAygSHDoneButton(widget->winId(), SHDB_HIDE);
-    }
-}
-
-void qt_wince_minimize(HWND hwnd)
-{
-#ifdef Q_OS_WINCE_WM
-    ShowWindow(hwnd, SW_HIDE);
-#else
-    if (!IsWindowVisible(hwnd)) {
-        // Hack for an initial showMinimized.
-        // Without it, our widget doesn't appear in the task bar.
-        ShowWindow(hwnd, SW_SHOW);
-    }
-    ShowWindow(hwnd, SW_MINIMIZE);
-#endif
-}
-
-void qt_wince_hide_taskbar(HWND hwnd) {
-    if (ptrAygFullScreen)
-        ptrAygFullScreen(hwnd, SHFS_HIDETASKBAR | SHFS_HIDESIPBUTTON | SHFS_HIDESTARTICON);
-}
-
-void qt_wince_full_screen(HWND hwnd, bool fullScreen, UINT swpf) {
-    resolveAygLibs();
-    if (fullScreen) {
-        QRect r = qApp->desktop()->screenGeometry(QWidget::find(hwnd));
-        SetWindowPos(hwnd, HWND_TOP, r.left(), r.top(), r.width(), r.height(), swpf);
-        if (ptrAygFullScreen)
-            ptrAygFullScreen(hwnd, SHFS_HIDETASKBAR | SHFS_HIDESIPBUTTON | SHFS_HIDESTARTICON);
-        if (!qt_wince_is_mobile()) {
-            HWND handle = FindWindow(L"HHTaskBar", L"");
-            if (handle) {
-                ShowWindow(handle, 0);
-                EnableWindow(handle, false);
-            }
-        }
-    } else {
-        if (ptrAygFullScreen)
-            ptrAygFullScreen(hwnd, SHFS_SHOWTASKBAR | SHFS_SHOWSIPBUTTON | SHFS_SHOWSTARTICON);
-        SetWindowPos(hwnd, 0, 0, 0, 0, 0, swpf);
-        if (!qt_wince_is_mobile()) {
-            HWND handle = FindWindow(L"HHTaskBar", L"");
-            if (handle) {
-                ShowWindow(handle, 1);
-                EnableWindow(handle, true);
-            }
-        }
-    }
-}
-
-void qt_wince_show_SIP(bool show)
-{
-    resolveAygLibs();
-    if (!ptrAygSHSipInfo)
-        return;
-
-    AygSIPINFO si;
-    memset(&si, 0, sizeof(si));
-    si.cbSize = sizeof(si);
-    ptrAygSHSipInfo(SPI_GETSIPINFO, 0, &si, 0);
-    si.cbSize = sizeof(si);
-    si.fdwFlags = (show ? SIPF_ON : SIPF_OFF);
-    ptrAygSHSipInfo(SPI_SETSIPINFO, 0, &si, 0);
-}
diff --git a/src/gui/kernel/qguifunctions_wince.h b/src/gui/kernel/qguifunctions_wince.h
deleted file mode 100644 (file)
index 9114fcd..0000000
+++ /dev/null
@@ -1,150 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef QGUIFUNCTIONS_WCE_H
-#define QGUIFUNCTIONS_WCE_H
-#ifdef Q_OS_WINCE
-#include <QtCore/qfunctions_wince.h>
-#define UNDER_NT
-#include <wingdi.h>
-
-#ifdef QT_BUILD_GUI_LIB
-QT_BEGIN_HEADER
-QT_BEGIN_NAMESPACE
-QT_END_NAMESPACE
-QT_END_HEADER
-#endif
-
-// application defines
-#define SPI_SETNONCLIENTMETRICS 72
-#define SPI_SETICONTITLELOGFONT 0x0022
-#define WM_ACTIVATEAPP 0x001c
-#define SW_PARENTCLOSING    1
-#define SW_OTHERMAXIMIZED   2
-#define SW_PARENTOPENING    3
-#define SW_OTHERRESTORED    4
-#define GET_XBUTTON_WPARAM(wParam)      (HIWORD(wParam))
-
-// drag n drop
-#ifndef CFSTR_PERFORMEDDROPEFFECT
-#define CFSTR_PERFORMEDDROPEFFECT TEXT("Performed DropEffect")
-#endif
-int qt_wince_GetDIBits(HDC, HBITMAP, uint, uint, void*, LPBITMAPINFO, uint);
-#define GetDIBits(a,b,c,d,e,f,g) qt_wince_GetDIBits(a,b,c,d,e,f,g)
-
-// QWidget
-#define SW_SHOWMINIMIZED SW_MINIMIZE
-
-// QRegion
-#define ALTERNATE 0
-#define WINDING 1
-
-// QFontEngine
-typedef struct _FIXED {
-  WORD  fract;
-  short value;
-} FIXED;
-
-typedef struct tagPOINTFX {
-  FIXED x;
-  FIXED y;
-} POINTFX;
-
-typedef struct _MAT2 {
-  FIXED eM11;
-  FIXED eM12;
-  FIXED eM21;
-  FIXED eM22;
-} MAT2;
-
-typedef struct _GLYPHMETRICS {
-    UINT    gmBlackBoxX;
-    UINT    gmBlackBoxY;
-    POINT   gmptGlyphOrigin;
-    short   gmCellIncX;
-    short   gmCellIncY;
-} GLYPHMETRICS;
-
-typedef struct tagTTPOLYGONHEADER
-{
-    DWORD   cb;
-    DWORD   dwType;
-    POINTFX pfxStart;
-} TTPOLYGONHEADER;
-
-typedef struct tagTTPOLYCURVE
-{
-    WORD    wType;
-    WORD    cpfx;
-    POINTFX apfx[1];
-} TTPOLYCURVE;
-
-#define GGO_NATIVE 2
-#define GGO_GLYPH_INDEX 0x0080
-#define TT_PRIM_LINE 1
-#define TT_PRIM_QSPLINE 2
-#define TT_PRIM_CSPLINE 3
-#define ANSI_VAR_FONT 12
-
-HINSTANCE qt_wince_ShellExecute(HWND hwnd, LPCWSTR operation, LPCWSTR file, LPCWSTR params, LPCWSTR dir, int showCmd);
-#define ShellExecute(a,b,c,d,e,f) qt_wince_ShellExecute(a,b,c,d,e,f)
-
-
-// Clipboard --------------------------------------------------------
-#define WM_CHANGECBCHAIN       1
-#define WM_DRAWCLIPBOARD       2
-
-BOOL qt_wince_ChangeClipboardChain(
-    HWND hWndRemove,  // handle to window to remove
-    HWND hWndNewNext  // handle to next window
-);
-#define ChangeClipboardChain(a,b) qt_wince_ChangeClipboardChain(a,b);
-
-HWND qt_wince_SetClipboardViewer(
-    HWND hWndNewViewer   // handle to clipboard viewer window
-);
-#define SetClipboardViewer(a) qt_wince_SetClipboardViewer(a)
-
-// Graphics ---------------------------------------------------------
-COLORREF qt_wince_PALETTEINDEX( WORD wPaletteIndex );
-#define PALETTEINDEX(a) qt_wince_PALETTEINDEX(a)
-
-#endif // Q_OS_WINCE
-#endif // QGUIFUNCTIONS_WCE_H
diff --git a/src/gui/kernel/qkeymapper_mac.cpp b/src/gui/kernel/qkeymapper_mac.cpp
deleted file mode 100644 (file)
index 6fac6dd..0000000
+++ /dev/null
@@ -1,997 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qt_mac_p.h>
-#include <qdebug.h>
-#include <qevent.h>
-#include <qevent_p.h>
-#include <qtextcodec.h>
-#include <qapplication.h>
-#include <qinputcontext.h>
-#include <qkeymapper_p.h>
-#include <qapplication_p.h>
-#include <qmacinputcontext_p.h>
-
-QT_BEGIN_NAMESPACE
-
-QT_USE_NAMESPACE
-
-/*****************************************************************************
-  QKeyMapper debug facilities
- *****************************************************************************/
-//#define DEBUG_KEY_BINDINGS
-//#define DEBUG_KEY_BINDINGS_MODIFIERS
-//#define DEBUG_KEY_MAPS
-
-/*****************************************************************************
-  Internal variables and functions
- *****************************************************************************/
-bool qt_mac_eat_unicode_key = false;
-extern bool qt_sendSpontaneousEvent(QObject *obj, QEvent *event); //qapplication_mac.cpp
-
-Q_GUI_EXPORT void qt_mac_secure_keyboard(bool b)
-{
-    static bool secure = false;
-    if (b != secure){
-        b ? EnableSecureEventInput() : DisableSecureEventInput();
-        secure = b;
-    }
-}
-
-/*
-    \internal
-    A Mac KeyboardLayoutItem has 8 possible states:
-        1. Unmodified
-        2. Shift
-        3. Control
-        4. Control + Shift
-        5. Alt
-        6. Alt + Shift
-        7. Alt + Control
-        8. Alt + Control + Shift
-        9. Meta
-        10. Meta + Shift
-        11. Meta + Control
-        12. Meta + Control + Shift
-        13. Meta + Alt
-        14. Meta + Alt + Shift
-        15. Meta + Alt + Control
-        16. Meta + Alt + Control + Shift
-*/
-struct KeyboardLayoutItem {
-    bool dirty;
-    quint32 qtKey[16]; // Can by any Qt::Key_<foo>, or unicode character
-};
-
-// Possible modifier states.
-// NOTE: The order of these states match the order in QKeyMapperPrivate::updatePossibleKeyCodes()!
-static const Qt::KeyboardModifiers ModsTbl[] = {
-    Qt::NoModifier,                                             // 0
-    Qt::ShiftModifier,                                          // 1
-    Qt::ControlModifier,                                        // 2
-    Qt::ControlModifier | Qt::ShiftModifier,                    // 3
-    Qt::AltModifier,                                            // 4
-    Qt::AltModifier | Qt::ShiftModifier,                        // 5
-    Qt::AltModifier | Qt::ControlModifier,                      // 6
-    Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier,  // 7
-    Qt::MetaModifier,                                           // 8
-    Qt::MetaModifier | Qt::ShiftModifier,                       // 9
-    Qt::MetaModifier | Qt::ControlModifier,                    // 10
-    Qt::MetaModifier | Qt::ControlModifier | Qt::ShiftModifier,// 11
-    Qt::MetaModifier | Qt::AltModifier,                        // 12
-    Qt::MetaModifier | Qt::AltModifier | Qt::ShiftModifier,    // 13
-    Qt::MetaModifier | Qt::AltModifier | Qt::ControlModifier,  // 14
-    Qt::MetaModifier | Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier,  // 15
-};
-
-/* key maps */
-struct qt_mac_enum_mapper
-{
-    int mac_code;
-    int qt_code;
-#if defined(DEBUG_KEY_BINDINGS)
-#   define QT_MAC_MAP_ENUM(x) x, #x
-    const char *desc;
-#else
-#   define QT_MAC_MAP_ENUM(x) x
-#endif
-};
-
-//modifiers
-static qt_mac_enum_mapper qt_mac_modifier_symbols[] = {
-    { shiftKey, QT_MAC_MAP_ENUM(Qt::ShiftModifier) },
-    { rightShiftKey, QT_MAC_MAP_ENUM(Qt::ShiftModifier) },
-    { controlKey, QT_MAC_MAP_ENUM(Qt::MetaModifier) },
-    { rightControlKey, QT_MAC_MAP_ENUM(Qt::MetaModifier) },
-    { cmdKey, QT_MAC_MAP_ENUM(Qt::ControlModifier) },
-    { optionKey, QT_MAC_MAP_ENUM(Qt::AltModifier) },
-    { rightOptionKey, QT_MAC_MAP_ENUM(Qt::AltModifier) },
-    { kEventKeyModifierNumLockMask, QT_MAC_MAP_ENUM(Qt::KeypadModifier) },
-    { 0, QT_MAC_MAP_ENUM(0) }
-};
-Qt::KeyboardModifiers qt_mac_get_modifiers(int keys)
-{
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-    qDebug("Qt: internal: **Mapping modifiers: %d (0x%04x)", keys, keys);
-#endif
-    Qt::KeyboardModifiers ret = Qt::NoModifier;
-    for (int i = 0; qt_mac_modifier_symbols[i].qt_code; i++) {
-        if (keys & qt_mac_modifier_symbols[i].mac_code) {
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-            qDebug("Qt: internal: got modifier: %s", qt_mac_modifier_symbols[i].desc);
-#endif
-            ret |= Qt::KeyboardModifier(qt_mac_modifier_symbols[i].qt_code);
-        }
-    }
-    if (qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta)) {
-        Qt::KeyboardModifiers oldModifiers = ret;
-        ret &= ~(Qt::MetaModifier | Qt::ControlModifier);
-        if (oldModifiers & Qt::ControlModifier)
-            ret |= Qt::MetaModifier;
-        if (oldModifiers & Qt::MetaModifier)
-            ret |= Qt::ControlModifier;
-    }
-    return ret;
-}
-static int qt_mac_get_mac_modifiers(Qt::KeyboardModifiers keys)
-{
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-    qDebug("Qt: internal: **Mapping modifiers: %d (0x%04x)", (int)keys, (int)keys);
-#endif
-    int ret = 0;
-    for (int i = 0; qt_mac_modifier_symbols[i].qt_code; i++) {
-        if (keys & qt_mac_modifier_symbols[i].qt_code) {
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-            qDebug("Qt: internal: got modifier: %s", qt_mac_modifier_symbols[i].desc);
-#endif
-            ret |= qt_mac_modifier_symbols[i].mac_code;
-        }
-    }
-
-    if (qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta)) {
-        int oldModifiers = ret;
-        ret &= ~(controlKeyBit | cmdKeyBit);
-        if (oldModifiers & controlKeyBit)
-            ret |= cmdKeyBit;
-        if (oldModifiers & cmdKeyBit)
-            ret |= controlKeyBit;
-    }
-    return ret;
-}
-void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object)
-{
-    static quint32 cachedModifiers = 0;
-    quint32 lastModifiers = cachedModifiers,
-          changedModifiers = lastModifiers ^ modifiers;
-    cachedModifiers = modifiers;
-
-    //check the bits
-    static qt_mac_enum_mapper modifier_key_symbols[] = {
-        { shiftKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Shift) },
-        { rightShiftKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Shift) }, //???
-        { controlKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Meta) },
-        { rightControlKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Meta) }, //???
-        { cmdKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Control) },
-        { optionKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Alt) },
-        { rightOptionKeyBit, QT_MAC_MAP_ENUM(Qt::Key_Alt) }, //???
-        { alphaLockBit, QT_MAC_MAP_ENUM(Qt::Key_CapsLock) },
-        { kEventKeyModifierNumLockBit, QT_MAC_MAP_ENUM(Qt::Key_NumLock) },
-        {   0, QT_MAC_MAP_ENUM(0) } };
-    for (int i = 0; i <= 32; i++) { //just check each bit
-        if (!(changedModifiers & (1 << i)))
-            continue;
-        QEvent::Type etype = QEvent::KeyPress;
-        if (lastModifiers & (1 << i))
-            etype = QEvent::KeyRelease;
-        int key = 0;
-        for (uint x = 0; modifier_key_symbols[x].mac_code; x++) {
-            if (modifier_key_symbols[x].mac_code == i) {
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-                qDebug("got modifier changed: %s", modifier_key_symbols[x].desc);
-#endif
-                key = modifier_key_symbols[x].qt_code;
-                break;
-            }
-        }
-        if (!key) {
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-            qDebug("could not get modifier changed: %d", i);
-#endif
-            continue;
-        }
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-        qDebug("KeyEvent (modif): Sending %s to %s::%s: %d - 0x%08x",
-               etype == QEvent::KeyRelease ? "KeyRelease" : "KeyPress",
-               object ? object->metaObject()->className() : "none",
-               object ? object->objectName().toLatin1().constData() : "",
-               key, (int)modifiers);
-#endif
-        QKeyEvent ke(etype, key, qt_mac_get_modifiers(modifiers ^ (1 << i)), QLatin1String(""));
-        qt_sendSpontaneousEvent(object, &ke);
-    }
-}
-
-//keyboard keys (non-modifiers)
-static qt_mac_enum_mapper qt_mac_keyboard_symbols[] = {
-    { kHomeCharCode, QT_MAC_MAP_ENUM(Qt::Key_Home) },
-    { kEnterCharCode, QT_MAC_MAP_ENUM(Qt::Key_Enter) },
-    { kEndCharCode, QT_MAC_MAP_ENUM(Qt::Key_End) },
-    { kBackspaceCharCode, QT_MAC_MAP_ENUM(Qt::Key_Backspace) },
-    { kTabCharCode, QT_MAC_MAP_ENUM(Qt::Key_Tab) },
-    { kPageUpCharCode, QT_MAC_MAP_ENUM(Qt::Key_PageUp) },
-    { kPageDownCharCode, QT_MAC_MAP_ENUM(Qt::Key_PageDown) },
-    { kReturnCharCode, QT_MAC_MAP_ENUM(Qt::Key_Return) },
-    { kEscapeCharCode, QT_MAC_MAP_ENUM(Qt::Key_Escape) },
-    { kLeftArrowCharCode, QT_MAC_MAP_ENUM(Qt::Key_Left) },
-    { kRightArrowCharCode, QT_MAC_MAP_ENUM(Qt::Key_Right) },
-    { kUpArrowCharCode, QT_MAC_MAP_ENUM(Qt::Key_Up) },
-    { kDownArrowCharCode, QT_MAC_MAP_ENUM(Qt::Key_Down) },
-    { kHelpCharCode, QT_MAC_MAP_ENUM(Qt::Key_Help) },
-    { kDeleteCharCode, QT_MAC_MAP_ENUM(Qt::Key_Delete) },
-//ascii maps, for debug
-    { ':', QT_MAC_MAP_ENUM(Qt::Key_Colon) },
-    { ';', QT_MAC_MAP_ENUM(Qt::Key_Semicolon) },
-    { '<', QT_MAC_MAP_ENUM(Qt::Key_Less) },
-    { '=', QT_MAC_MAP_ENUM(Qt::Key_Equal) },
-    { '>', QT_MAC_MAP_ENUM(Qt::Key_Greater) },
-    { '?', QT_MAC_MAP_ENUM(Qt::Key_Question) },
-    { '@', QT_MAC_MAP_ENUM(Qt::Key_At) },
-    { ' ', QT_MAC_MAP_ENUM(Qt::Key_Space) },
-    { '!', QT_MAC_MAP_ENUM(Qt::Key_Exclam) },
-    { '"', QT_MAC_MAP_ENUM(Qt::Key_QuoteDbl) },
-    { '#', QT_MAC_MAP_ENUM(Qt::Key_NumberSign) },
-    { '$', QT_MAC_MAP_ENUM(Qt::Key_Dollar) },
-    { '%', QT_MAC_MAP_ENUM(Qt::Key_Percent) },
-    { '&', QT_MAC_MAP_ENUM(Qt::Key_Ampersand) },
-    { '\'', QT_MAC_MAP_ENUM(Qt::Key_Apostrophe) },
-    { '(', QT_MAC_MAP_ENUM(Qt::Key_ParenLeft) },
-    { ')', QT_MAC_MAP_ENUM(Qt::Key_ParenRight) },
-    { '*', QT_MAC_MAP_ENUM(Qt::Key_Asterisk) },
-    { '+', QT_MAC_MAP_ENUM(Qt::Key_Plus) },
-    { ',', QT_MAC_MAP_ENUM(Qt::Key_Comma) },
-    { '-', QT_MAC_MAP_ENUM(Qt::Key_Minus) },
-    { '.', QT_MAC_MAP_ENUM(Qt::Key_Period) },
-    { '/', QT_MAC_MAP_ENUM(Qt::Key_Slash) },
-    { '[', QT_MAC_MAP_ENUM(Qt::Key_BracketLeft) },
-    { ']', QT_MAC_MAP_ENUM(Qt::Key_BracketRight) },
-    { '\\', QT_MAC_MAP_ENUM(Qt::Key_Backslash) },
-    { '_', QT_MAC_MAP_ENUM(Qt::Key_Underscore) },
-    { '`', QT_MAC_MAP_ENUM(Qt::Key_QuoteLeft) },
-    { '{', QT_MAC_MAP_ENUM(Qt::Key_BraceLeft) },
-    { '}', QT_MAC_MAP_ENUM(Qt::Key_BraceRight) },
-    { '|', QT_MAC_MAP_ENUM(Qt::Key_Bar) },
-    { '~', QT_MAC_MAP_ENUM(Qt::Key_AsciiTilde) },
-    { '^', QT_MAC_MAP_ENUM(Qt::Key_AsciiCircum) },
-    {   0, QT_MAC_MAP_ENUM(0) }
-};
-
-static qt_mac_enum_mapper qt_mac_keyvkey_symbols[] = { //real scan codes
-    { 122, QT_MAC_MAP_ENUM(Qt::Key_F1) },
-    { 120, QT_MAC_MAP_ENUM(Qt::Key_F2) },
-    { 99,  QT_MAC_MAP_ENUM(Qt::Key_F3) },
-    { 118, QT_MAC_MAP_ENUM(Qt::Key_F4) },
-    { 96,  QT_MAC_MAP_ENUM(Qt::Key_F5) },
-    { 97,  QT_MAC_MAP_ENUM(Qt::Key_F6) },
-    { 98,  QT_MAC_MAP_ENUM(Qt::Key_F7) },
-    { 100, QT_MAC_MAP_ENUM(Qt::Key_F8) },
-    { 101, QT_MAC_MAP_ENUM(Qt::Key_F9) },
-    { 109, QT_MAC_MAP_ENUM(Qt::Key_F10) },
-    { 103, QT_MAC_MAP_ENUM(Qt::Key_F11) },
-    { 111, QT_MAC_MAP_ENUM(Qt::Key_F12) },
-    { 105, QT_MAC_MAP_ENUM(Qt::Key_F13) },
-    { 107, QT_MAC_MAP_ENUM(Qt::Key_F14) },
-    { 113, QT_MAC_MAP_ENUM(Qt::Key_F15) },
-    { 106, QT_MAC_MAP_ENUM(Qt::Key_F16) },
-    {   0, QT_MAC_MAP_ENUM(0) }
-};
-
-static qt_mac_enum_mapper qt_mac_private_unicode[] = {
-    { 0xF700, QT_MAC_MAP_ENUM(Qt::Key_Up) },            //NSUpArrowFunctionKey
-    { 0xF701, QT_MAC_MAP_ENUM(Qt::Key_Down) },          //NSDownArrowFunctionKey
-    { 0xF702, QT_MAC_MAP_ENUM(Qt::Key_Left) },          //NSLeftArrowFunctionKey
-    { 0xF703, QT_MAC_MAP_ENUM(Qt::Key_Right) },         //NSRightArrowFunctionKey
-    { 0xF727, QT_MAC_MAP_ENUM(Qt::Key_Insert) },        //NSInsertFunctionKey
-    { 0xF728, QT_MAC_MAP_ENUM(Qt::Key_Delete) },        //NSDeleteFunctionKey
-    { 0xF729, QT_MAC_MAP_ENUM(Qt::Key_Home) },          //NSHomeFunctionKey
-    { 0xF72B, QT_MAC_MAP_ENUM(Qt::Key_End) },           //NSEndFunctionKey
-    { 0xF72C, QT_MAC_MAP_ENUM(Qt::Key_PageUp) },        //NSPageUpFunctionKey
-    { 0xF72D, QT_MAC_MAP_ENUM(Qt::Key_PageDown) },      //NSPageDownFunctionKey
-    { 0xF72F, QT_MAC_MAP_ENUM(Qt::Key_ScrollLock) },    //NSScrollLockFunctionKey
-    { 0xF730, QT_MAC_MAP_ENUM(Qt::Key_Pause) },         //NSPauseFunctionKey
-    { 0xF731, QT_MAC_MAP_ENUM(Qt::Key_SysReq) },        //NSSysReqFunctionKey
-    { 0xF735, QT_MAC_MAP_ENUM(Qt::Key_Menu) },          //NSMenuFunctionKey
-    { 0xF738, QT_MAC_MAP_ENUM(Qt::Key_Print) },         //NSPrintFunctionKey
-    { 0xF73A, QT_MAC_MAP_ENUM(Qt::Key_Clear) },         //NSClearDisplayFunctionKey
-    { 0xF73D, QT_MAC_MAP_ENUM(Qt::Key_Insert) },        //NSInsertCharFunctionKey
-    { 0xF73E, QT_MAC_MAP_ENUM(Qt::Key_Delete) },        //NSDeleteCharFunctionKey
-    { 0xF741, QT_MAC_MAP_ENUM(Qt::Key_Select) },        //NSSelectFunctionKey
-    { 0xF742, QT_MAC_MAP_ENUM(Qt::Key_Execute) },       //NSExecuteFunctionKey
-    { 0xF746, QT_MAC_MAP_ENUM(Qt::Key_Help) },          //NSHelpFunctionKey
-    { 0xF747, QT_MAC_MAP_ENUM(Qt::Key_Mode_switch) },   //NSModeSwitchFunctionKey
-    {   0,    QT_MAC_MAP_ENUM(0) }
-};
-
-static int qt_mac_get_key(int modif, const QChar &key, int virtualKey)
-{
-#ifdef DEBUG_KEY_BINDINGS
-    qDebug("**Mapping key: %d (0x%04x) - %d (0x%04x)", key.unicode(), key.unicode(), virtualKey, virtualKey);
-#endif
-
-    if (key == kClearCharCode && virtualKey == 0x47)
-        return Qt::Key_Clear;
-
-    if (key.isDigit()) {
-#ifdef DEBUG_KEY_BINDINGS
-            qDebug("%d: got key: %d", __LINE__, key.digitValue());
-#endif
-        return key.digitValue() + Qt::Key_0;
-    }
-
-    if (key.isLetter()) {
-#ifdef DEBUG_KEY_BINDINGS
-        qDebug("%d: got key: %d", __LINE__, (key.toUpper().unicode() - 'A'));
-#endif
-        return (key.toUpper().unicode() - 'A') + Qt::Key_A;
-    }
-    if (key.isSymbol()) {
-#ifdef DEBUG_KEY_BINDINGS
-        qDebug("%d: got key: %d", __LINE__, (key.unicode()));
-#endif
-        return key.unicode();
-    }
-
-    for (int i = 0; qt_mac_keyboard_symbols[i].qt_code; i++) {
-        if (qt_mac_keyboard_symbols[i].mac_code == key) {
-            /* To work like Qt for X11 we issue Backtab when Shift + Tab are pressed */
-            if (qt_mac_keyboard_symbols[i].qt_code == Qt::Key_Tab && (modif & Qt::ShiftModifier)) {
-#ifdef DEBUG_KEY_BINDINGS
-                qDebug("%d: got key: Qt::Key_Backtab", __LINE__);
-#endif
-                return Qt::Key_Backtab;
-            }
-
-#ifdef DEBUG_KEY_BINDINGS
-            qDebug("%d: got key: %s", __LINE__, qt_mac_keyboard_symbols[i].desc);
-#endif
-            return qt_mac_keyboard_symbols[i].qt_code;
-        }
-    }
-
-    //last ditch try to match the scan code
-    for (int i = 0; qt_mac_keyvkey_symbols[i].qt_code; i++) {
-        if (qt_mac_keyvkey_symbols[i].mac_code == virtualKey) {
-#ifdef DEBUG_KEY_BINDINGS
-            qDebug("%d: got key: %s", __LINE__, qt_mac_keyvkey_symbols[i].desc);
-#endif
-            return qt_mac_keyvkey_symbols[i].qt_code;
-        }
-    }
-
-    // check if they belong to key codes in private unicode range
-    if (key >= 0xf700 && key <= 0xf747) {
-        if (key >= 0xf704 && key <= 0xf726) {
-            return Qt::Key_F1 + (key.unicode() - 0xf704) ;
-        }
-        for (int i = 0; qt_mac_private_unicode[i].qt_code; i++) {
-            if (qt_mac_private_unicode[i].mac_code == key) {
-                return qt_mac_private_unicode[i].qt_code;
-            }
-        }
-
-    }
-
-    //oh well
-#ifdef DEBUG_KEY_BINDINGS
-    qDebug("Unknown case.. %s:%d %d[%d] %d", __FILE__, __LINE__, key.unicode(), key.toLatin1(), virtualKey);
-#endif
-    return Qt::Key_unknown;
-}
-
-static Boolean qt_KeyEventComparatorProc(EventRef inEvent, void *data)
-{
-    UInt32 ekind = GetEventKind(inEvent),
-           eclass = GetEventClass(inEvent);
-    return (eclass == kEventClassKeyboard && (void *)ekind == data);
-}
-
-static bool translateKeyEventInternal(EventHandlerCallRef er, EventRef keyEvent, int *qtKey,
-                                      QChar *outChar, Qt::KeyboardModifiers *outModifiers, bool *outHandled)
-{
-#if !defined(QT_MAC_USE_COCOA) || defined(Q_OS_MAC64)
-    Q_UNUSED(er);
-    Q_UNUSED(outHandled);
-#endif
-    const UInt32 ekind = GetEventKind(keyEvent);
-    {
-        UInt32 mac_modifiers = 0;
-        GetEventParameter(keyEvent, kEventParamKeyModifiers, typeUInt32, 0,
-                          sizeof(mac_modifiers), 0, &mac_modifiers);
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-        qDebug("************ Mapping modifiers and key ***********");
-#endif
-        *outModifiers = qt_mac_get_modifiers(mac_modifiers);
-#ifdef DEBUG_KEY_BINDINGS_MODIFIERS
-        qDebug("------------ Mapping modifiers and key -----------");
-#endif
-    }
-
-    //get keycode
-    UInt32 keyCode = 0;
-    GetEventParameter(keyEvent, kEventParamKeyCode, typeUInt32, 0, sizeof(keyCode), 0, &keyCode);
-
-    //get mac mapping
-    static UInt32 tmp_unused_state = 0L;
-    const UCKeyboardLayout *uchrData = 0;
-#if defined(Q_OS_MAC32)
-    KeyboardLayoutRef keyLayoutRef = 0;
-    KLGetCurrentKeyboardLayout(&keyLayoutRef);
-    OSStatus err;
-    if (keyLayoutRef != 0) {
-        err = KLGetKeyboardLayoutProperty(keyLayoutRef, kKLuchrData,
-                                  (reinterpret_cast<const void **>(&uchrData)));
-        if (err != noErr) {
-            qWarning("Qt::internal::unable to get keyboardlayout %ld %s:%d",
-                     long(err), __FILE__, __LINE__);
-        }
-    }
-#else
-    QCFType<TISInputSourceRef> inputSource = TISCopyCurrentKeyboardInputSource();
-    Q_ASSERT(inputSource != 0);
-    CFDataRef data = static_cast<CFDataRef>(TISGetInputSourceProperty(inputSource,
-                                                                 kTISPropertyUnicodeKeyLayoutData));
-    uchrData = data ? reinterpret_cast<const UCKeyboardLayout *>(CFDataGetBytePtr(data)) : 0;
-#endif
-    *qtKey = Qt::Key_unknown;
-    if (uchrData) {
-        // The easy stuff; use the unicode stuff!
-        UniChar string[4];
-        UniCharCount actualLength;
-        UInt32 currentModifiers = GetCurrentEventKeyModifiers();
-        UInt32 currentModifiersWOAltOrControl = currentModifiers & ~(controlKey | optionKey);
-        int keyAction;
-        switch (ekind) {
-        default:
-        case kEventRawKeyDown:
-            keyAction = kUCKeyActionDown;
-            break;
-        case kEventRawKeyUp:
-            keyAction = kUCKeyActionUp;
-            break;
-        case kEventRawKeyRepeat:
-            keyAction = kUCKeyActionAutoKey;
-            break;
-        }
-        OSStatus err = UCKeyTranslate(uchrData, keyCode, keyAction,
-                                  ((currentModifiersWOAltOrControl >> 8) & 0xff), LMGetKbdType(),
-                                  kUCKeyTranslateNoDeadKeysMask, &tmp_unused_state, 4, &actualLength,
-                                  string);
-        if (err == noErr) {
-            *outChar = QChar(string[0]);
-            *qtKey = qt_mac_get_key(*outModifiers, *outChar, keyCode);
-            if (currentModifiersWOAltOrControl != currentModifiers) {
-                // Now get the real char.
-                err = UCKeyTranslate(uchrData, keyCode, keyAction,
-                                     ((currentModifiers >> 8) & 0xff), LMGetKbdType(),
-                                      kUCKeyTranslateNoDeadKeysMask, &tmp_unused_state, 4, &actualLength,
-                                      string);
-                if (err == noErr)
-                    *outChar = QChar(string[0]);
-            }
-        } else {
-            qWarning("Qt::internal::UCKeyTranslate is returnining %ld %s:%d",
-                     long(err), __FILE__, __LINE__);
-        }
-    }
-#ifdef Q_OS_MAC32
-    else {
-        // The road less travelled; use KeyTranslate
-        const void *keyboard_layout;
-        KeyboardLayoutRef keyLayoutRef = 0;
-        KLGetCurrentKeyboardLayout(&keyLayoutRef);
-        err = KLGetKeyboardLayoutProperty(keyLayoutRef, kKLKCHRData,
-                                  reinterpret_cast<const void **>(&keyboard_layout));
-
-        int translatedChar = KeyTranslate(keyboard_layout, (GetCurrentEventKeyModifiers() &
-                                                             (kEventKeyModifierNumLockMask|shiftKey|cmdKey|
-                                                              rightShiftKey|alphaLock)) | keyCode,
-                                           &tmp_unused_state);
-        if (!translatedChar) {
-#ifdef QT_MAC_USE_COCOA
-            if (outHandled) {
-                qt_mac_eat_unicode_key = false;
-                if (er)
-                    CallNextEventHandler(er, keyEvent);
-                *outHandled = qt_mac_eat_unicode_key;
-            }
-#endif
-            return false;
-        }
-
-        //map it into qt keys
-        *qtKey = qt_mac_get_key(*outModifiers, QChar(translatedChar), keyCode);
-        if (*outModifiers & (Qt::AltModifier | Qt::ControlModifier)) {
-            if (translatedChar & (1 << 7)) //high ascii
-                translatedChar = 0;
-        } else {          //now get the real ascii value
-            UInt32 tmp_mod = 0L;
-            static UInt32 tmp_state = 0L;
-            if (*outModifiers & Qt::ShiftModifier)
-                tmp_mod |= shiftKey;
-            if (*outModifiers & Qt::MetaModifier)
-                tmp_mod |= controlKey;
-            if (*outModifiers & Qt::ControlModifier)
-                tmp_mod |= cmdKey;
-            if (GetCurrentEventKeyModifiers() & alphaLock) //no Qt mapper
-                tmp_mod |= alphaLock;
-            if (*outModifiers & Qt::AltModifier)
-                tmp_mod |= optionKey;
-            if (*outModifiers & Qt::KeypadModifier)
-                tmp_mod |= kEventKeyModifierNumLockMask;
-            translatedChar = KeyTranslate(keyboard_layout, tmp_mod | keyCode, &tmp_state);
-        }
-        {
-            ByteCount unilen = 0;
-            if (GetEventParameter(keyEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, 0, &unilen, 0)
-                    == noErr && unilen == 2) {
-                GetEventParameter(keyEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, unilen, 0, outChar);
-            } else if (translatedChar) {
-                static QTextCodec *c = 0;
-                if (!c)
-                    c = QTextCodec::codecForName("Apple Roman");
-               char tmpChar = (char)translatedChar; // **sigh**
-                *outChar = c->toUnicode(&tmpChar, 1).at(0);
-            } else {
-                *qtKey = qt_mac_get_key(*outModifiers, QChar(translatedChar), keyCode);
-            }
-        }
-    }
-#endif
-    if (*qtKey == Qt::Key_unknown)
-        *qtKey = qt_mac_get_key(*outModifiers, *outChar, keyCode);
-    return true;
-}
-
-QKeyMapperPrivate::QKeyMapperPrivate()
-{
-    memset(keyLayout, 0, sizeof(keyLayout));
-    keyboard_layout_format.unicode = 0;
-#ifdef Q_OS_MAC32
-    keyboard_mode = NullMode;
-#else
-    currentInputSource = 0;
-#endif
-}
-
-QKeyMapperPrivate::~QKeyMapperPrivate()
-{
-    deleteLayouts();
-}
-
-bool
-QKeyMapperPrivate::updateKeyboard()
-{
-    const UCKeyboardLayout *uchrData = 0;
-#ifdef Q_OS_MAC32
-    KeyboardLayoutRef keyLayoutRef = 0;
-    KLGetCurrentKeyboardLayout(&keyLayoutRef);
-
-    if (keyboard_mode != NullMode && currentKeyboardLayout == keyLayoutRef)
-        return false;
-
-    OSStatus err;
-    if (keyLayoutRef != 0) {
-        err = KLGetKeyboardLayoutProperty(keyLayoutRef, kKLuchrData,
-                                  const_cast<const void **>(reinterpret_cast<const void **>(&uchrData)));
-        if (err != noErr) {
-            qWarning("Qt::internal::unable to get unicode keyboardlayout %ld %s:%d",
-                     long(err), __FILE__, __LINE__);
-        }
-    }
-#else
-    QCFType<TISInputSourceRef> source = TISCopyCurrentKeyboardInputSource();
-    if (keyboard_mode != NullMode && source == currentInputSource) {
-        return false;
-    }
-    Q_ASSERT(source != 0);
-    CFDataRef data = static_cast<CFDataRef>(TISGetInputSourceProperty(source,
-                                                                 kTISPropertyUnicodeKeyLayoutData));
-    uchrData = data ? reinterpret_cast<const UCKeyboardLayout *>(CFDataGetBytePtr(data)) : 0;
-#endif
-
-    keyboard_kind = LMGetKbdType();
-    if (uchrData) {
-        keyboard_layout_format.unicode = uchrData;
-        keyboard_mode = UnicodeMode;
-    }
-#ifdef Q_OS_MAC32
-    else {
-        void *happy;
-        err = KLGetKeyboardLayoutProperty(keyLayoutRef, kKLKCHRData,
-                                  const_cast<const void **>(reinterpret_cast<void **>(&happy)));
-        if (err != noErr) {
-            qFatal("Qt::internal::unable to get non-unicode layout, cannot procede %ld %s:%d",
-                     long(err), __FILE__, __LINE__);
-        }
-        keyboard_layout_format.other = happy;
-        keyboard_mode = OtherMode;
-    }
-
-    currentKeyboardLayout = keyLayoutRef;
-#else
-    currentInputSource = source;
-#endif
-    keyboard_dead = 0;
-    CFStringRef iso639Code;
-#ifdef Q_OS_MAC32
-# ifndef kKLLanguageCode
-# define kKLLanguageCode 9
-# endif
-    KLGetKeyboardLayoutProperty(currentKeyboardLayout, kKLLanguageCode,
-                                reinterpret_cast<const void **>(&iso639Code));
-#else
-    CFArrayRef array = static_cast<CFArrayRef>(TISGetInputSourceProperty(currentInputSource, kTISPropertyInputSourceLanguages));
-    iso639Code = static_cast<CFStringRef>(CFArrayGetValueAtIndex(array, 0)); // Actually a RFC3066bis, but it's close enough
-#endif
-    if (iso639Code) {
-        keyboardInputLocale = QLocale(QCFString::toQString(iso639Code));
-        keyboardInputDirection = keyboardInputLocale.textDirection();
-    } else {
-        keyboardInputLocale = QLocale::c();
-        keyboardInputDirection = Qt::LeftToRight;
-    }
-    return true;
-}
-
-void
-QKeyMapperPrivate::deleteLayouts()
-{
-    keyboard_mode = NullMode;
-    for (int i = 0; i < 255; ++i) {
-        if (keyLayout[i]) {
-            delete keyLayout[i];
-            keyLayout[i] = 0;
-        }
-    }
-}
-
-void
-QKeyMapperPrivate::clearMappings()
-{
-    deleteLayouts();
-    updateKeyboard();
-}
-
-QList<int>
-QKeyMapperPrivate::possibleKeys(QKeyEvent *e)
-{
-    QList<int> ret;
-
-    KeyboardLayoutItem *kbItem = keyLayout[e->nativeVirtualKey()];
-    if (!kbItem) // Key is not in any keyboard layout (e.g. eisu-key on Japanese keyboard) 
-        return ret;
-
-    int baseKey = kbItem->qtKey[0];
-    Qt::KeyboardModifiers keyMods = e->modifiers();
-    ret << int(baseKey + keyMods); // The base key is _always_ valid, of course
-
-    for (int i = 1; i < 8; ++i) {
-        Qt::KeyboardModifiers neededMods = ModsTbl[i];
-        int key = kbItem->qtKey[i];
-        if (key && key != baseKey && ((keyMods & neededMods) == neededMods))
-            ret << int(key + (keyMods & ~neededMods));
-    }
-
-    return ret;
-}
-
-bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, EventHandlerCallRef er, EventRef event,
-                                          void *info, bool grab)
-{
-    Q_ASSERT(GetEventClass(event) == kEventClassKeyboard);
-    bool handled_event=true;
-    UInt32 ekind = GetEventKind(event);
-
-    // unfortunately modifiers changed event looks quite different, so I have a separate
-    // code path
-    if (ekind == kEventRawKeyModifiersChanged) {
-        //figure out changed modifiers, wish Apple would just send a delta
-        UInt32 modifiers = 0;
-        GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, 0,
-                          sizeof(modifiers), 0, &modifiers);
-        qt_mac_send_modifiers_changed(modifiers, widget);
-        return true;
-    }
-#ifndef QT_NO_IM
-    QInputContext *currentContext = qApp->inputContext();
-    if (currentContext && currentContext->isComposing()) {
-        if (ekind == kEventRawKeyDown) {
-            QMacInputContext *context = qobject_cast<QMacInputContext*>(currentContext);
-            if (context)
-                context->setLastKeydownEvent(event);
-        }
-        return false;
-    }
-    // Once we process the key down , we don't need to send the saved event again from
-    // kEventTextInputUnicodeForKeyEvent, so clear it.
-    if (currentContext && ekind == kEventRawKeyDown) {
-        QMacInputContext *context = qobject_cast<QMacInputContext*>(currentContext);
-        if (context)
-            context->setLastKeydownEvent(0);
-    }
-#endif
-    //get modifiers
-    Qt::KeyboardModifiers modifiers;
-    int qtKey;
-    QChar ourChar;
-    if (translateKeyEventInternal(er, event, &qtKey, &ourChar, &modifiers,
-                                  &handled_event) == false)
-        return handled_event;
-    QString text(ourChar);
-    /* This is actually wrong - but unfortunately it is the best that can be
-       done for now because of the Control/Meta mapping problems */
-    if (modifiers & (Qt::ControlModifier | Qt::MetaModifier)
-        && !qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta)) {
-        text = QString();
-    }
-
-
-    if (widget) {
-#ifndef QT_MAC_USE_COCOA
-        Q_UNUSED(info);
-        // Try not to call "other" event handlers if we have a popup,
-        // However, if the key has text
-        // then we should pass it along because otherwise then people
-        // can use input method stuff.
-        if (!qApp->activePopupWidget()
-                || (qApp->activePopupWidget() && !text.isEmpty())) {
-            //Find out if someone else wants the event, namely
-            //is it of use to text services? If so we won't bother
-            //with a QKeyEvent.
-            qt_mac_eat_unicode_key = false;
-            if (er)
-                CallNextEventHandler(er, event);
-            extern bool qt_mac_menubar_is_open();   
-            if (qt_mac_eat_unicode_key || qt_mac_menubar_is_open()) {
-                return true;
-            }
-        }
-#endif
-        // Try to compress key events.
-        if (!text.isEmpty() && widget->testAttribute(Qt::WA_KeyCompression)) {
-            EventTime lastTime = GetEventTime(event);
-            for (;;) {
-                EventRef releaseEvent = FindSpecificEventInQueue(GetMainEventQueue(),
-                                                                 qt_KeyEventComparatorProc,
-                                                                 (void*)kEventRawKeyUp);
-                if (!releaseEvent)
-                    break;
-                const EventTime releaseTime = GetEventTime(releaseEvent);
-                if (releaseTime < lastTime)
-                    break;
-                lastTime = releaseTime;
-
-                EventRef pressEvent = FindSpecificEventInQueue(GetMainEventQueue(),
-                                                               qt_KeyEventComparatorProc,
-                                                               (void*)kEventRawKeyDown);
-                if (!pressEvent)
-                    break;
-                const EventTime pressTime = GetEventTime(pressEvent);
-                if (pressTime < lastTime)
-                    break;
-                lastTime = pressTime;
-
-                Qt::KeyboardModifiers compressMod;
-                int compressQtKey = 0;
-                QChar compressChar;
-                if (translateKeyEventInternal(er, pressEvent,
-                                              &compressQtKey, &compressChar, &compressMod, 0)
-                    == false) {
-                    break;
-                }
-                // Copied from qapplication_x11.cpp (change both).
-
-                bool stopCompression =
-                    // 1) misc keys
-                    (compressQtKey >= Qt::Key_Escape && compressQtKey <= Qt::Key_SysReq)
-                    // 2) cursor movement
-                    || (compressQtKey >= Qt::Key_Home && compressQtKey <= Qt::Key_PageDown)
-                    // 3) extra keys
-                    || (compressQtKey >= Qt::Key_Super_L && compressQtKey <= Qt::Key_Direction_R)
-                    // 4) something that a) doesn't translate to text or b) translates
-                    //    to newline text
-                    || (compressQtKey == 0)
-                    || (compressChar == QLatin1Char('\n'))
-                    || (compressQtKey == Qt::Key_unknown);
-
-                if (compressMod == modifiers && !compressChar.isNull() && !stopCompression) {
-#ifdef DEBUG_KEY_BINDINGS
-                    qDebug("compressing away %c", compressChar.toLatin1());
-#endif
-                    text += compressChar;
-                    // Clean up
-                    RemoveEventFromQueue(GetMainEventQueue(), releaseEvent);
-                    RemoveEventFromQueue(GetMainEventQueue(), pressEvent);
-                } else {
-#ifdef DEBUG_KEY_BINDINGS
-                    qDebug("stoping compression..");
-#endif
-                    break;
-                }
-            }
-        }
-
-        // There is no way to get the scan code from carbon. But we cannot use the value 0, since
-        // it indicates that the event originates from somewhere else than the keyboard
-        UInt32 macScanCode = 1;
-        UInt32 macVirtualKey = 0;
-        GetEventParameter(event, kEventParamKeyCode, typeUInt32, 0, sizeof(macVirtualKey), 0, &macVirtualKey);
-        UInt32 macModifiers = 0;
-        GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, 0,
-                          sizeof(macModifiers), 0, &macModifiers);
-#ifdef QT_MAC_USE_COCOA
-        // The unicode characters in the range 0xF700-0xF747 are reserved
-        // by Mac OS X for transient use as keyboard function keys. We
-        // wont send 'text' for such key events. This is done to match
-        // behavior on other platforms.
-        unsigned int *unicodeKey = (unsigned int*)info;
-        if (*unicodeKey >= 0xf700 && *unicodeKey <= 0xf747)
-            text = QString();
-        bool isAccepted;
-#endif
-        handled_event = QKeyMapper::sendKeyEvent(widget, grab,
-                                                 (ekind == kEventRawKeyUp) ? QEvent::KeyRelease : QEvent::KeyPress,
-                                                 qtKey, modifiers, text, ekind == kEventRawKeyRepeat, 0,
-                                                 macScanCode, macVirtualKey, macModifiers
-#ifdef QT_MAC_USE_COCOA
-                                                 ,&isAccepted
-#endif
-                                                 );
-#ifdef QT_MAC_USE_COCOA
-        *unicodeKey = (unsigned int)isAccepted;
-#endif
-    }
-    return handled_event;
-}
-
-void
-QKeyMapperPrivate::updateKeyMap(EventHandlerCallRef, EventRef event, void *
-#if defined(QT_MAC_USE_COCOA)
-                                unicodeKey // unicode character from NSEvent (modifiers applied)
-#endif
-                                )
-{
-    UInt32 macVirtualKey = 0;
-    GetEventParameter(event, kEventParamKeyCode, typeUInt32, 0, sizeof(macVirtualKey), 0, &macVirtualKey);
-    if (updateKeyboard())
-       QKeyMapper::changeKeyboard();
-    else if (keyLayout[macVirtualKey])
-        return;
-
-    UniCharCount buffer_size = 10;
-    UniChar buffer[buffer_size];
-    keyLayout[macVirtualKey] = new KeyboardLayoutItem;
-    for (int i = 0; i < 16; ++i) {
-        UniCharCount out_buffer_size = 0;
-        keyLayout[macVirtualKey]->qtKey[i] = 0;
-#ifdef Q_WS_MAC32
-        if (keyboard_mode == UnicodeMode) {
-#endif
-            const UInt32 keyModifier = ((qt_mac_get_mac_modifiers(ModsTbl[i]) >> 8) & 0xFF);
-            OSStatus err = UCKeyTranslate(keyboard_layout_format.unicode, macVirtualKey, kUCKeyActionDown, keyModifier,
-                                          keyboard_kind, 0, &keyboard_dead, buffer_size, &out_buffer_size, buffer);
-            if (err == noErr && out_buffer_size) {
-                const QChar unicode(buffer[0]);
-                int qtkey = qt_mac_get_key(keyModifier, unicode, macVirtualKey);
-                if (qtkey == Qt::Key_unknown)
-                    qtkey = unicode.unicode();
-                keyLayout[macVirtualKey]->qtKey[i] = qtkey;
-            }
-#ifndef Q_WS_MAC32
-            else {
-                const QChar unicode(*((UniChar *)unicodeKey));
-                int qtkey = qt_mac_get_key(keyModifier, unicode, macVirtualKey);
-                if (qtkey == Qt::Key_unknown)
-                    qtkey = unicode.unicode();
-                keyLayout[macVirtualKey]->qtKey[i] = qtkey;
-            }
-#endif
-#ifdef Q_WS_MAC32            
-        } else {
-            const UInt32 keyModifier = (qt_mac_get_mac_modifiers(ModsTbl[i]));
-
-            uchar translatedChar = KeyTranslate(keyboard_layout_format.other, keyModifier | macVirtualKey, &keyboard_dead);
-            if (translatedChar) {
-                static QTextCodec *c = 0;
-                if (!c)
-                    c = QTextCodec::codecForName("Apple Roman");
-                const QChar unicode(c->toUnicode((const char *)&translatedChar, 1).at(0));
-                int qtkey = qt_mac_get_key(keyModifier, unicode, macVirtualKey);
-                if (qtkey == Qt::Key_unknown)
-                    qtkey = unicode.unicode();
-                keyLayout[macVirtualKey]->qtKey[i] = qtkey;
-            }
-        }
-#endif
-    }
-#ifdef DEBUG_KEY_MAPS
-    qDebug("updateKeyMap for virtual key = 0x%02x!", (uint)macVirtualKey);
-    for (int i = 0; i < 16; ++i) {
-        qDebug("    [%d] (%d,0x%02x,'%c')", i,
-               keyLayout[macVirtualKey]->qtKey[i],
-               keyLayout[macVirtualKey]->qtKey[i],
-               keyLayout[macVirtualKey]->qtKey[i]);
-    }
-#endif
-}
-
-bool
-QKeyMapper::sendKeyEvent(QWidget *widget, bool grab,
-                         QEvent::Type type, int code, Qt::KeyboardModifiers modifiers,
-                         const QString &text, bool autorepeat, int count,
-                         quint32 nativeScanCode, quint32 nativeVirtualKey,
-                         quint32 nativeModifiers, bool *isAccepted)
-{
-    Q_UNUSED(count);
-    if (widget && widget->isEnabled()) {
-        bool key_event = true;
-Q_UNUSED(grab);
-        if (key_event) {
-#if defined(DEBUG_KEY_BINDINGS) || defined(DEBUG_KEY_BINDINGS_MODIFIERS)
-            qDebug("KeyEvent: Sending %s to %s::%s: %s 0x%08x%s",
-                   type == QEvent::KeyRelease ? "KeyRelease" : "KeyPress",
-                   widget ? widget->metaObject()->className() : "none",
-                   widget ? widget->objectName().toLatin1().constData() : "",
-                   text.toLatin1().constData(), int(modifiers),
-                   autorepeat ? " Repeat" : "");
-#endif
-            QKeyEvent ke(type, code, modifiers,
-                           nativeScanCode, nativeVirtualKey, nativeModifiers,
-                           text, autorepeat, qMax(1, text.length()));
-            bool retMe = qt_sendSpontaneousEvent(widget,&ke);
-            if (isAccepted)
-                *isAccepted = ke.isAccepted();
-            return retMe;
-        }
-    }
-    return false;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qkeymapper_win.cpp b/src/gui/kernel/qkeymapper_win.cpp
deleted file mode 100644 (file)
index 91713b1..0000000
+++ /dev/null
@@ -1,1211 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qkeymapper_p.h"
-
-#include <qt_windows.h>
-#include <qdebug.h>
-#include <qevent_p.h>
-#include <qlocale_p.h>
-#include <qapplication_p.h>
-#include <qwidget.h>
-#include <qapplication.h>
-#include <ctype.h>
-
-QT_BEGIN_NAMESPACE
-
-// Uncommend, to show debugging information for the keymapper
-//#define DEBUG_KEYMAPPER
-
-// Implemented elsewhere
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
-
-extern Q_CORE_EXPORT QLocale qt_localeFromLCID(LCID id);
-#ifndef LANG_PASHTO
-#define LANG_PASHTO 0x63
-#endif
-#ifndef LANG_SYRIAC
-#define LANG_SYRIAC 0x5a
-#endif
-#ifndef LANG_DIVEHI
-#define LANG_DIVEHI 0x65
-#endif
-#ifndef VK_OEM_PLUS
-#define VK_OEM_PLUS 0xBB
-#endif
-#ifndef VK_OEM_3
-#define VK_OEM_3 0xC0
-#endif
-#ifndef MAPVK_VK_TO_CHAR
-#define MAPVK_VK_TO_CHAR (2)
-#endif
-
-#if defined(Q_OS_WINCE)
-bool GetKeyboardState(unsigned char* kbuffer)
-{
-    for (int i=0; i< 256; ++i)
-        kbuffer[i] = GetAsyncKeyState(i);
-    return true;
-}
-#endif
-
-// We not only need the scancode itself but also the extended bit of key messages. Thus we need
-// the additional bit when masking the scancode.
-enum { scancodeBitmask = 0x1ff };
-
-
-// Key recorder ------------------------------------------------------------------------[ start ] --
-struct KeyRecord {
-    KeyRecord(int c, int a, int s, const QString &t) : code(c), ascii(a), state(s), text(t) {}
-    KeyRecord() {}
-
-    int code;
-    int ascii;
-    int state;
-    QString text;
-};
-
-static const int QT_MAX_KEY_RECORDINGS = 64; // User has LOTS of fingers...
-struct KeyRecorder
-{
-    KeyRecorder() : nrecs(0) {}
-
-    inline KeyRecord *findKey(int code, bool remove);
-    inline void storeKey(int code, int ascii, int state, const QString& text);
-    inline void clearKeys();
-
-    int nrecs;
-    KeyRecord deleted_record; // A copy of last entry removed from records[]
-    KeyRecord records[QT_MAX_KEY_RECORDINGS];
-};
-static KeyRecorder key_recorder;
-
-KeyRecord *KeyRecorder::findKey(int code, bool remove)
-{
-    KeyRecord *result = 0;
-    for (int i = 0; i < nrecs; ++i) {
-        if (records[i].code == code) {
-            if (remove) {
-                deleted_record = records[i];
-                // Move rest down, and decrease count
-                while (i + 1 < nrecs) {
-                    records[i] = records[i + 1];
-                    ++i;
-                }
-                --nrecs;
-                result = &deleted_record;
-            } else {
-                result = &records[i];
-            }
-            break;
-        }
-    }
-    return result;
-}
-
-void KeyRecorder::storeKey(int code, int ascii, int state, const QString& text)
-{
-    Q_ASSERT_X(nrecs != QT_MAX_KEY_RECORDINGS,
-               "Internal KeyRecorder",
-               "Keyboard recorder buffer overflow, consider increasing QT_MAX_KEY_RECORDINGS");
-
-    if (nrecs == QT_MAX_KEY_RECORDINGS) {
-        qWarning("Qt: Internal keyboard buffer overflow");
-        return;
-    }
-    records[nrecs++] = KeyRecord(code,ascii,state,text);
-}
-
-void KeyRecorder::clearKeys()
-{
-    nrecs = 0;
-}
-// Key recorder --------------------------------------------------------------------------[ end ] --
-
-
-// Key translation ---------------------------------------------------------------------[ start ] --
-// Meaning of values:
-//             0 = Character output key, needs keyboard driver mapping
-//   Key_unknown = Unknown Virtual Key, no translation possible, ignore
-static const uint KeyTbl[] = { // Keyboard mapping table
-                        // Dec |  Hex | Windows Virtual key
-    Qt::Key_unknown,    //   0   0x00
-    Qt::Key_unknown,    //   1   0x01   VK_LBUTTON          | Left mouse button
-    Qt::Key_unknown,    //   2   0x02   VK_RBUTTON          | Right mouse button
-    Qt::Key_Cancel,     //   3   0x03   VK_CANCEL           | Control-Break processing
-    Qt::Key_unknown,    //   4   0x04   VK_MBUTTON          | Middle mouse button
-    Qt::Key_unknown,    //   5   0x05   VK_XBUTTON1         | X1 mouse button
-    Qt::Key_unknown,    //   6   0x06   VK_XBUTTON2         | X2 mouse button
-    Qt::Key_unknown,    //   7   0x07   -- unassigned --
-    Qt::Key_Backspace,  //   8   0x08   VK_BACK             | BackSpace key
-    Qt::Key_Tab,        //   9   0x09   VK_TAB              | Tab key
-    Qt::Key_unknown,    //  10   0x0A   -- reserved --
-    Qt::Key_unknown,    //  11   0x0B   -- reserved --
-    Qt::Key_Clear,      //  12   0x0C   VK_CLEAR            | Clear key
-    Qt::Key_Return,     //  13   0x0D   VK_RETURN           | Enter key
-    Qt::Key_unknown,    //  14   0x0E   -- unassigned --
-    Qt::Key_unknown,    //  15   0x0F   -- unassigned --
-    Qt::Key_Shift,      //  16   0x10   VK_SHIFT            | Shift key
-    Qt::Key_Control,    //  17   0x11   VK_CONTROL          | Ctrl key
-    Qt::Key_Alt,        //  18   0x12   VK_MENU             | Alt key
-    Qt::Key_Pause,      //  19   0x13   VK_PAUSE            | Pause key
-    Qt::Key_CapsLock,   //  20   0x14   VK_CAPITAL          | Caps-Lock
-    Qt::Key_unknown,    //  21   0x15   VK_KANA / VK_HANGUL | IME Kana or Hangul mode
-    Qt::Key_unknown,    //  22   0x16   -- unassigned --
-    Qt::Key_unknown,    //  23   0x17   VK_JUNJA            | IME Junja mode
-    Qt::Key_unknown,    //  24   0x18   VK_FINAL            | IME final mode
-    Qt::Key_unknown,    //  25   0x19   VK_HANJA / VK_KANJI | IME Hanja or Kanji mode
-    Qt::Key_unknown,    //  26   0x1A   -- unassigned --
-    Qt::Key_Escape,     //  27   0x1B   VK_ESCAPE           | Esc key
-    Qt::Key_unknown,    //  28   0x1C   VK_CONVERT          | IME convert
-    Qt::Key_unknown,    //  29   0x1D   VK_NONCONVERT       | IME non-convert
-    Qt::Key_unknown,    //  30   0x1E   VK_ACCEPT           | IME accept
-    Qt::Key_Mode_switch,//  31   0x1F   VK_MODECHANGE       | IME mode change request
-    Qt::Key_Space,      //  32   0x20   VK_SPACE            | Spacebar
-    Qt::Key_PageUp,     //  33   0x21   VK_PRIOR            | Page Up key
-    Qt::Key_PageDown,   //  34   0x22   VK_NEXT             | Page Down key
-    Qt::Key_End,        //  35   0x23   VK_END              | End key
-    Qt::Key_Home,       //  36   0x24   VK_HOME             | Home key
-    Qt::Key_Left,       //  37   0x25   VK_LEFT             | Left arrow key
-    Qt::Key_Up,         //  38   0x26   VK_UP               | Up arrow key
-    Qt::Key_Right,      //  39   0x27   VK_RIGHT            | Right arrow key
-    Qt::Key_Down,       //  40   0x28   VK_DOWN             | Down arrow key
-    Qt::Key_Select,     //  41   0x29   VK_SELECT           | Select key
-    Qt::Key_Printer,    //  42   0x2A   VK_PRINT            | Print key
-    Qt::Key_Execute,    //  43   0x2B   VK_EXECUTE          | Execute key
-    Qt::Key_Print,      //  44   0x2C   VK_SNAPSHOT         | Print Screen key
-    Qt::Key_Insert,     //  45   0x2D   VK_INSERT           | Ins key
-    Qt::Key_Delete,     //  46   0x2E   VK_DELETE           | Del key
-    Qt::Key_Help,       //  47   0x2F   VK_HELP             | Help key
-    0,                  //  48   0x30   (VK_0)              | 0 key
-    0,                  //  49   0x31   (VK_1)              | 1 key
-    0,                  //  50   0x32   (VK_2)              | 2 key
-    0,                  //  51   0x33   (VK_3)              | 3 key
-    0,                  //  52   0x34   (VK_4)              | 4 key
-    0,                  //  53   0x35   (VK_5)              | 5 key
-    0,                  //  54   0x36   (VK_6)              | 6 key
-    0,                  //  55   0x37   (VK_7)              | 7 key
-    0,                  //  56   0x38   (VK_8)              | 8 key
-    0,                  //  57   0x39   (VK_9)              | 9 key
-    Qt::Key_unknown,    //  58   0x3A   -- unassigned --
-    Qt::Key_unknown,    //  59   0x3B   -- unassigned --
-    Qt::Key_unknown,    //  60   0x3C   -- unassigned --
-    Qt::Key_unknown,    //  61   0x3D   -- unassigned --
-    Qt::Key_unknown,    //  62   0x3E   -- unassigned --
-    Qt::Key_unknown,    //  63   0x3F   -- unassigned --
-    Qt::Key_unknown,    //  64   0x40   -- unassigned --
-    0,                  //  65   0x41   (VK_A)              | A key
-    0,                  //  66   0x42   (VK_B)              | B key
-    0,                  //  67   0x43   (VK_C)              | C key
-    0,                  //  68   0x44   (VK_D)              | D key
-    0,                  //  69   0x45   (VK_E)              | E key
-    0,                  //  70   0x46   (VK_F)              | F key
-    0,                  //  71   0x47   (VK_G)              | G key
-    0,                  //  72   0x48   (VK_H)              | H key
-    0,                  //  73   0x49   (VK_I)              | I key
-    0,                  //  74   0x4A   (VK_J)              | J key
-    0,                  //  75   0x4B   (VK_K)              | K key
-    0,                  //  76   0x4C   (VK_L)              | L key
-    0,                  //  77   0x4D   (VK_M)              | M key
-    0,                  //  78   0x4E   (VK_N)              | N key
-    0,                  //  79   0x4F   (VK_O)              | O key
-    0,                  //  80   0x50   (VK_P)              | P key
-    0,                  //  81   0x51   (VK_Q)              | Q key
-    0,                  //  82   0x52   (VK_R)              | R key
-    0,                  //  83   0x53   (VK_S)              | S key
-    0,                  //  84   0x54   (VK_T)              | T key
-    0,                  //  85   0x55   (VK_U)              | U key
-    0,                  //  86   0x56   (VK_V)              | V key
-    0,                  //  87   0x57   (VK_W)              | W key
-    0,                  //  88   0x58   (VK_X)              | X key
-    0,                  //  89   0x59   (VK_Y)              | Y key
-    0,                  //  90   0x5A   (VK_Z)              | Z key
-    Qt::Key_Meta,       //  91   0x5B   VK_LWIN             | Left Windows  - MS Natural kbd
-    Qt::Key_Meta,       //  92   0x5C   VK_RWIN             | Right Windows - MS Natural kbd
-    Qt::Key_Menu,       //  93   0x5D   VK_APPS             | Application key-MS Natural kbd
-    Qt::Key_unknown,    //  94   0x5E   -- reserved --
-    Qt::Key_Sleep,      //  95   0x5F   VK_SLEEP
-    Qt::Key_0,          //  96   0x60   VK_NUMPAD0          | Numeric keypad 0 key
-    Qt::Key_1,          //  97   0x61   VK_NUMPAD1          | Numeric keypad 1 key
-    Qt::Key_2,          //  98   0x62   VK_NUMPAD2          | Numeric keypad 2 key
-    Qt::Key_3,          //  99   0x63   VK_NUMPAD3          | Numeric keypad 3 key
-    Qt::Key_4,          // 100   0x64   VK_NUMPAD4          | Numeric keypad 4 key
-    Qt::Key_5,          // 101   0x65   VK_NUMPAD5          | Numeric keypad 5 key
-    Qt::Key_6,          // 102   0x66   VK_NUMPAD6          | Numeric keypad 6 key
-    Qt::Key_7,          // 103   0x67   VK_NUMPAD7          | Numeric keypad 7 key
-    Qt::Key_8,          // 104   0x68   VK_NUMPAD8          | Numeric keypad 8 key
-    Qt::Key_9,          // 105   0x69   VK_NUMPAD9          | Numeric keypad 9 key
-    Qt::Key_Asterisk,   // 106   0x6A   VK_MULTIPLY         | Multiply key
-    Qt::Key_Plus,       // 107   0x6B   VK_ADD              | Add key
-    Qt::Key_Comma,      // 108   0x6C   VK_SEPARATOR        | Separator key
-    Qt::Key_Minus,      // 109   0x6D   VK_SUBTRACT         | Subtract key
-    Qt::Key_Period,     // 110   0x6E   VK_DECIMAL          | Decimal key
-    Qt::Key_Slash,      // 111   0x6F   VK_DIVIDE           | Divide key
-    Qt::Key_F1,         // 112   0x70   VK_F1               | F1 key
-    Qt::Key_F2,         // 113   0x71   VK_F2               | F2 key
-    Qt::Key_F3,         // 114   0x72   VK_F3               | F3 key
-    Qt::Key_F4,         // 115   0x73   VK_F4               | F4 key
-    Qt::Key_F5,         // 116   0x74   VK_F5               | F5 key
-    Qt::Key_F6,         // 117   0x75   VK_F6               | F6 key
-    Qt::Key_F7,         // 118   0x76   VK_F7               | F7 key
-    Qt::Key_F8,         // 119   0x77   VK_F8               | F8 key
-    Qt::Key_F9,         // 120   0x78   VK_F9               | F9 key
-    Qt::Key_F10,        // 121   0x79   VK_F10              | F10 key
-    Qt::Key_F11,        // 122   0x7A   VK_F11              | F11 key
-    Qt::Key_F12,        // 123   0x7B   VK_F12              | F12 key
-    Qt::Key_F13,        // 124   0x7C   VK_F13              | F13 key
-    Qt::Key_F14,        // 125   0x7D   VK_F14              | F14 key
-    Qt::Key_F15,        // 126   0x7E   VK_F15              | F15 key
-    Qt::Key_F16,        // 127   0x7F   VK_F16              | F16 key
-    Qt::Key_F17,        // 128   0x80   VK_F17              | F17 key
-    Qt::Key_F18,        // 129   0x81   VK_F18              | F18 key
-    Qt::Key_F19,        // 130   0x82   VK_F19              | F19 key
-    Qt::Key_F20,        // 131   0x83   VK_F20              | F20 key
-    Qt::Key_F21,        // 132   0x84   VK_F21              | F21 key
-    Qt::Key_F22,        // 133   0x85   VK_F22              | F22 key
-    Qt::Key_F23,        // 134   0x86   VK_F23              | F23 key
-    Qt::Key_F24,        // 135   0x87   VK_F24              | F24 key
-    Qt::Key_unknown,    // 136   0x88   -- unassigned --
-    Qt::Key_unknown,    // 137   0x89   -- unassigned --
-    Qt::Key_unknown,    // 138   0x8A   -- unassigned --
-    Qt::Key_unknown,    // 139   0x8B   -- unassigned --
-    Qt::Key_unknown,    // 140   0x8C   -- unassigned --
-    Qt::Key_unknown,    // 141   0x8D   -- unassigned --
-    Qt::Key_unknown,    // 142   0x8E   -- unassigned --
-    Qt::Key_unknown,    // 143   0x8F   -- unassigned --
-    Qt::Key_NumLock,    // 144   0x90   VK_NUMLOCK          | Num Lock key
-    Qt::Key_ScrollLock, // 145   0x91   VK_SCROLL           | Scroll Lock key
-                        // Fujitsu/OASYS kbd --------------------
-    0, //Qt::Key_Jisho, // 146   0x92   VK_OEM_FJ_JISHO     | 'Dictionary' key /
-                        //              VK_OEM_NEC_EQUAL  = key on numpad on NEC PC-9800 kbd
-    Qt::Key_Massyo,     // 147   0x93   VK_OEM_FJ_MASSHOU   | 'Unregister word' key
-    Qt::Key_Touroku,    // 148   0x94   VK_OEM_FJ_TOUROKU   | 'Register word' key
-    0, //Qt::Key_Oyayubi_Left,//149   0x95  VK_OEM_FJ_LOYA  | 'Left OYAYUBI' key
-    0, //Qt::Key_Oyayubi_Right,//150  0x96  VK_OEM_FJ_ROYA  | 'Right OYAYUBI' key
-    Qt::Key_unknown,    // 151   0x97   -- unassigned --
-    Qt::Key_unknown,    // 152   0x98   -- unassigned --
-    Qt::Key_unknown,    // 153   0x99   -- unassigned --
-    Qt::Key_unknown,    // 154   0x9A   -- unassigned --
-    Qt::Key_unknown,    // 155   0x9B   -- unassigned --
-    Qt::Key_unknown,    // 156   0x9C   -- unassigned --
-    Qt::Key_unknown,    // 157   0x9D   -- unassigned --
-    Qt::Key_unknown,    // 158   0x9E   -- unassigned --
-    Qt::Key_unknown,    // 159   0x9F   -- unassigned --
-    Qt::Key_Shift,      // 160   0xA0   VK_LSHIFT           | Left Shift key
-    Qt::Key_Shift,      // 161   0xA1   VK_RSHIFT           | Right Shift key
-    Qt::Key_Control,    // 162   0xA2   VK_LCONTROL         | Left Ctrl key
-    Qt::Key_Control,    // 163   0xA3   VK_RCONTROL         | Right Ctrl key
-    Qt::Key_Alt,        // 164   0xA4   VK_LMENU            | Left Menu key
-    Qt::Key_Alt,        // 165   0xA5   VK_RMENU            | Right Menu key
-    Qt::Key_Back,       // 166   0xA6   VK_BROWSER_BACK     | Browser Back key
-    Qt::Key_Forward,    // 167   0xA7   VK_BROWSER_FORWARD  | Browser Forward key
-    Qt::Key_Refresh,    // 168   0xA8   VK_BROWSER_REFRESH  | Browser Refresh key
-    Qt::Key_Stop,       // 169   0xA9   VK_BROWSER_STOP     | Browser Stop key
-    Qt::Key_Search,     // 170   0xAA   VK_BROWSER_SEARCH   | Browser Search key
-    Qt::Key_Favorites,  // 171   0xAB   VK_BROWSER_FAVORITES| Browser Favorites key
-    Qt::Key_HomePage,   // 172   0xAC   VK_BROWSER_HOME     | Browser Start and Home key
-    Qt::Key_VolumeMute, // 173   0xAD   VK_VOLUME_MUTE      | Volume Mute key
-    Qt::Key_VolumeDown, // 174   0xAE   VK_VOLUME_DOWN      | Volume Down key
-    Qt::Key_VolumeUp,   // 175   0xAF   VK_VOLUME_UP        | Volume Up key
-    Qt::Key_MediaNext,  // 176   0xB0   VK_MEDIA_NEXT_TRACK | Next Track key
-    Qt::Key_MediaPrevious, //177 0xB1   VK_MEDIA_PREV_TRACK | Previous Track key
-    Qt::Key_MediaStop,  // 178   0xB2   VK_MEDIA_STOP       | Stop Media key
-    Qt::Key_MediaPlay,  // 179   0xB3   VK_MEDIA_PLAY_PAUSE | Play/Pause Media key
-    Qt::Key_LaunchMail, // 180   0xB4   VK_LAUNCH_MAIL      | Start Mail key
-    Qt::Key_LaunchMedia,// 181   0xB5   VK_LAUNCH_MEDIA_SELECT Select Media key
-    Qt::Key_Launch0,    // 182   0xB6   VK_LAUNCH_APP1      | Start Application 1 key
-    Qt::Key_Launch1,    // 183   0xB7   VK_LAUNCH_APP2      | Start Application 2 key
-    Qt::Key_unknown,    // 184   0xB8   -- reserved --
-    Qt::Key_unknown,    // 185   0xB9   -- reserved --
-    0,                  // 186   0xBA   VK_OEM_1            | ';:' for US
-    0,                  // 187   0xBB   VK_OEM_PLUS         | '+' any country
-    0,                  // 188   0xBC   VK_OEM_COMMA        | ',' any country
-    0,                  // 189   0xBD   VK_OEM_MINUS        | '-' any country
-    0,                  // 190   0xBE   VK_OEM_PERIOD       | '.' any country
-    0,                  // 191   0xBF   VK_OEM_2            | '/?' for US
-    0,                  // 192   0xC0   VK_OEM_3            | '`~' for US
-    Qt::Key_unknown,    // 193   0xC1   -- reserved --
-    Qt::Key_unknown,    // 194   0xC2   -- reserved --
-    Qt::Key_unknown,    // 195   0xC3   -- reserved --
-    Qt::Key_unknown,    // 196   0xC4   -- reserved --
-    Qt::Key_unknown,    // 197   0xC5   -- reserved --
-    Qt::Key_unknown,    // 198   0xC6   -- reserved --
-    Qt::Key_unknown,    // 199   0xC7   -- reserved --
-    Qt::Key_unknown,    // 200   0xC8   -- reserved --
-    Qt::Key_unknown,    // 201   0xC9   -- reserved --
-    Qt::Key_unknown,    // 202   0xCA   -- reserved --
-    Qt::Key_unknown,    // 203   0xCB   -- reserved --
-    Qt::Key_unknown,    // 204   0xCC   -- reserved --
-    Qt::Key_unknown,    // 205   0xCD   -- reserved --
-    Qt::Key_unknown,    // 206   0xCE   -- reserved --
-    Qt::Key_unknown,    // 207   0xCF   -- reserved --
-    Qt::Key_unknown,    // 208   0xD0   -- reserved --
-    Qt::Key_unknown,    // 209   0xD1   -- reserved --
-    Qt::Key_unknown,    // 210   0xD2   -- reserved --
-    Qt::Key_unknown,    // 211   0xD3   -- reserved --
-    Qt::Key_unknown,    // 212   0xD4   -- reserved --
-    Qt::Key_unknown,    // 213   0xD5   -- reserved --
-    Qt::Key_unknown,    // 214   0xD6   -- reserved --
-    Qt::Key_unknown,    // 215   0xD7   -- reserved --
-    Qt::Key_unknown,    // 216   0xD8   -- unassigned --
-    Qt::Key_unknown,    // 217   0xD9   -- unassigned --
-    Qt::Key_unknown,    // 218   0xDA   -- unassigned --
-    0,                  // 219   0xDB   VK_OEM_4            | '[{' for US
-    0,                  // 220   0xDC   VK_OEM_5            | '\|' for US
-    0,                  // 221   0xDD   VK_OEM_6            | ']}' for US
-    0,                  // 222   0xDE   VK_OEM_7            | ''"' for US
-    0,                  // 223   0xDF   VK_OEM_8
-    Qt::Key_unknown,    // 224   0xE0   -- reserved --
-    Qt::Key_unknown,    // 225   0xE1   VK_OEM_AX           | 'AX' key on Japanese AX kbd
-    Qt::Key_unknown,    // 226   0xE2   VK_OEM_102          | "<>" or "\|" on RT 102-key kbd
-    Qt::Key_unknown,    // 227   0xE3   VK_ICO_HELP         | Help key on ICO
-    Qt::Key_unknown,    // 228   0xE4   VK_ICO_00           | 00 key on ICO
-    Qt::Key_unknown,    // 229   0xE5   VK_PROCESSKEY       | IME Process key
-    Qt::Key_unknown,    // 230   0xE6   VK_ICO_CLEAR        |
-    Qt::Key_unknown,    // 231   0xE7   VK_PACKET           | Unicode char as keystrokes
-    Qt::Key_unknown,    // 232   0xE8   -- unassigned --
-                        // Nokia/Ericsson definitions ---------------
-    Qt::Key_unknown,    // 233   0xE9   VK_OEM_RESET
-    Qt::Key_unknown,    // 234   0xEA   VK_OEM_JUMP
-    Qt::Key_unknown,    // 235   0xEB   VK_OEM_PA1
-    Qt::Key_unknown,    // 236   0xEC   VK_OEM_PA2
-    Qt::Key_unknown,    // 237   0xED   VK_OEM_PA3
-    Qt::Key_unknown,    // 238   0xEE   VK_OEM_WSCTRL
-    Qt::Key_unknown,    // 239   0xEF   VK_OEM_CUSEL
-    Qt::Key_unknown,    // 240   0xF0   VK_OEM_ATTN
-    Qt::Key_unknown,    // 241   0xF1   VK_OEM_FINISH
-    Qt::Key_unknown,    // 242   0xF2   VK_OEM_COPY
-    Qt::Key_unknown,    // 243   0xF3   VK_OEM_AUTO
-    Qt::Key_unknown,    // 244   0xF4   VK_OEM_ENLW
-    Qt::Key_unknown,    // 245   0xF5   VK_OEM_BACKTAB
-    Qt::Key_unknown,    // 246   0xF6   VK_ATTN             | Attn key
-    Qt::Key_unknown,    // 247   0xF7   VK_CRSEL            | CrSel key
-    Qt::Key_unknown,    // 248   0xF8   VK_EXSEL            | ExSel key
-    Qt::Key_unknown,    // 249   0xF9   VK_EREOF            | Erase EOF key
-    Qt::Key_Play,       // 250   0xFA   VK_PLAY             | Play key
-    Qt::Key_Zoom,       // 251   0xFB   VK_ZOOM             | Zoom key
-    Qt::Key_unknown,    // 252   0xFC   VK_NONAME           | Reserved
-    Qt::Key_unknown,    // 253   0xFD   VK_PA1              | PA1 key
-    Qt::Key_Clear,      // 254   0xFE   VK_OEM_CLEAR        | Clear key
-    0
-};
-
-// Possible modifier states.
-// NOTE: The order of these states match the order in QKeyMapperPrivate::updatePossibleKeyCodes()!
-static const Qt::KeyboardModifiers ModsTbl[] = {
-    Qt::NoModifier,                                             // 0
-    Qt::ShiftModifier,                                          // 1
-    Qt::ControlModifier,                                        // 2
-    Qt::ControlModifier | Qt::ShiftModifier,                    // 3
-    Qt::AltModifier,                                            // 4
-    Qt::AltModifier | Qt::ShiftModifier,                        // 5
-    Qt::AltModifier | Qt::ControlModifier,                      // 6
-    Qt::AltModifier | Qt::ShiftModifier | Qt::ControlModifier,  // 7
-    Qt::NoModifier,                                             // Fall-back to raw Key_*
-};
-
-/**
-  Remap return or action key to select key for windows mobile.
-*/
-inline int winceKeyBend(int keyCode)
-{
-#if defined(Q_OS_WINCE_WM) && defined(QT_KEYPAD_NAVIGATION)
-    // remap return or action key to select key for windows mobile.
-    // will be changed to a table remapping function in the next version (4.6/7).
-    if (keyCode == VK_RETURN && QApplication::keypadNavigationEnabled())
-        return Qt::Key_Select;
-    else
-        return KeyTbl[keyCode];
-#else
-    return KeyTbl[keyCode];
-#endif
-}
-
-#if defined(Q_OS_WINCE)
-    // Use the KeyTbl to resolve a Qt::Key out of the virtual keys.
-    // In case it is not resolvable, continue using the virtual key itself.
-
-QT_BEGIN_INCLUDE_NAMESPACE
-        
-int ToUnicode(UINT vk, int /*scancode*/, unsigned char* /*kbdBuffer*/, LPWSTR unicodeBuffer, int, int)
-{
-    QT_USE_NAMESPACE
-    QChar* buf = reinterpret_cast< QChar*>(unicodeBuffer);
-    if (KeyTbl[vk] == 0) {
-        buf[0] = vk;
-        return 1;
-    }
-    return 0;
-}
-
-int ToAscii(UINT vk, int scancode, unsigned char *kbdBuffer, LPWORD unicodeBuffer, int flag)
-{
-    return ToUnicode(vk, scancode, kbdBuffer, (LPWSTR) unicodeBuffer, 0, flag);
-
-}
-QT_END_INCLUDE_NAMESPACE
-
-#endif
-
-// Translate a VK into a Qt key code, or unicode character
-static inline int toKeyOrUnicode(int vk, int scancode, unsigned char *kbdBuffer, bool *isDeadkey = 0)
-{
-    Q_ASSERT(vk > 0 && vk < 256);
-    int code = 0;
-    QChar unicodeBuffer[5];
-    int res = ToUnicode(vk, scancode, kbdBuffer, reinterpret_cast<LPWSTR>(unicodeBuffer), 5, 0);
-    // When Ctrl modifier is used ToUnicode does not return correct values. In order to assign the
-    // right key the control modifier is removed for just that function if the previous call failed.
-    if (res == 0 && kbdBuffer[VK_CONTROL]) {
-        const unsigned char controlState = kbdBuffer[VK_CONTROL];
-        kbdBuffer[VK_CONTROL] = 0;
-        res = ToUnicode(vk, scancode, kbdBuffer, reinterpret_cast<LPWSTR>(unicodeBuffer), 5, 0);
-        kbdBuffer[VK_CONTROL] = controlState;
-    }
-    if (res)
-        code = unicodeBuffer[0].toUpper().unicode();
-
-    // Qt::Key_*'s are not encoded below 0x20, so try again, and DEL keys (0x7f) is encoded with a
-    // proper Qt::Key_ code
-    if (code < 0x20 || code == 0x7f) // Handles res==0 too
-        code = winceKeyBend(vk);
-
-    if (isDeadkey)
-        *isDeadkey = (res == -1);
-
-    return code == Qt::Key_unknown ? 0 : code;
-}
-
-Q_GUI_EXPORT int qt_translateKeyCode(int vk)
-{
-    int code = winceKeyBend((vk < 0 || vk > 255) ? 0 : vk);
-    return code == Qt::Key_unknown ? 0 : code;
-}
-
-static inline int asciiToKeycode(char a, int state)
-{
-    if (a >= 'a' && a <= 'z')
-        a = toupper(a);
-    if ((state & Qt::ControlModifier) != 0) {
-        if (a >= 0 && a <= 31)              // Ctrl+@..Ctrl+A..CTRL+Z..Ctrl+_
-            a += '@';                       // to @..A..Z.._
-    }
-    return a & 0xff;
-}
-
-static inline bool isModifierKey(int code)
-{
-    return (code >= Qt::Key_Shift) && (code <= Qt::Key_ScrollLock);
-}
-// Key translation -----------------------------------------------------------------------[ end ]---
-
-
-static void qt_show_system_menu(QWidget* tlw)
-{
-    Q_ASSERT(tlw->testAttribute(Qt::WA_WState_Created));
-    HMENU menu = GetSystemMenu(tlw->internalWinId(), FALSE);
-    if (!menu)
-        return; // no menu for this window
-
-#define enabled (MF_BYCOMMAND | MF_ENABLED)
-#define disabled (MF_BYCOMMAND | MF_GRAYED)
-
-#ifndef Q_OS_WINCE
-    EnableMenuItem(menu, SC_MINIMIZE, (tlw->windowFlags() & Qt::WindowMinimizeButtonHint)?enabled:disabled);
-    bool maximized = IsZoomed(tlw->internalWinId());
-
-    EnableMenuItem(menu, SC_MAXIMIZE, ! (tlw->windowFlags() & Qt::WindowMaximizeButtonHint) || maximized?disabled:enabled);
-    EnableMenuItem(menu, SC_RESTORE, maximized?enabled:disabled);
-
-    // We should _not_ check with the setFixedSize(x,y) case here, since Windows is not able to check
-    // this and our menu here would be out-of-sync with the menu produced by mouse-click on the
-    // System Menu, or right-click on the title bar.
-    EnableMenuItem(menu, SC_SIZE, (tlw->windowFlags() & Qt::MSWindowsFixedSizeDialogHint) || maximized?disabled:enabled);
-    EnableMenuItem(menu, SC_MOVE, maximized?disabled:enabled);
-    EnableMenuItem(menu, SC_CLOSE, enabled);
-    // Set bold on close menu item
-    MENUITEMINFO closeItem;
-    closeItem.cbSize = sizeof(MENUITEMINFO);
-    closeItem.fMask = MIIM_STATE;
-    closeItem.fState = MFS_DEFAULT;
-    SetMenuItemInfo(menu, SC_CLOSE, FALSE, &closeItem);
-#endif
-
-#undef enabled
-#undef disabled
-    int ret = TrackPopupMenuEx(menu,
-                               TPM_LEFTALIGN  | TPM_TOPALIGN | TPM_NONOTIFY | TPM_RETURNCMD,
-                               tlw->geometry().x(), tlw->geometry().y(),
-                               tlw->internalWinId(),
-                               0);
-    if (ret)
-        QtWndProc(tlw->internalWinId(), WM_SYSCOMMAND, ret, 0);
-}
-
-
-// QETWidget class is only for accessing the sendSpontaneousEvent function in QApplication
-class QETWidget : public QWidget {
-public:
-    static bool sendSpontaneousEvent(QObject *r, QEvent *e)
-    { return QApplication::sendSpontaneousEvent(r, e); }
-};
-
-
-// Keyboard map private ----------------------------------------------------------------[ start ]---
-
-/*
-    \internal
-    A Windows KeyboardLayoutItem has 8 possible states:
-        1. Unmodified
-        2. Shift
-        3. Control
-        4. Control + Shift
-        5. Alt
-        6. Alt + Shift
-        7. Alt + Control
-        8. Alt + Control + Shift
-*/
-struct KeyboardLayoutItem {
-    bool dirty;
-    quint8 deadkeys;
-    quint32 qtKey[9]; // Can by any Qt::Key_<foo>, or unicode character
-};
-
-QKeyMapperPrivate::QKeyMapperPrivate()
-{
-    memset(keyLayout, 0, sizeof(keyLayout));
-}
-
-QKeyMapperPrivate::~QKeyMapperPrivate()
-{
-    deleteLayouts();
-}
-
-void QKeyMapperPrivate::deleteLayouts()
-{
-    for (int i = 0; i < 255; ++i) {
-        if (keyLayout[i]) {
-            delete keyLayout[i];
-            keyLayout[i] = 0;
-        }
-    }
-}
-
-void QKeyMapperPrivate::clearMappings()
-{
-    deleteLayouts();
-
-    /* MAKELCID()'s first argument is a WORD, and GetKeyboardLayout()
-     * returns a DWORD. */
-
-    LCID newLCID = MAKELCID((quintptr)GetKeyboardLayout(0), SORT_DEFAULT);
-//    keyboardInputLocale = qt_localeFromLCID(newLCID);
-
-    bool bidi = false;
-    wchar_t LCIDFontSig[16];
-    if (GetLocaleInfo(newLCID, LOCALE_FONTSIGNATURE, LCIDFontSig, sizeof(LCIDFontSig) / sizeof(wchar_t))
-        && (LCIDFontSig[7] & (wchar_t)0x0800))
-        bidi = true;
-
-    keyboardInputDirection = bidi ? Qt::RightToLeft : Qt::LeftToRight;
-}
-
-void QKeyMapperPrivate::clearRecordedKeys()
-{
-    key_recorder.clearKeys();
-}
-
-
-inline void setKbdState(unsigned char *kbd, bool shift, bool ctrl, bool alt)
-{
-    kbd[VK_LSHIFT  ] = (shift ? 0x80 : 0);
-    kbd[VK_SHIFT   ] = (shift ? 0x80 : 0);
-    kbd[VK_LCONTROL] = (ctrl ? 0x80 : 0);
-    kbd[VK_CONTROL ] = (ctrl ? 0x80 : 0);
-    kbd[VK_RMENU   ] = (alt ? 0x80 : 0);
-    kbd[VK_MENU    ] = (alt ? 0x80 : 0);
-}
-
-void QKeyMapperPrivate::updateKeyMap(const MSG &msg)
-{
-    unsigned char kbdBuffer[256]; // Will hold the complete keyboard state
-    GetKeyboardState(kbdBuffer);
-    const quint32 scancode = (msg.lParam >> 16) & scancodeBitmask;
-    updatePossibleKeyCodes(kbdBuffer, scancode, msg.wParam);
-}
-
-void QKeyMapperPrivate::updatePossibleKeyCodes(unsigned char *kbdBuffer, quint32 scancode,
-                                               quint32 vk_key)
-{
-    if (!vk_key || (keyLayout[vk_key] && !keyLayout[vk_key]->dirty))
-        return;
-
-    if (!keyLayout[vk_key])
-        keyLayout[vk_key] = new KeyboardLayoutItem;
-
-    // Copy keyboard state, so we can modify and query output for each possible permutation
-    unsigned char buffer[256];
-    memcpy(buffer, kbdBuffer, sizeof(buffer));
-    // Always 0, as Windows doesn't treat these as modifiers;
-    buffer[VK_LWIN    ] = 0;
-    buffer[VK_RWIN    ] = 0;
-    buffer[VK_CAPITAL ] = 0;
-    buffer[VK_NUMLOCK ] = 0;
-    buffer[VK_SCROLL  ] = 0;
-    // Always 0, since we'll only change the other versions
-    buffer[VK_RSHIFT  ] = 0;
-    buffer[VK_RCONTROL] = 0;
-    buffer[VK_LMENU   ] = 0; // Use right Alt, since left Ctrl + right Alt is considered AltGraph
-
-    bool isDeadKey = false;
-    keyLayout[vk_key]->deadkeys = 0;
-    keyLayout[vk_key]->dirty = false;
-    setKbdState(buffer, false, false, false);
-    keyLayout[vk_key]->qtKey[0] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
-    keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x01 : 0;
-    setKbdState(buffer, true, false, false);
-    keyLayout[vk_key]->qtKey[1] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
-    keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x02 : 0;
-    setKbdState(buffer, false, true, false);
-    keyLayout[vk_key]->qtKey[2] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
-    keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x04 : 0;
-    setKbdState(buffer, true, true, false);
-    keyLayout[vk_key]->qtKey[3] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
-    keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x08 : 0;
-    setKbdState(buffer, false, false, true);
-    keyLayout[vk_key]->qtKey[4] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
-    keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x10 : 0;
-    setKbdState(buffer, true, false, true);
-    keyLayout[vk_key]->qtKey[5] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
-    keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x20 : 0;
-    setKbdState(buffer, false, true, true);
-    keyLayout[vk_key]->qtKey[6] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
-    keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x40 : 0;
-    setKbdState(buffer, true, true, true);
-    keyLayout[vk_key]->qtKey[7] = toKeyOrUnicode(vk_key, scancode, buffer, &isDeadKey);
-    keyLayout[vk_key]->deadkeys |= isDeadKey ? 0x80 : 0;
-    // Add a fall back key for layouts which don't do composition and show non-latin1 characters
-    int fallbackKey = winceKeyBend(vk_key);
-    if (!fallbackKey || fallbackKey == Qt::Key_unknown) {
-        fallbackKey = 0;
-        if (vk_key != keyLayout[vk_key]->qtKey[0] && vk_key < 0x5B && vk_key > 0x2F)
-            fallbackKey = vk_key;
-    }
-    keyLayout[vk_key]->qtKey[8] = fallbackKey;
-
-    // If this vk_key makes a dead key with any combination of modifiers
-    if (keyLayout[vk_key]->deadkeys) {
-        // Push a Space, then the original key through the low-level ToAscii functions.
-        // We do this because these functions (ToAscii / ToUnicode) will alter the internal state of
-        // the keyboard driver By doing the following, we set the keyboard driver state back to what
-        // it was before we wrecked it with the code above.
-        // We need to push the space with an empty keystate map, since the driver checks the map for
-        // transitions in modifiers, so this helps us capture all possible deadkeys.
-        unsigned char emptyBuffer[256];
-        memset(emptyBuffer, 0, sizeof(emptyBuffer));
-        ::ToAscii(VK_SPACE, 0, emptyBuffer, reinterpret_cast<LPWORD>(&buffer), 0);
-        ::ToAscii(vk_key, scancode, kbdBuffer, reinterpret_cast<LPWORD>(&buffer), 0);
-    }
-
-#ifdef DEBUG_KEYMAPPER
-    qDebug("updatePossibleKeyCodes for virtual key = 0x%02x!", vk_key);
-    for (int i = 0; i < 9; ++i) {
-        qDebug("    [%d] (%d,0x%02x,'%c')  %s", i,
-               keyLayout[vk_key]->qtKey[i],
-               keyLayout[vk_key]->qtKey[i],
-               keyLayout[vk_key]->qtKey[i] ? keyLayout[vk_key]->qtKey[i] : 0x03,
-               keyLayout[vk_key]->deadkeys & (1<<i) ? "deadkey" : "");
-    }
-#endif // DEBUG_KEYMAPPER
-}
-
-bool QKeyMapperPrivate::isADeadKey(unsigned int vk_key, unsigned int modifiers)
-{
-    if (keyLayout && (vk_key < 256) && keyLayout[vk_key]) {
-        for(register int i = 0; i < 9; ++i) {
-            if (uint(ModsTbl[i]) == modifiers)
-                return bool(keyLayout[vk_key]->deadkeys & 1<<i);
-        }
-    }
-    return false;
-}
-
-extern bool qt_use_rtl_extensions;
-
-QList<int> QKeyMapperPrivate::possibleKeys(QKeyEvent *e)
-{
-    QList<int> result;
-    const quint32 nativeVirtualKey = e->nativeVirtualKey();
-    if (nativeVirtualKey > 255)
-        return result;
-
-    KeyboardLayoutItem *kbItem = keyLayout[nativeVirtualKey];
-    if(!kbItem)
-        return result;
-
-    quint32 baseKey = kbItem->qtKey[0];
-    Qt::KeyboardModifiers keyMods = e->modifiers();
-    if (baseKey == Qt::Key_Return && (e->nativeModifiers() & ExtendedKey)) {
-        result << int(Qt::Key_Enter + keyMods);
-        return result;
-    }
-    result << int(baseKey + keyMods); // The base key is _always_ valid, of course
-
-    for(int i = 1; i < 9; ++i) {
-        Qt::KeyboardModifiers neededMods = ModsTbl[i];
-        quint32 key = kbItem->qtKey[i];
-        if (key && key != baseKey && ((keyMods & neededMods) == neededMods))
-            result << int(key + (keyMods & ~neededMods));
-    }
-
-    return result;
-}
-
-bool QKeyMapperPrivate::translateKeyEvent(QWidget *widget, const MSG &msg, bool grab)
-{
-    Q_Q(QKeyMapper);
-    Q_UNUSED(q); // Strange, but the compiler complains on q not being referenced, even if it is..
-    bool k0 = false;
-    bool k1 = false;
-    int  msgType = msg.message;
-    // WM_(IME_)CHAR messages already contain the character in question so there is
-    // no need to fiddle with our key map. In any other case add this key to the
-    // keymap if it is not present yet.
-    if (msg.message != WM_CHAR && msg.message != WM_IME_CHAR)
-        updateKeyMap(msg);
-
-    const quint32 scancode = (msg.lParam >> 16) & scancodeBitmask;
-    const quint32 vk_key = msg.wParam;
-
-    quint32 nModifiers = 0;
-
-#if defined(Q_OS_WINCE)
-        nModifiers |= (GetKeyState(VK_SHIFT  ) < 0 ? ShiftAny : 0);
-        nModifiers |= (GetKeyState(VK_CONTROL) < 0 ? ControlAny : 0);
-        nModifiers |= (GetKeyState(VK_MENU   ) < 0 ? AltAny : 0);
-        nModifiers |= (GetKeyState(VK_LWIN   ) < 0 ? MetaLeft : 0);
-        nModifiers |= (GetKeyState(VK_RWIN   ) < 0 ? MetaRight : 0);
-#else
-        // Map native modifiers to some bit representation
-        nModifiers |= (GetKeyState(VK_LSHIFT  ) & 0x80 ? ShiftLeft : 0);
-        nModifiers |= (GetKeyState(VK_RSHIFT  ) & 0x80 ? ShiftRight : 0);
-        nModifiers |= (GetKeyState(VK_LCONTROL) & 0x80 ? ControlLeft : 0);
-        nModifiers |= (GetKeyState(VK_RCONTROL) & 0x80 ? ControlRight : 0);
-        nModifiers |= (GetKeyState(VK_LMENU   ) & 0x80 ? AltLeft : 0);
-        nModifiers |= (GetKeyState(VK_RMENU   ) & 0x80 ? AltRight : 0);
-        nModifiers |= (GetKeyState(VK_LWIN    ) & 0x80 ? MetaLeft : 0);
-        nModifiers |= (GetKeyState(VK_RWIN    ) & 0x80 ? MetaRight : 0);
-        // Add Lock keys to the same bits
-        nModifiers |= (GetKeyState(VK_CAPITAL ) & 0x01 ? CapsLock : 0);
-        nModifiers |= (GetKeyState(VK_NUMLOCK ) & 0x01 ? NumLock : 0);
-        nModifiers |= (GetKeyState(VK_SCROLL  ) & 0x01 ? ScrollLock : 0);
-#endif // Q_OS_WINCE
-
-    if (msg.lParam & ExtendedKey)
-        nModifiers |= msg.lParam & ExtendedKey;
-
-    // Get the modifier states (may be altered later, depending on key code)
-    int state = 0;
-    state |= (nModifiers & ShiftAny ? int(Qt::ShiftModifier) : 0);
-    state |= (nModifiers & ControlAny ? int(Qt::ControlModifier) : 0);
-    state |= (nModifiers & AltAny ? int(Qt::AltModifier) : 0);
-    state |= (nModifiers & MetaAny ? int(Qt::MetaModifier) : 0);
-
-    // A multi-character key not found by our look-ahead
-    if (msgType == WM_CHAR) {
-        QString s;
-        QChar ch = QChar((ushort)msg.wParam);
-        if (!ch.isNull())
-            s += ch;
-
-        k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, 0, Qt::KeyboardModifier(state), s, false, 0, scancode, vk_key, nModifiers);
-        k1 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, 0, Qt::KeyboardModifier(state), s, false, 0, scancode, vk_key, nModifiers);
-    }
-
-    // Input method characters not found by our look-ahead
-    else if (msgType == WM_IME_CHAR) {
-        QString s;
-        QChar ch = QChar((ushort)msg.wParam);
-        if (!ch.isNull())
-            s += ch;
-
-        k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, 0, Qt::KeyboardModifier(state), s, false, 0, scancode, vk_key, nModifiers);
-        k1 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, 0, Qt::KeyboardModifier(state), s, false, 0, scancode, vk_key, nModifiers);
-    }
-
-    else {
-        // handle Directionality changes (BiDi) with RTL extensions
-        if (qt_use_rtl_extensions) {
-            static int dirStatus = 0;
-            if (!dirStatus && state == Qt::ControlModifier
-                && msg.wParam == VK_CONTROL
-                && msgType == WM_KEYDOWN) {
-                if (GetKeyState(VK_LCONTROL) < 0)
-                    dirStatus = VK_LCONTROL;
-                else if (GetKeyState(VK_RCONTROL) < 0)
-                    dirStatus = VK_RCONTROL;
-            } else if (dirStatus) {
-                if (msgType == WM_KEYDOWN) {
-                    if (msg.wParam == VK_SHIFT) {
-                        if (dirStatus == VK_LCONTROL && GetKeyState(VK_LSHIFT) < 0)
-                            dirStatus = VK_LSHIFT;
-                        else if (dirStatus == VK_RCONTROL && GetKeyState(VK_RSHIFT) < 0)
-                            dirStatus = VK_RSHIFT;
-                    } else {
-                        dirStatus = 0;
-                    }
-                } else if (msgType == WM_KEYUP) {
-                    if (dirStatus == VK_LSHIFT
-                        && ((msg.wParam == VK_SHIFT && GetKeyState(VK_LCONTROL))
-                        || (msg.wParam == VK_CONTROL && GetKeyState(VK_LSHIFT)))) {
-                            k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, Qt::Key_Direction_L, 0,
-                                                 QString(), false, 0,
-                                                 scancode, msg.wParam, nModifiers);
-                            k1 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, Qt::Key_Direction_L, 0,
-                                                 QString(), false, 0,
-                                                 scancode, msg.wParam, nModifiers);
-                            dirStatus = 0;
-                        } else if (dirStatus == VK_RSHIFT
-                                   && ( (msg.wParam == VK_SHIFT && GetKeyState(VK_RCONTROL))
-                                   || (msg.wParam == VK_CONTROL && GetKeyState(VK_RSHIFT)))) {
-                                k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, Qt::Key_Direction_R,
-                                                     0, QString(), false, 0,
-                                                     scancode, msg.wParam, nModifiers);
-                                k1 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, Qt::Key_Direction_R,
-                                                     0, QString(), false, 0,
-                                                     scancode, msg.wParam, nModifiers);
-                                dirStatus = 0;
-                            } else {
-                                dirStatus = 0;
-                            }
-                } else {
-                    dirStatus = 0;
-                }
-            }
-        }
-
-        // IME will process these keys, so simply return
-        if(msg.wParam == VK_PROCESSKEY)
-            return true;
-
-        // Ignore invalid virtual keycodes (see bugs 127424, QTBUG-3630)
-        if (msg.wParam == 0 || msg.wParam == 0xFF)
-            return true;
-
-        // Translate VK_* (native) -> Key_* (Qt) keys
-        int modifiersIndex = 0;
-        modifiersIndex |= (nModifiers & ShiftAny ? 0x1 : 0);
-        modifiersIndex |= (nModifiers & ControlAny ? 0x2 : 0);
-        modifiersIndex |= (nModifiers & AltAny ? 0x4 : 0);
-
-        int code = keyLayout[vk_key]->qtKey[modifiersIndex];
-
-        // Invert state logic:
-        // If the key actually pressed is a modifier key, then we remove its modifier key from the
-        // state, since a modifier-key can't have itself as a modifier
-        if (code == Qt::Key_Control)
-            state = state ^ Qt::ControlModifier;
-        else if (code == Qt::Key_Shift)
-            state = state ^ Qt::ShiftModifier;
-        else if (code == Qt::Key_Alt)
-            state = state ^ Qt::AltModifier;
-
-        // If the bit 24 of lParm is set you received a enter,
-        // otherwise a Return. (This is the extended key bit)
-        if ((code == Qt::Key_Return) && (msg.lParam & 0x1000000))
-            code = Qt::Key_Enter;
-
-        // All cursor keys without extended bit
-        if (!(msg.lParam & 0x1000000)) {
-            switch (code) {
-            case Qt::Key_Left:
-            case Qt::Key_Right:
-            case Qt::Key_Up:
-            case Qt::Key_Down:
-            case Qt::Key_PageUp:
-            case Qt::Key_PageDown:
-            case Qt::Key_Home:
-            case Qt::Key_End:
-            case Qt::Key_Insert:
-            case Qt::Key_Delete:
-            case Qt::Key_Asterisk:
-            case Qt::Key_Plus:
-            case Qt::Key_Minus:
-            case Qt::Key_Period:
-            case Qt::Key_Comma:
-            case Qt::Key_0:
-            case Qt::Key_1:
-            case Qt::Key_2:
-            case Qt::Key_3:
-            case Qt::Key_4:
-            case Qt::Key_5:
-            case Qt::Key_6:
-            case Qt::Key_7:
-            case Qt::Key_8:
-            case Qt::Key_9:
-                state |= ((msg.wParam >= '0' && msg.wParam <= '9')
-                         || (msg.wParam >= VK_OEM_PLUS && msg.wParam <= VK_OEM_3))
-                            ? 0 : int(Qt::KeypadModifier);
-            default:
-                if ((uint)msg.lParam == 0x004c0001 || (uint)msg.lParam == 0xc04c0001)
-                    state |= Qt::KeypadModifier;
-                break;
-            }
-        }
-        // Other keys with with extended bit
-        else {
-            switch (code) {
-            case Qt::Key_Enter:
-            case Qt::Key_Slash:
-            case Qt::Key_NumLock:
-                state |= Qt::KeypadModifier;
-            default:
-                break;
-            }
-        }
-
-        // KEYDOWN ---------------------------------------------------------------------------------
-        if (msgType == WM_KEYDOWN || msgType == WM_IME_KEYDOWN || msgType == WM_SYSKEYDOWN) {
-            // Get the last record of this key press, so we can validate the current state
-            // The record is not removed from the list
-            KeyRecord *rec = key_recorder.findKey(msg.wParam, false);
-
-            // If rec's state doesn't match the current state, something has changed behind our back
-            // (Consumed by modal widget is one possibility) So, remove the record from the list
-            // This will stop the auto-repeat of the key, should a modifier change, for example
-            if (rec && rec->state != state) {
-                key_recorder.findKey(msg.wParam, true);
-                rec = 0;
-            }
-
-            // Find unicode character from Windows Message Queue
-            MSG wm_char;
-            UINT charType = (msgType == WM_KEYDOWN
-                                ? WM_CHAR
-                                : msgType == WM_IME_KEYDOWN ? WM_IME_CHAR : WM_SYSCHAR);
-
-            QChar uch;
-            if (PeekMessage(&wm_char, 0, charType, charType, PM_REMOVE)) {
-                // Found a ?_CHAR
-                uch = QChar((ushort)wm_char.wParam);
-                if (msgType == WM_SYSKEYDOWN && uch.isLetter() && (msg.lParam & KF_ALTDOWN))
-                    uch = uch.toLower(); // (See doc of WM_SYSCHAR) Alt-letter
-                if (!code && !uch.row())
-                    code = asciiToKeycode(uch.cell(), state);
-            }
-
-            // Special handling for the WM_IME_KEYDOWN message. Microsoft IME (Korean) will not 
-            // generate a WM_IME_CHAR message corresponding to this message. We might get wrong
-            // results, if we map this virtual key-code directly (for eg '?' US layouts). So try
-            // to find the correct key using the current message parameters & keyboard state.
-            if (uch.isNull() && msgType == WM_IME_KEYDOWN) {
-                BYTE keyState[256];
-                wchar_t newKey[3] = {0};
-                GetKeyboardState(keyState);
-                int val = ToUnicode(vk_key, scancode, keyState, newKey, 2,  0);
-                if (val == 1) {
-                    uch = QChar(newKey[0]);
-                } else {
-                    // If we are still not able to find a unicode key, pass the WM_IME_KEYDOWN 
-                    // message to DefWindowProc() for generating a proper WM_KEYDOWN.
-                    return false;
-                }
-            }
-
-            // If no ?_CHAR was found in the queue; deduct character from the ?_KEYDOWN parameters
-            if (uch.isNull()) {
-                if (msg.wParam == VK_DELETE) {
-                    uch = QChar(QLatin1Char(0x7f)); // Windows doesn't know this one.
-                } else {
-                    if (msgType != WM_SYSKEYDOWN || !code) {
-                        UINT map = MapVirtualKey(msg.wParam, 2);
-                        // If the high bit of the return value is set, it's a deadkey
-                        if (!(map & 0x80000000))
-                            uch = QChar((ushort)map);
-                    }
-                }
-                if (!code && !uch.row())
-                    code = asciiToKeycode(uch.cell(), state);
-            }
-
-            // Special handling of global Windows hotkeys
-            if (state == Qt::AltModifier) {
-                switch (code) {
-                case Qt::Key_Escape:
-                case Qt::Key_Tab:
-                case Qt::Key_Enter:
-                case Qt::Key_F4:
-                    return false; // Send the event on to Windows
-                case Qt::Key_Space:
-                    // do not pass this key to windows, we will process it ourselves
-                    qt_show_system_menu(widget->window());
-                    return true;
-                default:
-                    break;
-                }
-            }
-
-            // Map SHIFT + Tab to SHIFT + BackTab, QShortcutMap knows about this translation
-            if (code == Qt::Key_Tab && (state & Qt::ShiftModifier) == Qt::ShiftModifier)
-                code = Qt::Key_Backtab;
-
-            // If we have a record, it means that the key is already pressed, the state is the same
-            // so, we have an auto-repeating key
-            if (rec) {
-                if (code < Qt::Key_Shift || code > Qt::Key_ScrollLock) {
-                    k0 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, code,
-                                         Qt::KeyboardModifier(state), rec->text, true, 0,
-                                         scancode, msg.wParam, nModifiers);
-                    k1 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, code,
-                                         Qt::KeyboardModifier(state), rec->text, true, 0,
-                                         scancode, msg.wParam, nModifiers);
-                }
-            }
-            // No record of the key being previous pressed, so we now send a QEvent::KeyPress event,
-            // and store the key data into our records.
-            else {
-                QString text;
-                if (!uch.isNull())
-                    text += uch;
-                char a = uch.row() ? 0 : uch.cell();
-                key_recorder.storeKey(msg.wParam, a, state, text);
-                k0 = q->sendKeyEvent(widget, grab, QEvent::KeyPress, code, Qt::KeyboardModifier(state),
-                                     text, false, 0, scancode, msg.wParam, nModifiers);
-
-                bool store = true;
-                // Alt+<alphanumerical> go to the Win32 menu system if unhandled by Qt
-#if !defined(Q_OS_WINCE)
-                if (msgType == WM_SYSKEYDOWN && !k0 && a) {
-                    HWND parent = GetParent(widget->internalWinId());
-                    while (parent) {
-                        if (GetMenu(parent)) {
-                            SendMessage(parent, WM_SYSCOMMAND, SC_KEYMENU, a);
-                            store = false;
-                            k0 = true;
-                            break;
-                        }
-                        parent = GetParent(parent);
-                    }
-                }
-#endif
-                if (!store)
-                    key_recorder.findKey(msg.wParam, true);
-            }
-        }
-
-        // KEYUP -----------------------------------------------------------------------------------
-        else {
-            // Try to locate the key in our records, and remove it if it exists.
-            // The key may not be in our records if, for example, the down event was handled by
-            // win32 natively, or our window gets focus while a key is already press, but now gets
-            // the key release event.
-            KeyRecord* rec = key_recorder.findKey(msg.wParam, true);
-            if (!rec && !(code == Qt::Key_Shift
-                          || code == Qt::Key_Control
-                          || code == Qt::Key_Meta
-                          || code == Qt::Key_Alt)) {
-                // Someone ate the key down event
-            } else {
-                if (!code)
-                    code = asciiToKeycode(rec->ascii ? rec->ascii : msg.wParam, state);
-
-                // Map SHIFT + Tab to SHIFT + BackTab, QShortcutMap knows about this translation
-                if (code == Qt::Key_Tab && (state & Qt::ShiftModifier) == Qt::ShiftModifier)
-                    code = Qt::Key_Backtab;
-
-                k0 = q->sendKeyEvent(widget, grab, QEvent::KeyRelease, code, Qt::KeyboardModifier(state),
-                                     (rec ? rec->text : QString()), false, 0, scancode, msg.wParam, nModifiers);
-
-                // don't pass Alt to Windows unless we are embedded in a non-Qt window
-#if !defined(Q_OS_WINCE)
-                if (code == Qt::Key_Alt) {
-                    k0 = true;
-                    HWND parent = GetParent(widget->internalWinId());
-                    while (parent) {
-                        if (!QWidget::find(parent) && GetMenu(parent)) {
-                            k0 = false;
-                            break;
-                        }
-                        parent = GetParent(parent);
-                    }
-                }
-#endif
-            }
-        }
-    }
-
-    // Return true, if a QKeyEvent was sent to a widget
-    return k0 || k1;
-}
-
-
-// QKeyMapper (Windows) implementation -------------------------------------------------[ start ]---
-
-bool QKeyMapper::sendKeyEvent(QWidget *widget, bool grab,
-                              QEvent::Type type, int code, Qt::KeyboardModifiers modifiers,
-                              const QString &text, bool autorepeat, int count,
-                              quint32 nativeScanCode, quint32 nativeVirtualKey, quint32 nativeModifiers,
-                              bool *)
-{
-#if defined(Q_OS_WINCE)
-    Q_UNUSED(grab);
-#endif
-    Q_UNUSED(count);
-    Q_UNUSED(grab);
-    if (!widget->isEnabled())
-        return false;
-
-    QKeyEvent e(type, code, modifiers,
-                  nativeScanCode, nativeVirtualKey, nativeModifiers,
-                  text, autorepeat, qMax(1, int(text.length())));
-    QETWidget::sendSpontaneousEvent(widget, &e);
-
-    if (!isModifierKey(code)
-        && modifiers == Qt::AltModifier
-        && ((code >= Qt::Key_A && code <= Qt::Key_Z) || (code >= Qt::Key_0 && code <= Qt::Key_9))
-        && type == QEvent::KeyPress
-        && !e.isAccepted())
-        QApplication::beep();           // Emulate windows behavior
-
-    return e.isAccepted();
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qmacdefines_mac.h b/src/gui/kernel/qmacdefines_mac.h
deleted file mode 100644 (file)
index 7398878..0000000
+++ /dev/null
@@ -1,179 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-/*
- *  qmacdefines_mac_p.h
- *  All the defines you'll ever need for Qt/Mac :-)
- */
-
-/* This is just many defines. Therefore it doesn't need things like:
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-Yes, it is an informative comment ;-)
-*/
-
-#include <QtCore/qglobal.h>
-
-#ifdef qDebug
-#  define old_qDebug qDebug
-#  undef qDebug
-#endif
-
-#ifdef __LP64__
-typedef signed int OSStatus;
-#else
-typedef signed long OSStatus;
-#endif
-
-#ifdef __OBJC__
-#    ifdef slots
-#      define old_slots slots
-#      undef slots
-#    endif
-#include <Cocoa/Cocoa.h>
-#    ifdef old_slots
-#      undef slots
-#      define slots
-#      undef old_slots
-#    endif
-#endif
-#ifdef QT_MAC_USE_COCOA
-    typedef struct OpaqueEventHandlerCallRef * EventHandlerCallRef;
-    typedef struct OpaqueEventRef * EventRef;
-    typedef struct OpaqueMenuRef * MenuRef;
-    typedef struct OpaquePasteboardRef* PasteboardRef;
-    typedef struct OpaqueRgnHandle * RgnHandle;
-    typedef const struct __HIShape *HIShapeRef;
-    typedef struct __HIShape *HIMutableShapeRef;
-    typedef struct CGRect CGRect;
-    typedef struct CGImage *CGImageRef;
-    typedef struct CGContext *CGContextRef;
-    typedef struct GDevice * GDPtr;
-    typedef GDPtr * GDHandle;
-    typedef struct OpaqueIconRef * IconRef;
-#   ifdef __OBJC__
-        typedef NSWindow* OSWindowRef;
-        typedef NSView *OSViewRef;
-        typedef NSMenu *OSMenuRef;
-        typedef NSEvent *OSEventRef;
-#   else
-        typedef void *OSWindowRef;
-        typedef void *OSViewRef;
-        typedef void *OSMenuRef;
-        typedef void *OSEventRef;
-#   endif
-#else  // Carbon
-    typedef struct OpaqueEventHandlerCallRef * EventHandlerCallRef;
-    typedef struct OpaqueEventRef * EventRef;
-    typedef struct OpaqueMenuRef * MenuRef;
-    typedef struct OpaquePasteboardRef* PasteboardRef;
-    typedef struct OpaqueRgnHandle * RgnHandle;
-    typedef const struct __HIShape *HIShapeRef;
-    typedef struct __HIShape *HIMutableShapeRef;
-    typedef struct CGRect CGRect;
-    typedef struct CGImage *CGImageRef;
-    typedef struct CGContext *CGContextRef;
-    typedef struct GDevice * GDPtr;
-    typedef GDPtr * GDHandle;
-    typedef struct OpaqueIconRef * IconRef;
-    typedef struct OpaqueWindowPtr * WindowRef;
-    typedef struct OpaqueControlRef * HIViewRef;
-    typedef WindowRef OSWindowRef;
-    typedef HIViewRef OSViewRef;
-    typedef MenuRef OSMenuRef;
-    typedef EventRef OSEventRef;
-#endif  // QT_MAC_USE_COCOA
-
-typedef PasteboardRef OSPasteboardRef;
-typedef struct AEDesc AEDescList;
-typedef AEDescList AERecord;
-typedef AERecord AppleEvent;
-
-#ifdef check
-#undef check
-#endif
-
-#ifdef old_qDebug
-#  undef qDebug
-#  define qDebug QT_NO_QDEBUG_MACRO
-#  undef old_qDebug
-#endif
diff --git a/src/gui/kernel/qmacgesturerecognizer_mac.mm b/src/gui/kernel/qmacgesturerecognizer_mac.mm
deleted file mode 100644 (file)
index 9360d72..0000000
+++ /dev/null
@@ -1,272 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmacgesturerecognizer_mac_p.h"
-#include "qgesture.h"
-#include "qgesture_p.h"
-#include "qevent.h"
-#include "qevent_p.h"
-#include "qwidget.h"
-#include "qdebug.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-QMacSwipeGestureRecognizer::QMacSwipeGestureRecognizer()
-{
-}
-
-QGesture *QMacSwipeGestureRecognizer::create(QObject * /*target*/)
-{
-    return new QSwipeGesture;
-}
-
-QGestureRecognizer::Result
-QMacSwipeGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *event)
-{
-    if (event->type() == QEvent::NativeGesture && obj->isWidgetType()) {
-        QNativeGestureEvent *ev = static_cast<QNativeGestureEvent*>(event);
-        switch (ev->gestureType) {
-            case QNativeGestureEvent::Swipe: {
-                QSwipeGesture *g = static_cast<QSwipeGesture *>(gesture);
-                g->setSwipeAngle(ev->angle);
-                g->setHotSpot(ev->position);
-                return QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint;
-                break; }
-            default:
-                break;
-        }
-    }
-
-    return QGestureRecognizer::Ignore;
-}
-
-void QMacSwipeGestureRecognizer::reset(QGesture *gesture)
-{
-    QSwipeGesture *g = static_cast<QSwipeGesture *>(gesture);
-    g->setSwipeAngle(0);
-    QGestureRecognizer::reset(gesture);
-}
-
-////////////////////////////////////////////////////////////////////////
-
-QMacPinchGestureRecognizer::QMacPinchGestureRecognizer()
-{
-}
-
-QGesture *QMacPinchGestureRecognizer::create(QObject * /*target*/)
-{
-    return new QPinchGesture;
-}
-
-QGestureRecognizer::Result
-QMacPinchGestureRecognizer::recognize(QGesture *gesture, QObject *obj, QEvent *event)
-{
-    if (event->type() == QEvent::NativeGesture && obj->isWidgetType()) {
-        QPinchGesture *g = static_cast<QPinchGesture *>(gesture);
-        QNativeGestureEvent *ev = static_cast<QNativeGestureEvent*>(event);
-        switch(ev->gestureType) {
-        case QNativeGestureEvent::GestureBegin:
-            reset(gesture);
-            g->setStartCenterPoint(static_cast<QWidget*>(obj)->mapFromGlobal(ev->position));
-            g->setCenterPoint(g->startCenterPoint());
-            g->setChangeFlags(QPinchGesture::CenterPointChanged);
-            g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
-            g->setHotSpot(ev->position);
-            return QGestureRecognizer::MayBeGesture | QGestureRecognizer::ConsumeEventHint;
-        case QNativeGestureEvent::Rotate: {
-            g->setLastScaleFactor(g->scaleFactor());
-            g->setLastRotationAngle(g->rotationAngle());
-            g->setRotationAngle(g->rotationAngle() + ev->percentage);
-            g->setChangeFlags(QPinchGesture::RotationAngleChanged);
-            g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
-            g->setHotSpot(ev->position);
-            return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
-        }
-        case QNativeGestureEvent::Zoom:
-            g->setLastScaleFactor(g->scaleFactor());
-            g->setLastRotationAngle(g->rotationAngle());
-            g->setScaleFactor(g->scaleFactor() * (1 + ev->percentage));
-            g->setChangeFlags(QPinchGesture::ScaleFactorChanged);
-            g->setTotalChangeFlags(g->totalChangeFlags() | g->changeFlags());
-            g->setHotSpot(ev->position);
-            return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
-        case QNativeGestureEvent::GestureEnd:
-            return QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint;
-        default:
-            break;
-        }
-    }
-
-    return QGestureRecognizer::Ignore;
-}
-
-void QMacPinchGestureRecognizer::reset(QGesture *gesture)
-{
-    QPinchGesture *g = static_cast<QPinchGesture *>(gesture);
-    g->setChangeFlags(0);
-    g->setTotalChangeFlags(0);
-    g->setScaleFactor(1.0f);
-    g->setTotalScaleFactor(1.0f);
-    g->setLastScaleFactor(1.0f);
-    g->setRotationAngle(0.0f);
-    g->setTotalRotationAngle(0.0f);
-    g->setLastRotationAngle(0.0f);
-    g->setCenterPoint(QPointF());
-    g->setStartCenterPoint(QPointF());
-    g->setLastCenterPoint(QPointF());
-    QGestureRecognizer::reset(gesture);
-}
-
-////////////////////////////////////////////////////////////////////////
-
-#if defined(QT_MAC_USE_COCOA)
-
-QMacPanGestureRecognizer::QMacPanGestureRecognizer() : _panCanceled(true)
-{
-}
-
-QGesture *QMacPanGestureRecognizer::create(QObject *target)
-{
-    if (!target)
-        return new QPanGesture;
-
-    if (QWidget *w = qobject_cast<QWidget *>(target)) {
-        w->setAttribute(Qt::WA_AcceptTouchEvents);
-        w->setAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
-        return new QPanGesture;
-    }
-    return 0;
-}
-
-QGestureRecognizer::Result
-QMacPanGestureRecognizer::recognize(QGesture *gesture, QObject *target, QEvent *event)
-{
-    const int panBeginDelay = 300;
-    const int panBeginRadius = 3;
-
-    QPanGesture *g = static_cast<QPanGesture *>(gesture);
-
-    switch (event->type()) {
-    case QEvent::TouchBegin: {
-        const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
-        if (ev->touchPoints().size() == 1) {
-            reset(gesture);
-            _startPos = QCursor::pos();
-            _panTimer.start(panBeginDelay, target);
-            _panCanceled = false;
-            return QGestureRecognizer::MayBeGesture;
-        }
-        break;}
-    case QEvent::TouchEnd: {
-        if (_panCanceled)
-            break;
-
-        const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
-        if (ev->touchPoints().size() == 1)
-            return QGestureRecognizer::FinishGesture;
-        break;}
-    case QEvent::TouchUpdate: {
-        if (_panCanceled)
-            break;
-
-        const QTouchEvent *ev = static_cast<const QTouchEvent*>(event);
-        if (ev->touchPoints().size() == 1) {
-            if (_panTimer.isActive()) {
-                // INVARIANT: Still in maybeGesture. Check if the user
-                // moved his finger so much that it makes sense to cancel the pan:
-                const QPointF p = QCursor::pos();
-                if ((p - _startPos).manhattanLength() > panBeginRadius) {
-                    _panCanceled = true;
-                    _panTimer.stop();
-                    return QGestureRecognizer::CancelGesture;
-                }
-            } else {
-                const QPointF p = QCursor::pos();
-                const QPointF posOffset = p - _startPos;
-                g->setLastOffset(g->offset());
-                g->setOffset(QPointF(posOffset.x(), posOffset.y()));
-                g->setHotSpot(_startPos);
-                return QGestureRecognizer::TriggerGesture;
-            }
-        } else if (_panTimer.isActive()) {
-            // I only want to cancel the pan if the user is pressing
-            // more than one finger, and the pan hasn't started yet:
-            _panCanceled = true;
-            _panTimer.stop();
-            return QGestureRecognizer::CancelGesture;
-        }
-        break;}
-    case QEvent::Timer: {
-        QTimerEvent *ev = static_cast<QTimerEvent *>(event);
-        if (ev->timerId() == _panTimer.timerId()) {
-            _panTimer.stop();
-            if (_panCanceled)
-                break;
-            // Begin new pan session!
-            _startPos = QCursor::pos();
-            g->setHotSpot(_startPos);
-            return QGestureRecognizer::TriggerGesture | QGestureRecognizer::ConsumeEventHint;
-        }
-        break; }
-    default:
-        break;
-    }
-
-    return QGestureRecognizer::Ignore;
-}
-
-void QMacPanGestureRecognizer::reset(QGesture *gesture)
-{
-    QPanGesture *g = static_cast<QPanGesture *>(gesture);
-    _startPos = QPointF();
-    _panCanceled = true;
-    g->setOffset(QPointF(0, 0));
-    g->setLastOffset(QPointF(0, 0));
-    g->setAcceleration(qreal(1));
-    QGestureRecognizer::reset(gesture);
-}
-#endif // QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
diff --git a/src/gui/kernel/qmacgesturerecognizer_mac_p.h b/src/gui/kernel/qmacgesturerecognizer_mac_p.h
deleted file mode 100644 (file)
index 1b42288..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QMACSWIPEGESTURERECOGNIZER_MAC_P_H
-#define QMACSWIPEGESTURERECOGNIZER_MAC_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 "qtimer.h"
-#include "qpoint.h"
-#include "qgesturerecognizer.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-class QMacSwipeGestureRecognizer : public QGestureRecognizer
-{
-public:
-    QMacSwipeGestureRecognizer();
-
-    QGesture *create(QObject *target);
-    QGestureRecognizer::Result recognize(QGesture *gesture, QObject *watched, QEvent *event);
-    void reset(QGesture *gesture);
-};
-
-class QMacPinchGestureRecognizer : public QGestureRecognizer
-{
-public:
-    QMacPinchGestureRecognizer();
-
-    QGesture *create(QObject *target);
-    QGestureRecognizer::Result recognize(QGesture *gesture, QObject *watched, QEvent *event);
-    void reset(QGesture *gesture);
-};
-
-#if defined(QT_MAC_USE_COCOA)
-
-class QMacPanGestureRecognizer : public QObject, public QGestureRecognizer
-{
-public:
-    QMacPanGestureRecognizer();
-
-    QGesture *create(QObject *target);
-    QGestureRecognizer::Result recognize(QGesture *gesture, QObject *watched, QEvent *event);
-    void reset(QGesture *gesture);
-private:
-    QPointF _startPos;
-    QBasicTimer _panTimer;
-    bool _panCanceled;
-};
-
-#endif
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#endif // QMACSWIPEGESTURERECOGNIZER_MAC_P_H
diff --git a/src/gui/kernel/qmime_mac.cpp b/src/gui/kernel/qmime_mac.cpp
deleted file mode 100644 (file)
index 9428d9d..0000000
+++ /dev/null
@@ -1,1123 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmime.h"
-
-//#define USE_INTERNET_CONFIG
-
-#ifndef USE_INTERNET_CONFIG
-# include "qfile.h"
-# include "qfileinfo.h"
-# include "qtextstream.h"
-# include "qdir.h"
-# include <unistd.h>
-# include <sys/types.h>
-# include <sys/stat.h>
-# include <sys/fcntl.h>
-#endif
-
-#include "qdebug.h"
-#include "qpixmap.h"
-#include "qimagewriter.h"
-#include "qimagereader.h"
-#include "qdatastream.h"
-#include "qbuffer.h"
-#include "qdatetime.h"
-#include "qapplication_p.h"
-#include "qtextcodec.h"
-#include "qregexp.h"
-#include "qurl.h"
-#include "qmap.h"
-#include <qt_mac_p.h>
-
-
-#ifdef Q_WS_MAC32
-#include <QuickTime/QuickTime.h>
-#include <qlibrary.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern CGImageRef qt_mac_createCGImageFromQImage(const QImage &img, const QImage **imagePtr = 0); // qpaintengine_mac.cpp
-
-typedef QList<QMacPasteboardMime*> MimeList;
-Q_GLOBAL_STATIC(MimeList, globalMimeList)
-
-static void cleanup_mimes()
-{
-    MimeList *mimes = globalMimeList();
-    while (!mimes->isEmpty())
-        delete mimes->takeFirst();
-}
-
-Q_GLOBAL_STATIC(QStringList, globalDraggedTypesList)
-
-/*!
-    \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
-*/
-Q_GUI_EXPORT void qRegisterDraggedTypes(const QStringList &types)
-{
-    (*globalDraggedTypesList()) += types;
-}
-
-const QStringList& qEnabledDraggedTypes()
-{
-    return (*globalDraggedTypesList());
-}
-
-
-/*****************************************************************************
-  QDnD debug facilities
- *****************************************************************************/
-//#define DEBUG_MIME_MAPS
-
-ScrapFlavorType qt_mac_mime_type = 'CUTE';
-CFStringRef qt_mac_mime_typeUTI = CFSTR("com.pasteboard.trolltech.marker");
-
-/*!
-  \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
-
-  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.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.
-*/
-QMacPasteboardMime::QMacPasteboardMime(char t) : type(t)
-{
-    globalMimeList()->append(this);
-}
-
-/*!
-  Destroys a conversion object, removing it from the global
-  list of available convertors.
-*/
-QMacPasteboardMime::~QMacPasteboardMime()
-{
-    if(!QApplication::closingDown())
-        globalMimeList()->removeAll(this);
-}
-
-class QMacPasteboardMimeAny : public QMacPasteboardMime {
-private:
-
-public:
-    QMacPasteboardMimeAny() : QMacPasteboardMime(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 QMacPasteboardMime {
-private:
-
-public:
-    QMacPasteboardMimeTypeName() : QMacPasteboardMime(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("x-qt-mime-type-name").toUtf8());
-    return ret;
-}
-
-class QMacPasteboardMimePlainText : public QMacPasteboardMime {
-public:
-    QMacPasteboardMimePlainText() : QMacPasteboardMime(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 QMacPasteboardMimePlainText::convertorName()
-{
-    return QLatin1String("PlainText");
-}
-
-QString QMacPasteboardMimePlainText::flavorFor(const QString &mime)
-{
-    if (mime == QLatin1String("text/plain"))
-        return QLatin1String("com.apple.traditional-mac-plain-text");
-    return QString();
-}
-
-QString QMacPasteboardMimePlainText::mimeFor(QString flav)
-{
-    if (flav == QLatin1String("com.apple.traditional-mac-plain-text"))
-        return QLatin1String("text/plain");
-    return QString();
-}
-
-bool QMacPasteboardMimePlainText::canConvert(const QString &mime, QString flav)
-{
-    return flavorFor(mime) == flav;
-}
-
-QVariant QMacPasteboardMimePlainText::convertToMime(const QString &mimetype, QList<QByteArray> data, QString flavor)
-{
-    if(data.count() > 1)
-        qWarning("QMacPasteboardMimePlainText: Cannot handle multiple member data");
-    const QByteArray &firstData = data.first();
-    QVariant ret;
-    if(flavor == QCFString(QLatin1String("com.apple.traditional-mac-plain-text"))) {
-        QCFString str(CFStringCreateWithBytes(kCFAllocatorDefault,
-                                             reinterpret_cast<const UInt8 *>(firstData.constData()),
-                                             firstData.size(), CFStringGetSystemEncoding(), false));
-        ret = QString(str);
-    } else {
-        qWarning("QMime::convertToMime: unhandled mimetype: %s", qPrintable(mimetype));
-    }
-    return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimePlainText::convertFromMime(const QString &, QVariant data, QString flavor)
-{
-    QList<QByteArray> ret;
-    QString string = data.toString();
-    if(flavor == QCFString(QLatin1String("com.apple.traditional-mac-plain-text")))
-        ret.append(string.toLatin1());
-    return ret;
-}
-
-class QMacPasteboardMimeUnicodeText : public QMacPasteboardMime {
-public:
-    QMacPasteboardMimeUnicodeText() : QMacPasteboardMime(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 flavorFor(mime) == flav;
-}
-
-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")) {
-        QCFString str(CFStringCreateWithBytes(kCFAllocatorDefault,
-                                             reinterpret_cast<const UInt8 *>(firstData.constData()),
-                                             firstData.size(), CFStringGetSystemEncoding(), false));
-        ret = QString(str);
-    } else if (flavor == QLatin1String("public.utf16-plain-text")) {
-        ret = QString(reinterpret_cast<const QChar *>(firstData.constData()),
-                      firstData.size() / sizeof(QChar));
-    } 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());
-    else if (flavor == QLatin1String("public.utf16-plain-text"))
-        ret.append(QByteArray((char*)string.utf16(), string.length()*2));
-    return ret;
-}
-
-class QMacPasteboardMimeHTMLText : public QMacPasteboardMime {
-public:
-    QMacPasteboardMimeHTMLText() : QMacPasteboardMime(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;
-}
-
-
-#ifdef Q_WS_MAC32
-
-// This can be removed once 10.6 is the minimum (or we have to require 64-bit) whichever comes first.
-
-typedef ComponentResult (*PtrGraphicsImportSetDataHandle)(GraphicsImportComponent, Handle);
-typedef ComponentResult (*PtrGraphicsImportCreateCGImage)(GraphicsImportComponent, CGImageRef*, UInt32);
-typedef ComponentResult (*PtrGraphicsExportSetInputCGImage)(GraphicsExportComponent, CGImageRef);
-typedef ComponentResult (*PtrGraphicsExportSetOutputHandle)(GraphicsExportComponent, Handle);
-typedef ComponentResult (*PtrGraphicsExportDoExport)(GraphicsExportComponent, unsigned long *);
-
-static PtrGraphicsImportSetDataHandle ptrGraphicsImportSetDataHandle = 0;
-static PtrGraphicsImportCreateCGImage ptrGraphicsImportCreateCGImage = 0;
-static PtrGraphicsExportSetInputCGImage ptrGraphicsExportSetInputCGImage = 0;
-static PtrGraphicsExportSetOutputHandle ptrGraphicsExportSetOutputHandle = 0;
-static PtrGraphicsExportDoExport ptrGraphicsExportDoExport = 0;
-
-static bool resolveMimeQuickTimeSymbols()
-{
-    static bool triedResolve = false;
-    if (!triedResolve) {
-        QLibrary library(QLatin1String("/System/Library/Frameworks/QuickTime.framework/QuickTime"));
-        ptrGraphicsImportSetDataHandle = reinterpret_cast<PtrGraphicsImportSetDataHandle>(library.resolve("GraphicsImportSetDataHandle"));
-        ptrGraphicsImportCreateCGImage = reinterpret_cast<PtrGraphicsImportCreateCGImage>(library.resolve("GraphicsImportCreateCGImage"));
-        ptrGraphicsExportSetInputCGImage = reinterpret_cast<PtrGraphicsExportSetInputCGImage>(library.resolve("GraphicsExportSetInputCGImage"));
-        ptrGraphicsExportSetOutputHandle = reinterpret_cast<PtrGraphicsExportSetOutputHandle>(library.resolve("GraphicsExportSetOutputHandle"));
-        ptrGraphicsExportDoExport = reinterpret_cast<PtrGraphicsExportDoExport>(library.resolve("GraphicsExportDoExport"));
-        triedResolve = true;
-    }
-
-    return ptrGraphicsImportSetDataHandle != 0
-           && ptrGraphicsImportCreateCGImage != 0 && ptrGraphicsExportSetInputCGImage != 0
-           && ptrGraphicsExportSetOutputHandle != 0 && ptrGraphicsExportDoExport != 0;
-}
-
-class QMacPasteboardMimePict : public QMacPasteboardMime {
-public:
-    QMacPasteboardMimePict() : QMacPasteboardMime(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 QMacPasteboardMimePict::convertorName()
-{
-    return QLatin1String("Pict");
-}
-
-QString QMacPasteboardMimePict::flavorFor(const QString &mime)
-{
-    if(mime.startsWith(QLatin1String("application/x-qt-image")))
-        return QLatin1String("com.apple.pict");
-    return QString();
-}
-
-QString QMacPasteboardMimePict::mimeFor(QString flav)
-{
-    if(flav == QLatin1String("com.apple.pict"))
-        return QLatin1String("application/x-qt-image");
-    return QString();
-}
-
-bool QMacPasteboardMimePict::canConvert(const QString &mime, QString flav)
-{
-    return flav == QLatin1String("com.apple.pict")
-            && mime == QLatin1String("application/x-qt-image");
-}
-
-
-QVariant QMacPasteboardMimePict::convertToMime(const QString &mime, QList<QByteArray> data, QString flav)
-{
-    if(data.count() > 1)
-        qWarning("QMacPasteboardMimePict: Cannot handle multiple member data");
-    QVariant ret;
-    if (!resolveMimeQuickTimeSymbols())
-        return ret;
-
-    if(!canConvert(mime, flav))
-        return ret;
-    const QByteArray &a = data.first();
-
-    // This function expects the 512 header (just to skip it, so create the extra space for it).
-    Handle pic = NewHandle(a.size() + 512);
-    memcpy(*pic + 512, a.constData(), a.size());
-
-    GraphicsImportComponent graphicsImporter;
-    ComponentResult result = OpenADefaultComponent(GraphicsImporterComponentType,
-                                                   kQTFileTypePicture, &graphicsImporter);
-    QCFType<CGImageRef> cgImage;
-    if (!result)
-        result = ptrGraphicsImportSetDataHandle(graphicsImporter, pic);
-    if (!result)
-        result = ptrGraphicsImportCreateCGImage(graphicsImporter, &cgImage,
-                                             kGraphicsImportCreateCGImageUsingCurrentSettings);
-    if (!result)
-        ret = QVariant(QPixmap::fromMacCGImageRef(cgImage).toImage());
-    CloseComponent(graphicsImporter);
-    DisposeHandle(pic);
-    return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimePict::convertFromMime(const QString &mime, QVariant variant,
-                                                          QString flav)
-{
-    QList<QByteArray> ret;
-    if (!resolveMimeQuickTimeSymbols())
-        return ret;
-
-    if (!canConvert(mime, flav))
-        return ret;
-    QCFType<CGImageRef> cgimage = qt_mac_createCGImageFromQImage(qvariant_cast<QImage>(variant));
-    Handle pic = NewHandle(0);
-    GraphicsExportComponent graphicsExporter;
-    ComponentResult result = OpenADefaultComponent(GraphicsExporterComponentType,
-                                                   kQTFileTypePicture, &graphicsExporter);
-    if (!result) {
-        unsigned long sizeWritten;
-        result = ptrGraphicsExportSetInputCGImage(graphicsExporter, cgimage);
-        if (!result)
-            result = ptrGraphicsExportSetOutputHandle(graphicsExporter, pic);
-        if (!result)
-            result = ptrGraphicsExportDoExport(graphicsExporter, &sizeWritten);
-
-        CloseComponent(graphicsExporter);
-    }
-
-    int size = GetHandleSize((Handle)pic);
-    // Skip the Picture File header (512 bytes) and feed the raw data
-    QByteArray ar(reinterpret_cast<char *>(*pic + 512), size - 512);
-    ret.append(ar);
-    DisposeHandle(pic);
-    return ret;
-}
-
-
-#endif //Q_WS_MAC32
-
-class QMacPasteboardMimeTiff : public QMacPasteboardMime {
-public:
-    QMacPasteboardMimeTiff() : QMacPasteboardMime(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");
-    QVariant ret;
-    if (!canConvert(mime, flav))
-        return ret;
-    const QByteArray &a = data.first();
-    QCFType<CGImageRef> image;
-    QCFType<CFDataRef> tiffData = CFDataCreateWithBytesNoCopy(0,
-                                                reinterpret_cast<const UInt8 *>(a.constData()),
-                                                a.size(), kCFAllocatorNull);
-    QCFType<CGImageSourceRef> imageSource = CGImageSourceCreateWithData(tiffData, 0);
-    image = CGImageSourceCreateImageAtIndex(imageSource, 0, 0);
-
-    if (image != 0)
-        ret = QVariant(QPixmap::fromMacCGImageRef(image).toImage());
-    return ret;
-}
-
-QList<QByteArray> QMacPasteboardMimeTiff::convertFromMime(const QString &mime, QVariant variant, QString flav)
-{
-    QList<QByteArray> ret;
-    if (!canConvert(mime, flav))
-        return ret;
-
-    QImage img = qvariant_cast<QImage>(variant);
-    QCFType<CGImageRef> cgimage = qt_mac_createCGImageFromQImage(img);
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
-        QCFType<CFMutableDataRef> data = CFDataCreateMutable(0, 0);
-        QCFType<CGImageDestinationRef> imageDestination = CGImageDestinationCreateWithData(data, kUTTypeTIFF, 1, 0);
-        if (imageDestination != 0) {
-            CFTypeRef keys[2];
-            QCFType<CFTypeRef> values[2];
-            QCFType<CFDictionaryRef> options;
-            keys[0] = kCGImagePropertyPixelWidth;
-            keys[1] = kCGImagePropertyPixelHeight;
-            int width = img.width();
-            int height = img.height();
-            values[0] = CFNumberCreate(0, kCFNumberIntType, &width);
-            values[1] = CFNumberCreate(0, kCFNumberIntType, &height);
-            options = CFDictionaryCreate(0, reinterpret_cast<const void **>(keys),
-                                         reinterpret_cast<const void **>(values), 2,
-                                         &kCFTypeDictionaryKeyCallBacks,
-                                         &kCFTypeDictionaryValueCallBacks);
-            CGImageDestinationAddImage(imageDestination, cgimage, options);
-            CGImageDestinationFinalize(imageDestination);
-        }
-        QByteArray ar(CFDataGetLength(data), 0);
-        CFDataGetBytes(data,
-                CFRangeMake(0, ar.size()),
-                reinterpret_cast<UInt8 *>(ar.data()));
-        ret.append(ar);
-    } else
-#endif
-    {
-#ifdef Q_WS_MAC32
-        Handle tiff = NewHandle(0);
-        if (resolveMimeQuickTimeSymbols()) {
-            GraphicsExportComponent graphicsExporter;
-            ComponentResult result = OpenADefaultComponent(GraphicsExporterComponentType,
-                                                           kQTFileTypeTIFF, &graphicsExporter);
-            if (!result) {
-                unsigned long sizeWritten;
-                result = ptrGraphicsExportSetInputCGImage(graphicsExporter, cgimage);
-                if (!result)
-                    result = ptrGraphicsExportSetOutputHandle(graphicsExporter, tiff);
-                if (!result)
-                    result = ptrGraphicsExportDoExport(graphicsExporter, &sizeWritten);
-
-                CloseComponent(graphicsExporter);
-            }
-        }
-        int size = GetHandleSize((Handle)tiff);
-        QByteArray ar(reinterpret_cast<char *>(*tiff), size);
-        ret.append(ar);
-        DisposeHandle(tiff);
-#endif
-    }
-    return ret;
-}
-
-
-class QMacPasteboardMimeFileUri : public QMacPasteboardMime {
-public:
-    QMacPasteboardMimeFileUri() : QMacPasteboardMime(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 QMacPasteboardMimeFileUri::convertorName()
-{
-    return QLatin1String("FileURL");
-}
-
-QString QMacPasteboardMimeFileUri::flavorFor(const QString &mime)
-{
-    if (mime == QLatin1String("text/uri-list"))
-        return QCFString(UTTypeCreatePreferredIdentifierForTag(kUTTagClassOSType, CFSTR("furl"), 0));
-    return QString();
-}
-
-QString QMacPasteboardMimeFileUri::mimeFor(QString flav)
-{
-    if (flav == QCFString(UTTypeCreatePreferredIdentifierForTag(kUTTagClassOSType, CFSTR("furl"), 0)))
-        return QLatin1String("text/uri-list");
-    return QString();
-}
-
-bool QMacPasteboardMimeFileUri::canConvert(const QString &mime, QString flav)
-{
-    return mime == QLatin1String("text/uri-list")
-            && flav == QCFString(UTTypeCreatePreferredIdentifierForTag(kUTTagClassOSType, CFSTR("furl"), 0));
-}
-
-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) {
-        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> 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().toLower() == 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 QMacPasteboardMimeUrl : public QMacPasteboardMime {
-public:
-    QMacPasteboardMimeUrl() : QMacPasteboardMime(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().toLower() == 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 QMacPasteboardMime
-{
-public:
-    QMacPasteboardMimeVCard() : QMacPasteboardMime(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 QString("VCard");
-}
-
-bool QMacPasteboardMimeVCard::canConvert(const QString &mime, QString flav)
-{
-    return mimeFor(flav) == mime;
-}
-
-QString QMacPasteboardMimeVCard::flavorFor(const QString &mime)
-{
-    if(mime.startsWith(QLatin1String("text/plain")))
-        return QLatin1String("public.vcard");
-    return QString();
-}
-
-QString QMacPasteboardMimeVCard::mimeFor(QString flav)
-{
-    if (flav == QLatin1String("public.vcard"))
-        return QLatin1String("text/plain");
-    return QString();
-}
-
-QVariant QMacPasteboardMimeVCard::convertToMime(const QString &mime, QList<QByteArray> data, QString)
-{
-    QByteArray cards;
-    if (mime == QLatin1String("text/plain")) {
-        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/plain"))
-        ret.append(data.toString().toUtf8());
-    return ret;
-}
-
-
-/*!
-  \internal
-
-  This is an internal function.
-*/
-void QMacPasteboardMime::initialize()
-{
-    if(globalMimeList()->isEmpty()) {
-        qAddPostRoutine(cleanup_mimes);
-
-        //standard types that we wrap
-        new QMacPasteboardMimeTiff;
-#ifdef Q_WS_MAC32
-        // 10.6 does automatic synthesis to and from PICT to standard image types (like TIFF),
-        // so don't bother doing it ourselves, especially since it's not available in 64-bit.
-        if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_6)
-            new QMacPasteboardMimePict;
-#endif
-        new QMacPasteboardMimeUnicodeText;
-        new QMacPasteboardMimePlainText;
-        new QMacPasteboardMimeHTMLText;
-        new QMacPasteboardMimeFileUri;
-        new QMacPasteboardMimeUrl;
-        new QMacPasteboardMimeTypeName;
-        new QMacPasteboardMimeVCard;
-        //make sure our "non-standard" types are always last! --Sam
-        new QMacPasteboardMimeAny;
-    }
-}
-
-/*!
-  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.
-*/
-QMacPasteboardMime*
-QMacPasteboardMime::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 QMacPasteboardMime::flavorToMime(uchar t, QString flav)
-{
-    MimeList *mimes = globalMimeList();
-    for(MimeList::const_iterator it = mimes->constBegin(); it != mimes->constEnd(); ++it) {
-#ifdef DEBUG_MIME_MAPS
-        qDebug("QMacPasteboardMime::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<QMacPasteboardMime*> QMacPasteboardMime::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 true if the convertor can convert (both ways) between
-  \a mime and \a flav; otherwise returns 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/gui/kernel/qmime_win.cpp b/src/gui/kernel/qmime_win.cpp
deleted file mode 100644 (file)
index 1b1b269..0000000
+++ /dev/null
@@ -1,1556 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmime.h"
-
-#include "qimagereader.h"
-#include "qimagewriter.h"
-#include "qdatastream.h"
-#include "qbuffer.h"
-#include "qt_windows.h"
-#include "qapplication_p.h"
-#include "qtextcodec.h"
-#include "qregexp.h"
-#include "qalgorithms.h"
-#include "qmap.h"
-#include "qdnd_p.h"
-#include <shlobj.h>
-#include "qurl.h"
-#include "qvariant.h"
-#include "qtextdocument.h"
-#include "qdir.h"
-
-#if defined(Q_OS_WINCE)
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_IMAGEFORMAT_BMP
-#ifndef CF_DIBV5
-#define CF_DIBV5 17
-#endif
-/* The MSVC compilers allows multi-byte characters, that has the behavior of
- * that each character gets shifted into position. 0x73524742 below is for MSVC
- * equivalent to doing 'sRGB', but this does of course not work
- * on conformant C++ compilers. */
-#define BMP_LCS_sRGB  0x73524742
-#define BMP_LCS_GM_IMAGES  0x00000004L
-
-struct _CIEXYZ {
-    long ciexyzX, ciexyzY, ciexyzZ;
-};
-
-struct _CIEXYZTRIPLE {
-    _CIEXYZ  ciexyzRed, ciexyzGreen, ciexyzBlue;
-};
-
-struct BMP_BITMAPV5HEADER {
-    DWORD  bV5Size;
-    LONG   bV5Width;
-    LONG   bV5Height;
-    WORD   bV5Planes;
-    WORD   bV5BitCount;
-    DWORD  bV5Compression;
-    DWORD  bV5SizeImage;
-    LONG   bV5XPelsPerMeter;
-    LONG   bV5YPelsPerMeter;
-    DWORD  bV5ClrUsed;
-    DWORD  bV5ClrImportant;
-    DWORD  bV5RedMask;
-    DWORD  bV5GreenMask;
-    DWORD  bV5BlueMask;
-    DWORD  bV5AlphaMask;
-    DWORD  bV5CSType;
-    _CIEXYZTRIPLE bV5Endpoints;
-    DWORD  bV5GammaRed;
-    DWORD  bV5GammaGreen;
-    DWORD  bV5GammaBlue;
-    DWORD  bV5Intent;
-    DWORD  bV5ProfileData;
-    DWORD  bV5ProfileSize;
-    DWORD  bV5Reserved;
-};
-static const int BMP_BITFIELDS = 3;
-
-extern bool qt_read_dib(QDataStream&, QImage&); // qimage.cpp
-extern bool qt_write_dib(QDataStream&, QImage);   // qimage.cpp
-static bool qt_write_dibv5(QDataStream &s, QImage image);
-static bool qt_read_dibv5(QDataStream &s, QImage &image);
-#endif
-
-//#define QMIME_DEBUG
-
-
-// helpers for using global memory
-
-static int getCf(const FORMATETC &formatetc)
-{
-    return formatetc.cfFormat;
-}
-
-static FORMATETC setCf(int cf)
-{
-    FORMATETC formatetc;
-    formatetc.cfFormat = cf;
-    formatetc.dwAspect = DVASPECT_CONTENT;
-    formatetc.lindex = -1;
-    formatetc.ptd = NULL;
-    formatetc.tymed = TYMED_HGLOBAL;
-    return formatetc;
-}
-
-static bool setData(const QByteArray &data, STGMEDIUM *pmedium)
-{
-    HGLOBAL hData = GlobalAlloc(0, data.size());
-    if (!hData)
-        return false;
-
-    void *out = GlobalLock(hData);
-    memcpy(out, data.data(), data.size());
-    GlobalUnlock(hData);
-    pmedium->tymed = TYMED_HGLOBAL;
-    pmedium->hGlobal = hData;
-    pmedium->pUnkForRelease = 0;
-    return true;
-}
-
-static QByteArray getData(int cf, IDataObject *pDataObj)
-{
-    QByteArray data;
-    FORMATETC formatetc = setCf(cf);
-    STGMEDIUM s;
-    if (pDataObj->GetData(&formatetc, &s) == S_OK) {
-        DWORD * val = (DWORD*)GlobalLock(s.hGlobal);
-        data = QByteArray::fromRawData((char*)val, GlobalSize(s.hGlobal));
-        data.detach();
-        GlobalUnlock(s.hGlobal);
-        ReleaseStgMedium(&s);
-    } else  {
-        //Try reading IStream data
-        formatetc.tymed = TYMED_ISTREAM;
-        if (pDataObj->GetData(&formatetc, &s) == S_OK) {
-            char szBuffer[4096];
-            ULONG actualRead = 0;
-            LARGE_INTEGER pos = {{0, 0}};
-            //Move to front (can fail depending on the data model implemented)
-            HRESULT hr = s.pstm->Seek(pos, STREAM_SEEK_SET, NULL);
-            while(SUCCEEDED(hr)){
-                hr = s.pstm->Read(szBuffer, sizeof(szBuffer), &actualRead);
-                if (SUCCEEDED(hr) && actualRead > 0) {
-                    data += QByteArray::fromRawData(szBuffer, actualRead);
-                }
-                if (actualRead != sizeof(szBuffer))
-                    break;
-            }
-            data.detach();
-            ReleaseStgMedium(&s);
-        }
-    }
-    return data;
-}
-
-static bool canGetData(int cf, IDataObject * pDataObj)
-{
-    FORMATETC formatetc = setCf(cf);
-     if (pDataObj->QueryGetData(&formatetc) != S_OK){
-        formatetc.tymed = TYMED_ISTREAM;
-        return pDataObj->QueryGetData(&formatetc) == S_OK;
-    }
-    return true;
-}
-
-class QWindowsMimeList
-{
-public:
-    QWindowsMimeList();
-    ~QWindowsMimeList();
-    void addWindowsMime(QWindowsMime * mime);
-    void removeWindowsMime(QWindowsMime * mime);
-    QList<QWindowsMime*> windowsMimes();
-
-private:
-    void init();
-    bool initialized;
-    QList<QWindowsMime*> mimes;
-};
-
-Q_GLOBAL_STATIC(QWindowsMimeList, theMimeList);
-
-
-/*!
-    \class QWindowsMime
-    \brief The QWindowsMime class maps open-standard MIME to Window Clipboard formats.
-    \ingroup draganddrop
-
-    Qt's drag-and-drop and clipboard facilities use the MIME standard.
-    On X11, this maps trivially to the Xdnd protocol, but on Windows
-    although some applications use MIME types to describe clipboard
-    formats, others use arbitrary non-standardized naming conventions,
-    or unnamed built-in formats of Windows.
-
-    By instantiating subclasses of QWindowsMime that provide conversions
-    between Windows Clipboard and MIME formats, you can convert
-    proprietary clipboard formats to MIME formats.
-
-    Qt has predefined support for the following Windows Clipboard formats:
-
-    \table
-    \header \o Windows Format \o Equivalent MIME type
-    \row \o \c CF_UNICODETEXT \o \c text/plain
-    \row \o \c CF_TEXT        \o \c text/plain
-    \row \o \c CF_DIB         \o \c{image/xyz}, where \c xyz is
-                                 a \l{QImageWriter::supportedImageFormats()}{Qt image format}
-    \row \o \c CF_HDROP       \o \c text/uri-list
-    \row \o \c CF_INETURL     \o \c text/uri-list
-    \row \o \c CF_HTML        \o \c text/html
-    \endtable
-
-    An example use of this class would be to map the Windows Metafile
-    clipboard format (\c CF_METAFILEPICT) to and from the MIME type
-    \c{image/x-wmf}. This conversion might simply be adding or removing
-    a header, or even just passing on the data. See \l{Drag and Drop}
-    for more information on choosing and definition MIME types.
-
-    You can check if a MIME type is convertible using canConvertFromMime() and
-    can perform conversions with convertToMime() and convertFromMime().
-*/
-
-/*!
-Constructs a new conversion object, adding it to the globally accessed
-list of available converters.
-*/
-QWindowsMime::QWindowsMime()
-{
-    theMimeList()->addWindowsMime(this);
-}
-
-/*!
-Destroys a conversion object, removing it from the global
-list of available converters.
-*/
-QWindowsMime::~QWindowsMime()
-{
-    theMimeList()->removeWindowsMime(this);
-}
-
-
-/*!
-    Registers the MIME type \a mime, and returns an ID number
-    identifying the format on Windows.
-*/
-int QWindowsMime::registerMimeType(const QString &mime)
-{
-    int f = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (mime.utf16()));
-    if (!f)
-        qErrnoWarning("QWindowsMime::registerMimeType: Failed to register clipboard format");
-
-    return f;
-}
-
-
-/*!
-\fn bool QWindowsMime::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-
-  Returns true if the converter can convert from the \a mimeData to
-  the format specified in \a formatetc.
-
-  All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
-  \fn bool QWindowsMime::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-
-  Returns true if the converter can convert to the \a mimeType from
-  the available formats in \a pDataObj.
-
-  All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
-\fn QString QWindowsMime::mimeForFormat(const FORMATETC &formatetc) const
-
-  Returns the mime type that will be created form the format specified
-  in \a formatetc, or an empty string if this converter does not support
-  \a formatetc.
-
-  All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
-\fn QVector<FORMATETC> QWindowsMime::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-
-  Returns a QVector of FORMATETC structures representing the different windows clipboard
-  formats that can be provided for the \a mimeType from the \a mimeData.
-
-  All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
-    \fn QVariant QWindowsMime::convertToMime(const QString &mimeType, IDataObject *pDataObj,
-                                             QVariant::Type preferredType) const
-
-    Returns a QVariant containing the converted data for \a mimeType from \a pDataObj.
-    If possible the QVariant should be of the \a preferredType to avoid needless conversions.
-
-    All subclasses must reimplement this pure virtual function.
-*/
-
-/*!
-\fn bool QWindowsMime::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-
-  Convert the \a mimeData to the format specified in \a formatetc.
-  The converted data should then be placed in \a pmedium structure.
-
-  Return true if the conversion was successful.
-
-  All subclasses must reimplement this pure virtual function.
-*/
-
-
-QWindowsMime *QWindowsMime::converterFromMime(const FORMATETC &formatetc, const QMimeData *mimeData)
-{
-    QList<QWindowsMime*> mimes = theMimeList()->windowsMimes();
-    for (int i=mimes.size()-1; i>=0; --i) {
-        if (mimes.at(i)->canConvertFromMime(formatetc, mimeData))
-            return mimes.at(i);
-    }
-    return 0;
-}
-
-QWindowsMime *QWindowsMime::converterToMime(const QString &mimeType, IDataObject *pDataObj)
-{
-    QList<QWindowsMime*> mimes = theMimeList()->windowsMimes();
-    for (int i=mimes.size()-1; i>=0; --i) {
-        if (mimes.at(i)->canConvertToMime(mimeType, pDataObj))
-            return mimes.at(i);
-    }
-    return 0;
-}
-
-QVector<FORMATETC> QWindowsMime::allFormatsForMime(const QMimeData *mimeData)
-{
-    QList<QWindowsMime*> mimes = theMimeList()->windowsMimes();
-    QVector<FORMATETC> formatics;
-    formatics.reserve(20);
-#ifndef QT_NO_DRAGANDDROP
-    QStringList formats = QInternalMimeData::formatsHelper(mimeData);
-    for (int f=0; f<formats.size(); ++f) {
-        for (int i=mimes.size()-1; i>=0; --i)
-            formatics += mimes.at(i)->formatsForMime(formats.at(f), mimeData);
-    }
-#else
-    Q_UNUSED(mimeData);
-#endif //QT_NO_DRAGANDDROP
-    return formatics;
-}
-
-QStringList QWindowsMime::allMimesForFormats(IDataObject *pDataObj)
-{
-    QList<QWindowsMime*> mimes = theMimeList()->windowsMimes();
-    QStringList formats;
-    LPENUMFORMATETC FAR fmtenum;
-    HRESULT hr = pDataObj->EnumFormatEtc(DATADIR_GET, &fmtenum);
-
-    if (hr == NOERROR) {
-        FORMATETC fmtetc;
-        while (S_OK == fmtenum->Next(1, &fmtetc, 0)) {
-#if defined(QMIME_DEBUG) && !defined(Q_OS_WINCE)
-            qDebug("QWindowsMime::allMimesForFormats()");
-            wchar_t buf[256] = {0};
-            GetClipboardFormatName(fmtetc.cfFormat, buf, 255);
-            qDebug("CF = %d : %s", fmtetc.cfFormat, QString::fromWCharArray(buf));
-#endif
-            for (int i=mimes.size()-1; i>=0; --i) {
-                QString format = mimes.at(i)->mimeForFormat(fmtetc);
-                if (!format.isEmpty() && !formats.contains(format)) {
-                    formats += format;
-                }
-            }
-            // as documented in MSDN to avoid possible memleak
-            if (fmtetc.ptd)
-                CoTaskMemFree(fmtetc.ptd);
-        }
-        fmtenum->Release();
-    }
-
-    return formats;
-}
-
-
-class QWindowsMimeText : public QWindowsMime
-{
-public:
-    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
-    QVariant convertToMime(const QString &mime, LPDATAOBJECT pDataObj, QVariant::Type preferredType) const;
-    QString mimeForFormat(const FORMATETC &formatetc) const;
-    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
-    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM *pmedium) const;
-    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-};
-
-bool QWindowsMimeText::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
-    int cf = getCf(formatetc);
-    return (cf == CF_UNICODETEXT || cf == CF_TEXT) && mimeData->hasText();
-}
-
-/*
-text/plain is defined as using CRLF, but so many programs don't,
-and programmers just look for '\n' in strings.
-Windows really needs CRLF, so we ensure it here.
-*/
-bool QWindowsMimeText::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM *pmedium) const
-{
-    if (canConvertFromMime(formatetc, mimeData)) {
-        QByteArray data;
-        int cf = getCf(formatetc);
-        if (cf == CF_TEXT) {
-            data = mimeData->text().toLocal8Bit();
-            // Anticipate required space for CRLFs at 1/40
-            int maxsize=data.size()+data.size()/40+3;
-            QByteArray r(maxsize, '\0');
-            char* o = r.data();
-            const char* d = data.data();
-            const int s = data.size();
-            bool cr=false;
-            int j=0;
-            for (int i=0; i<s; i++) {
-                char c = d[i];
-                if (c=='\r')
-                    cr=true;
-                else {
-                    if (c=='\n') {
-                        if (!cr)
-                            o[j++]='\r';
-                    }
-                    cr=false;
-                }
-                o[j++]=c;
-                if (j+3 >= maxsize) {
-                    maxsize += maxsize/4;
-                    r.resize(maxsize);
-                    o = r.data();
-                }
-            }
-            o[j]=0;
-            return setData(r, pmedium);
-        } else if (cf == CF_UNICODETEXT) {
-            QString str = mimeData->text();
-            const QChar *u = str.unicode();
-            QString res;
-            const int s = str.length();
-            int maxsize = s + s/40 + 3;
-            res.resize(maxsize);
-            int ri = 0;
-            bool cr = false;
-            for (int i=0; i < s; ++i) {
-                if (*u == QLatin1Char('\r'))
-                    cr = true;
-                else {
-                    if (*u == QLatin1Char('\n') && !cr)
-                        res[ri++] = QLatin1Char('\r');
-                    cr = false;
-                }
-                res[ri++] = *u;
-                if (ri+3 >= maxsize) {
-                    maxsize += maxsize/4;
-                    res.resize(maxsize);
-                }
-                ++u;
-            }
-            res.truncate(ri);
-            const int byteLength = res.length() * sizeof(ushort);
-            QByteArray r(byteLength + 2, '\0');
-            memcpy(r.data(), res.unicode(), byteLength);
-            r[byteLength] = 0;
-            r[byteLength+1] = 0;
-            return setData(r, pmedium);
-        }
-    }
-    return false;
-}
-
-bool QWindowsMimeText::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
-    return mimeType.startsWith(QLatin1String("text/plain"))
-           && (canGetData(CF_UNICODETEXT, pDataObj)
-           || canGetData(CF_TEXT, pDataObj));
-}
-
-QString QWindowsMimeText::mimeForFormat(const FORMATETC &formatetc) const
-{
-    int cf = getCf(formatetc);
-    if (cf == CF_UNICODETEXT || cf == CF_TEXT)
-        return QLatin1String("text/plain");
-    return QString();
-}
-
-
-QVector<FORMATETC> QWindowsMimeText::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
-    QVector<FORMATETC> formatics;
-    if (mimeType.startsWith(QLatin1String("text/plain")) && mimeData->hasText()) {
-        formatics += setCf(CF_UNICODETEXT);
-        formatics += setCf(CF_TEXT);
-    }
-    return formatics;
-}
-
-QVariant QWindowsMimeText::convertToMime(const QString &mime, LPDATAOBJECT pDataObj, QVariant::Type preferredType) const
-{
-    QVariant ret;
-
-    if (canConvertToMime(mime, pDataObj)) {
-        QString str;
-        QByteArray data = getData(CF_UNICODETEXT, pDataObj);
-        if (!data.isEmpty()) {
-            str = QString::fromWCharArray((const wchar_t *)data.data());
-            str.replace(QLatin1String("\r\n"), QLatin1String("\n"));
-        } else {
-            data = getData(CF_TEXT, pDataObj);
-            if (!data.isEmpty()) {
-                const char* d = data.data();
-                const int s = qstrlen(d);
-                QByteArray r(data.size()+1, '\0');
-                char* o = r.data();
-                int j=0;
-                for (int i=0; i<s; i++) {
-                    char c = d[i];
-                    if (c!='\r')
-                        o[j++]=c;
-                }
-                o[j]=0;
-                str = QString::fromLocal8Bit(r);
-            }
-        }
-        if (preferredType == QVariant::String)
-            ret = str;
-        else
-            ret = str.toUtf8();
-    }
-
-    return ret;
-}
-
-class QWindowsMimeURI : public QWindowsMime
-{
-public:
-    QWindowsMimeURI();
-    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
-    QVariant convertToMime(const QString &mime, LPDATAOBJECT pDataObj, QVariant::Type preferredType) const;
-    QString mimeForFormat(const FORMATETC &formatetc) const;
-    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
-    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM *pmedium) const;
-    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-private:
-    int CF_INETURL_W; // wide char version
-    int CF_INETURL;
-};
-
-QWindowsMimeURI::QWindowsMimeURI()
-{
-    CF_INETURL_W = QWindowsMime::registerMimeType(QLatin1String("UniformResourceLocatorW"));
-    CF_INETURL = QWindowsMime::registerMimeType(QLatin1String("UniformResourceLocator"));
-}
-
-bool QWindowsMimeURI::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
-    if (getCf(formatetc) == CF_HDROP) {
-        QList<QUrl> urls = mimeData->urls();
-        for (int i=0; i<urls.size(); i++) {
-            if (!urls.at(i).toLocalFile().isEmpty())
-                return true;
-        }
-    }
-    return (getCf(formatetc) == CF_INETURL_W || getCf(formatetc) == CF_INETURL) && mimeData->hasFormat(QLatin1String("text/uri-list"));
-}
-
-bool QWindowsMimeURI::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM *pmedium) const
-{
-    if (canConvertFromMime(formatetc, mimeData)) {
-        if (getCf(formatetc) == CF_HDROP) {
-            QList<QUrl> urls = mimeData->urls();
-            QStringList fileNames;
-            int size = sizeof(DROPFILES)+2;
-            for (int i=0; i<urls.size(); i++) {
-                QString fn = QDir::toNativeSeparators(urls.at(i).toLocalFile());
-                if (!fn.isEmpty()) {
-                    size += sizeof(ushort) * (fn.length() + 1);
-                    fileNames.append(fn);
-                }
-            }
-
-            QByteArray result(size, '\0');
-            DROPFILES* d = (DROPFILES*)result.data();
-            d->pFiles = sizeof(DROPFILES);
-            GetCursorPos(&d->pt); // try
-            d->fNC = true;
-            char* files = ((char*)d) + d->pFiles;
-
-            d->fWide = true;
-            wchar_t* f = (wchar_t*)files;
-            for (int i=0; i<fileNames.size(); i++) {
-                int l = fileNames.at(i).length();
-                memcpy(f, fileNames.at(i).utf16(), l * sizeof(ushort));
-                f += l;
-                *f++ = 0;
-            }
-            *f = 0;
-
-            return setData(result, pmedium);
-        } else if (getCf(formatetc) == CF_INETURL_W) {
-            QList<QUrl> urls = mimeData->urls();
-            QByteArray result;
-            if (!urls.isEmpty()) {
-                QString url = urls.at(0).toString();
-                result = QByteArray((const char *)url.utf16(), url.length() * sizeof(ushort));
-            }
-            result.append('\0');
-            result.append('\0');
-            return setData(result, pmedium);
-        } else if (getCf(formatetc) == CF_INETURL) {
-            QList<QUrl> urls = mimeData->urls();
-            QByteArray result;
-            if (!urls.isEmpty())
-                result = urls.at(0).toString().toLocal8Bit();
-            return setData(result, pmedium);
-        }
-    }
-
-    return false;
-}
-
-bool QWindowsMimeURI::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
-    return mimeType == QLatin1String("text/uri-list")
-           && (canGetData(CF_HDROP, pDataObj) || canGetData(CF_INETURL_W, pDataObj) || canGetData(CF_INETURL, pDataObj));
-}
-
-QString QWindowsMimeURI::mimeForFormat(const FORMATETC &formatetc) const
-{
-    QString format;
-    if (getCf(formatetc) == CF_HDROP || getCf(formatetc) == CF_INETURL_W || getCf(formatetc) == CF_INETURL)
-        format = QLatin1String("text/uri-list");
-    return format;
-}
-
-QVector<FORMATETC> QWindowsMimeURI::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
-    QVector<FORMATETC> formatics;
-    if (mimeType == QLatin1String("text/uri-list")) {
-        if (canConvertFromMime(setCf(CF_HDROP), mimeData))
-            formatics += setCf(CF_HDROP);
-        if (canConvertFromMime(setCf(CF_INETURL_W), mimeData))
-            formatics += setCf(CF_INETURL_W);
-        if (canConvertFromMime(setCf(CF_INETURL), mimeData))
-            formatics += setCf(CF_INETURL);
-    }
-    return formatics;
-}
-
-QVariant QWindowsMimeURI::convertToMime(const QString &mimeType, LPDATAOBJECT pDataObj, QVariant::Type preferredType) const
-{
-    if (mimeType == QLatin1String("text/uri-list")) {
-        if (canGetData(CF_HDROP, pDataObj)) {
-            QByteArray texturi;
-            QList<QVariant> urls;
-
-            QByteArray data = getData(CF_HDROP, pDataObj);
-            if (data.isEmpty())
-                return QVariant();
-
-            LPDROPFILES hdrop = (LPDROPFILES)data.data();
-            if (hdrop->fWide) {
-                const wchar_t* filesw = (const wchar_t *)(data.data() + hdrop->pFiles);
-                int i = 0;
-                while (filesw[i]) {
-                    QString fileurl = QString::fromWCharArray(filesw + i);
-                    urls += QUrl::fromLocalFile(fileurl);
-                    i += fileurl.length()+1;
-                }
-            } else {
-                const char* files = (const char *)data.data() + hdrop->pFiles;
-                int i=0;
-                while (files[i]) {
-                    urls += QUrl::fromLocalFile(QString::fromLocal8Bit(files+i));
-                    i += int(strlen(files+i))+1;
-                }
-            }
-
-            if (preferredType == QVariant::Url && urls.size() == 1)
-                return urls.at(0);
-            else if (!urls.isEmpty())
-                return urls;
-        } else if (canGetData(CF_INETURL_W, pDataObj)) {
-            QByteArray data = getData(CF_INETURL_W, pDataObj);
-            if (data.isEmpty())
-                return QVariant();
-            return QUrl(QString::fromWCharArray((const wchar_t *)data.constData()));
-         } else if (canGetData(CF_INETURL, pDataObj)) {
-            QByteArray data = getData(CF_INETURL, pDataObj);
-            if (data.isEmpty())
-                return QVariant();
-            return QUrl(QString::fromLocal8Bit(data.constData()));
-        }
-    }
-    return QVariant();
-}
-
-class QWindowsMimeHtml : public QWindowsMime
-{
-public:
-    QWindowsMimeHtml();
-
-    // for converting from Qt
-    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
-    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const;
-    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-
-    // for converting to Qt
-    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
-    QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const;
-    QString mimeForFormat(const FORMATETC &formatetc) const;
-
-private:
-    int CF_HTML;
-};
-
-QWindowsMimeHtml::QWindowsMimeHtml()
-{
-    CF_HTML = QWindowsMime::registerMimeType(QLatin1String("HTML Format"));
-}
-
-QVector<FORMATETC> QWindowsMimeHtml::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
-    QVector<FORMATETC> formatetcs;
-    if (mimeType == QLatin1String("text/html") && (!mimeData->html().isEmpty()))
-        formatetcs += setCf(CF_HTML);
-    return formatetcs;
-}
-
-QString QWindowsMimeHtml::mimeForFormat(const FORMATETC &formatetc) const
-{
-    if (getCf(formatetc) == CF_HTML)
-        return QLatin1String("text/html");
-    return QString();
-}
-
-bool QWindowsMimeHtml::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
-    return mimeType == QLatin1String("text/html") && canGetData(CF_HTML, pDataObj);
-}
-
-
-bool QWindowsMimeHtml::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
-    return getCf(formatetc) == CF_HTML && (!mimeData->html().isEmpty());
-}
-
-/*
-The windows HTML clipboard format is as follows (xxxxxxxxxx is a 10 integer number giving the positions
-in bytes). Charset used is mostly utf8, but can be different, ie. we have to look for the <meta> charset tag
-
-  Version: 1.0
-  StartHTML:xxxxxxxxxx
-  EndHTML:xxxxxxxxxx
-  StartFragment:xxxxxxxxxx
-  EndFragment:xxxxxxxxxx
-  ...html...
-
-*/
-QVariant QWindowsMimeHtml::convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const
-{
-    Q_UNUSED(preferredType);
-    QVariant result;
-    if (canConvertToMime(mime, pDataObj)) {
-        QByteArray html = getData(CF_HTML, pDataObj);
-#ifdef QMIME_DEBUG
-        qDebug("QWindowsMimeHtml::convertToMime");
-        qDebug("raw :");
-        qDebug(html);
-#endif
-        int start = html.indexOf("StartFragment:");
-        int end = html.indexOf("EndFragment:");
-
-        if (start != -1) {
-            int startOffset = start + 14;
-            int i = startOffset;
-            while (html.at(i) != '\r' && html.at(i) != '\n')
-                ++i;
-            QByteArray bytecount = html.mid(startOffset, i - startOffset);
-            start = bytecount.toInt();
-        }
-
-        if (end != -1) {
-            int endOffset = end + 12;
-            int i = endOffset ;
-            while (html.at(i) != '\r' && html.at(i) != '\n')
-                ++i;
-            QByteArray bytecount = html.mid(endOffset , i - endOffset);
-            end = bytecount.toInt();
-        }
-
-        if (end > start && start > 0) {
-            html = "<!--StartFragment-->" + html.mid(start, end - start);
-            html += "<!--EndFragment-->";
-            html.replace('\r', "");
-            result = QString::fromUtf8(html);
-        }
-    }
-    return result;
-}
-
-bool QWindowsMimeHtml::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-{
-    if (canConvertFromMime(formatetc, mimeData)) {
-        QByteArray data = mimeData->html().toUtf8();
-        QByteArray result =
-            "Version:1.0\r\n"                    // 0-12
-            "StartHTML:0000000105\r\n"            // 13-35
-            "EndHTML:0000000000\r\n"            // 36-55
-            "StartFragment:0000000000\r\n"            // 58-86
-            "EndFragment:0000000000\r\n\r\n";   // 87-105
-
-        if (data.indexOf("<!--StartFragment-->") == -1)
-            result += "<!--StartFragment-->";
-        result += data;
-        if (data.indexOf("<!--EndFragment-->") == -1)
-            result += "<!--EndFragment-->";
-
-        // set the correct number for EndHTML
-        QByteArray pos = QString::number(result.size()).toLatin1();
-        memcpy((char *)(result.data() + 53 - pos.length()), pos.constData(), pos.length());
-
-        // set correct numbers for StartFragment and EndFragment
-        pos = QString::number(result.indexOf("<!--StartFragment-->") + 20).toLatin1();
-        memcpy((char *)(result.data() + 79 - pos.length()), pos.constData(), pos.length());
-        pos = QString::number(result.indexOf("<!--EndFragment-->")).toLatin1();
-        memcpy((char *)(result.data() + 103 - pos.length()), pos.constData(), pos.length());
-
-        return setData(result, pmedium);
-    }
-    return false;
-}
-
-
-#ifndef QT_NO_IMAGEFORMAT_BMP
-class QWindowsMimeImage : public QWindowsMime
-{
-public:
-    QWindowsMimeImage();
-    // for converting from Qt
-    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
-    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const;
-    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-
-    // for converting to Qt
-    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
-    QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const;
-    QString mimeForFormat(const FORMATETC &formatetc) const;
-private:
-    bool hasOriginalDIBV5(IDataObject *pDataObj) const;
-    UINT CF_PNG;
-};
-
-QWindowsMimeImage::QWindowsMimeImage()
-{
-    CF_PNG = RegisterClipboardFormat(L"PNG");
-}
-
-QVector<FORMATETC> QWindowsMimeImage::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
-    QVector<FORMATETC> formatetcs;
-    if (mimeData->hasImage() && mimeType == QLatin1String("application/x-qt-image")) {
-        //add DIBV5 if image has alpha channel
-        QImage image = qvariant_cast<QImage>(mimeData->imageData());
-        if (!image.isNull() && image.hasAlphaChannel())
-            formatetcs += setCf(CF_DIBV5);
-        formatetcs += setCf(CF_DIB);
-    }
-    return formatetcs;
-}
-
-QString QWindowsMimeImage::mimeForFormat(const FORMATETC &formatetc) const
-{
-    int cf = getCf(formatetc);
-    if (cf == CF_DIB || cf == CF_DIBV5 || cf == int(CF_PNG))
-       return QLatin1String("application/x-qt-image");
-    return QString();
-}
-
-bool QWindowsMimeImage::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
-    if ((mimeType == QLatin1String("application/x-qt-image")) &&
-        (canGetData(CF_DIB, pDataObj) || canGetData(CF_PNG, pDataObj)))
-        return true;
-    return false;
-}
-
-bool QWindowsMimeImage::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
-    int cf = getCf(formatetc);
-    if (mimeData->hasImage()) {
-        if (cf == CF_DIB)
-            return true;
-        else if (cf == CF_DIBV5) {
-            //support DIBV5 conversion only if the image has alpha channel
-            QImage image = qvariant_cast<QImage>(mimeData->imageData());
-            if (!image.isNull() && image.hasAlphaChannel())
-                return true;
-        }
-    }
-    return false;
-}
-
-bool QWindowsMimeImage::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-{
-    int cf = getCf(formatetc);
-    if ((cf == CF_DIB || cf == CF_DIBV5) && mimeData->hasImage()) {
-        QImage img = qvariant_cast<QImage>(mimeData->imageData());
-        if (img.isNull())
-            return false;
-        QByteArray ba;
-        QDataStream s(&ba, QIODevice::WriteOnly);
-        s.setByteOrder(QDataStream::LittleEndian);// Intel byte order ####
-        if (cf == CF_DIB) {
-            if (img.format() > QImage::Format_ARGB32)
-                img = img.convertToFormat(QImage::Format_RGB32);
-            if (qt_write_dib(s, img))
-                return setData(ba, pmedium);
-        } else {
-            if (qt_write_dibv5(s, img))
-                return setData(ba, pmedium);
-        }
-    }
-    return false;
-}
-
-bool QWindowsMimeImage::hasOriginalDIBV5(IDataObject *pDataObj) const
-{
-    bool isSynthesized = true;
-    IEnumFORMATETC *pEnum =NULL;
-    HRESULT res = pDataObj->EnumFormatEtc(1, &pEnum);
-    if (res == S_OK && pEnum) {
-        FORMATETC fc;
-        while ((res = pEnum->Next(1, &fc, 0)) == S_OK) {
-            if (fc.ptd)
-                CoTaskMemFree(fc.ptd);
-            if (fc.cfFormat == CF_DIB)
-                break;
-            else if (fc.cfFormat == CF_DIBV5) {
-                isSynthesized  = false;
-                break;
-            }
-        }
-        pEnum->Release();
-    }
-    return !isSynthesized;
-}
-
-QVariant QWindowsMimeImage::convertToMime(const QString &mimeType, IDataObject *pDataObj, QVariant::Type preferredType) const
-{
-    Q_UNUSED(preferredType);
-    QVariant result;
-    if (mimeType != QLatin1String("application/x-qt-image"))
-        return result;
-    //Try to convert from a format which has more data
-    //DIBV5, use only if its is not synthesized
-    if (canGetData(CF_DIBV5, pDataObj) && hasOriginalDIBV5(pDataObj)) {
-        QImage img;
-        QByteArray data = getData(CF_DIBV5, pDataObj);
-        QDataStream s(&data, QIODevice::ReadOnly);
-        s.setByteOrder(QDataStream::LittleEndian);
-        if (qt_read_dibv5(s, img)) { // #### supports only 32bit DIBV5
-            return img;
-        }
-    }
-    //PNG, MS Office place this (undocumented)
-    if (canGetData(CF_PNG, pDataObj)) {
-        QImage img;
-        QByteArray data = getData(CF_PNG, pDataObj);
-        if (img.loadFromData(data, "PNG")) {
-            return img;
-        }
-    }
-    //Fallback to DIB
-    if (canGetData(CF_DIB, pDataObj)) {
-        QImage img;
-        QByteArray data = getData(CF_DIB, pDataObj);
-        QDataStream s(&data, QIODevice::ReadOnly);
-        s.setByteOrder(QDataStream::LittleEndian);// Intel byte order ####
-        if (qt_read_dib(s, img)) { // ##### encaps "-14"
-            return img;
-        }
-    }
-    // Failed
-    return result;
-}
-#endif
-
-class QBuiltInMimes : public QWindowsMime
-{
-public:
-    QBuiltInMimes();
-
-    // for converting from Qt
-    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
-    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const;
-    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-
-    // for converting to Qt
-    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
-    QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const;
-    QString mimeForFormat(const FORMATETC &formatetc) const;
-
-private:
-    QMap<int, QString> outFormats;
-    QMap<int, QString> inFormats;
-};
-
-QBuiltInMimes::QBuiltInMimes()
-: QWindowsMime()
-{
-    outFormats.insert(QWindowsMime::registerMimeType(QLatin1String("application/x-color")), QLatin1String("application/x-color"));
-    inFormats.insert(QWindowsMime::registerMimeType(QLatin1String("application/x-color")), QLatin1String("application/x-color"));
-}
-
-bool QBuiltInMimes::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
-    // really check
-    return formatetc.tymed & TYMED_HGLOBAL
-        && outFormats.contains(formatetc.cfFormat)
-        && mimeData->formats().contains(outFormats.value(formatetc.cfFormat));
-}
-
-bool QBuiltInMimes::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-{
-    if (canConvertFromMime(formatetc, mimeData)) {
-        QByteArray data;
-        if (outFormats.value(getCf(formatetc)) == QLatin1String("text/html")) {
-            // text/html is in wide chars on windows (compatible with mozillia)
-            QString html = mimeData->html();
-            // same code as in the text converter up above
-            const QChar *u = html.unicode();
-            QString res;
-            const int s = html.length();
-            int maxsize = s + s/40 + 3;
-            res.resize(maxsize);
-            int ri = 0;
-            bool cr = false;
-            for (int i=0; i < s; ++i) {
-                if (*u == QLatin1Char('\r'))
-                    cr = true;
-                else {
-                    if (*u == QLatin1Char('\n') && !cr)
-                        res[ri++] = QLatin1Char('\r');
-                    cr = false;
-                }
-                res[ri++] = *u;
-                if (ri+3 >= maxsize) {
-                    maxsize += maxsize/4;
-                    res.resize(maxsize);
-                }
-                ++u;
-            }
-            res.truncate(ri);
-            const int byteLength = res.length() * sizeof(ushort);
-            QByteArray r(byteLength + 2, '\0');
-            memcpy(r.data(), res.unicode(), byteLength);
-            r[byteLength] = 0;
-            r[byteLength+1] = 0;
-            data = r;
-        } else {
-#ifndef QT_NO_DRAGANDDROP
-            data = QInternalMimeData::renderDataHelper(outFormats.value(getCf(formatetc)), mimeData);
-#endif //QT_NO_DRAGANDDROP
-        }
-        return setData(data, pmedium);
-    }
-    return false;
-}
-
-QVector<FORMATETC> QBuiltInMimes::formatsForMime(const QString &mimeType, const QMimeData *mimeData) const
-{
-    QVector<FORMATETC> formatetcs;
-    if (!outFormats.keys(mimeType).isEmpty() && mimeData->formats().contains(mimeType))
-        formatetcs += setCf(outFormats.key(mimeType));
-    return formatetcs;
-}
-
-bool QBuiltInMimes::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
-    return (!inFormats.keys(mimeType).isEmpty())
-        && canGetData(inFormats.key(mimeType), pDataObj);
-}
-
-QVariant QBuiltInMimes::convertToMime(const QString &mimeType, IDataObject *pDataObj, QVariant::Type preferredType) const
-{
-    QVariant val;
-    if (canConvertToMime(mimeType, pDataObj)) {
-        QByteArray data = getData(inFormats.key(mimeType), pDataObj);
-        if (!data.isEmpty()) {
-#ifdef QMIME_DEBUG
-            qDebug("QBuiltInMimes::convertToMime()");
-#endif
-            if (mimeType == QLatin1String("text/html") && preferredType == QVariant::String) {
-                // text/html is in wide chars on windows (compatible with Mozilla)
-                val = QString::fromWCharArray((const wchar_t *)data.data());
-            } else {
-                val = data; // it should be enough to return the data and let QMimeData do the rest.
-            }
-        }
-    }
-    return val;
-}
-
-QString QBuiltInMimes::mimeForFormat(const FORMATETC &formatetc) const
-{
-    return inFormats.value(getCf(formatetc));
-}
-
-
-class QLastResortMimes : public QWindowsMime
-{
-public:
-
-    QLastResortMimes();
-    // for converting from Qt
-    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const;
-    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const;
-    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const;
-
-    // for converting to Qt
-    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const;
-    QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const;
-    QString mimeForFormat(const FORMATETC &formatetc) const;
-
-private:
-    QMap<int, QString> formats;
-    static QStringList ianaTypes;
-    static QStringList excludeList;
-};
-
-QStringList QLastResortMimes::ianaTypes;
-QStringList QLastResortMimes::excludeList;
-
-QLastResortMimes::QLastResortMimes()
-{
-    //MIME Media-Types
-    if (!ianaTypes.size()) {
-        ianaTypes.append(QLatin1String("application/"));
-        ianaTypes.append(QLatin1String("audio/"));
-        ianaTypes.append(QLatin1String("example/"));
-        ianaTypes.append(QLatin1String("image/"));
-        ianaTypes.append(QLatin1String("message/"));
-        ianaTypes.append(QLatin1String("model/"));
-        ianaTypes.append(QLatin1String("multipart/"));
-        ianaTypes.append(QLatin1String("text/"));
-        ianaTypes.append(QLatin1String("video/"));
-    }
-    //Types handled by other classes
-    if (!excludeList.size()) {
-        excludeList.append(QLatin1String("HTML Format"));
-        excludeList.append(QLatin1String("UniformResourceLocator"));
-        excludeList.append(QLatin1String("text/html"));
-        excludeList.append(QLatin1String("text/plain"));
-        excludeList.append(QLatin1String("text/uri-list"));
-        excludeList.append(QLatin1String("application/x-qt-image"));
-        excludeList.append(QLatin1String("application/x-color"));
-    }
-}
-
-bool QLastResortMimes::canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const
-{
-    // really check
-#ifndef QT_NO_DRAGANDDROP
-    return formatetc.tymed & TYMED_HGLOBAL
-        && (formats.contains(formatetc.cfFormat)
-        && QInternalMimeData::hasFormatHelper(formats.value(formatetc.cfFormat), mimeData));
-#else
-    Q_UNUSED(mimeData);
-    Q_UNUSED(formatetc);
-    return formatetc.tymed & TYMED_HGLOBAL
-        && formats.contains(formatetc.cfFormat);
-#endif //QT_NO_DRAGANDDROP
-}
-
-bool QLastResortMimes::convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const
-{
-#ifndef QT_NO_DRAGANDDROP
-    return canConvertFromMime(formatetc, mimeData)
-        && setData(QInternalMimeData::renderDataHelper(formats.value(getCf(formatetc)), mimeData), pmedium);
-#else
-    Q_UNUSED(mimeData);
-    Q_UNUSED(formatetc);
-    Q_UNUSED(pmedium);
-    return false;
-#endif //QT_NO_DRAGANDDROP
-}
-
-QVector<FORMATETC> QLastResortMimes::formatsForMime(const QString &mimeType, const QMimeData * /*mimeData*/) const
-{
-    QVector<FORMATETC> formatetcs;
-    if (!formats.keys(mimeType).isEmpty()) {
-        formatetcs += setCf(formats.key(mimeType));
-    } else if (!excludeList.contains(mimeType, Qt::CaseInsensitive)){
-        // register any other available formats
-        int cf = QWindowsMime::registerMimeType(mimeType);
-        QLastResortMimes *that = const_cast<QLastResortMimes *>(this);
-        that->formats.insert(cf, mimeType);
-        formatetcs += setCf(cf);
-    }
-    return formatetcs;
-}
-static const char x_qt_windows_mime[] = "application/x-qt-windows-mime;value=\"";
-
-static bool isCustomMimeType(const QString &mimeType)
-{
-    return mimeType.startsWith(QLatin1String(x_qt_windows_mime), Qt::CaseInsensitive);
-}
-
-static QString customMimeType(const QString &mimeType)
-{
-    int len = sizeof(x_qt_windows_mime) - 1;
-    int n = mimeType.lastIndexOf(QLatin1Char('\"'))-len;
-    return mimeType.mid(len, n);
-}
-
-bool QLastResortMimes::canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const
-{
-    if (isCustomMimeType(mimeType)) {
-        QString clipFormat = customMimeType(mimeType);
-        int cf = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (clipFormat.utf16()));
-        return canGetData(cf, pDataObj);
-    } else if (formats.keys(mimeType).isEmpty()) {
-        // if it is not in there then register it an see if we can get it
-        int cf = QWindowsMime::registerMimeType(mimeType);
-        return canGetData(cf, pDataObj);
-    } else {
-        return canGetData(formats.key(mimeType), pDataObj);
-    }
-    return false;
-}
-
-QVariant QLastResortMimes::convertToMime(const QString &mimeType, IDataObject *pDataObj, QVariant::Type preferredType) const
-{
-    Q_UNUSED(preferredType);
-    QVariant val;
-    if (canConvertToMime(mimeType, pDataObj)) {
-        QByteArray data;
-        if (isCustomMimeType(mimeType)) {
-            QString clipFormat = customMimeType(mimeType);
-            int cf = RegisterClipboardFormat(reinterpret_cast<const wchar_t *> (clipFormat.utf16()));
-            data = getData(cf, pDataObj);
-        } else if (formats.keys(mimeType).isEmpty()) {
-            int cf = QWindowsMime::registerMimeType(mimeType);
-            data = getData(cf, pDataObj);
-        } else {
-            data = getData(formats.key(mimeType), pDataObj);
-        }
-        if (!data.isEmpty())
-            val = data; // it should be enough to return the data and let QMimeData do the rest.
-    }
-    return val;
-}
-
-QString QLastResortMimes::mimeForFormat(const FORMATETC &formatetc) const
-{
-    QString format = formats.value(getCf(formatetc));
-    if (!format.isEmpty())
-        return format;
-
-    wchar_t buffer[256];
-    int len = GetClipboardFormatName(getCf(formatetc), buffer, 256);
-
-    if (len) {
-        QString clipFormat = QString::fromWCharArray(buffer, len);
-#ifndef QT_NO_DRAGANDDROP
-        if (QInternalMimeData::canReadData(clipFormat))
-            format = clipFormat;
-        else if((formatetc.cfFormat >= 0xC000)){
-            //create the mime as custom. not registered.
-            if (!excludeList.contains(clipFormat, Qt::CaseInsensitive)) {
-                //check if this is a mime type
-                bool ianaType = false;
-                int sz = ianaTypes.size();
-                for (int i = 0; i < sz; i++) {
-                    if (clipFormat.startsWith(ianaTypes[i], Qt::CaseInsensitive)) {
-                        ianaType =  true;
-                        break;
-                    }
-                }
-                if (!ianaType)
-                    format = QLatin1String(x_qt_windows_mime) + clipFormat + QLatin1Char('\"');
-                else
-                    format = clipFormat;
-            }
-        }
-#endif //QT_NO_DRAGANDDROP
-    }
-
-    return format;
-}
-
-QWindowsMimeList::QWindowsMimeList()
-    : initialized(false)
-{
-}
-
-QWindowsMimeList::~QWindowsMimeList()
-{
-    while (mimes.size())
-        delete mimes.first();
-}
-
-
-void QWindowsMimeList::init()
-{
-    if (!initialized) {
-        initialized = true;
-#ifndef QT_NO_IMAGEFORMAT_BMP
-        new QWindowsMimeImage;
-#endif
-        new QLastResortMimes;
-        new QWindowsMimeText;
-        new QWindowsMimeURI;
-
-        new QWindowsMimeHtml;
-        new QBuiltInMimes;
-    }
-}
-
-void QWindowsMimeList::addWindowsMime(QWindowsMime * mime)
-{
-    init();
-    mimes.append(mime);
-}
-
-void QWindowsMimeList::removeWindowsMime(QWindowsMime * mime)
-{
-    init();
-    mimes.removeAll(mime);
-}
-
-QList<QWindowsMime*> QWindowsMimeList::windowsMimes()
-{
-    init();
-    return mimes;
-}
-
-#ifndef QT_NO_IMAGEFORMAT_BMP
-static bool qt_write_dibv5(QDataStream &s, QImage image)
-{
-    QIODevice* d = s.device();
-    if (!d->isWritable())
-        return false;
-
-    //depth will be always 32
-    int bpl_bmp = image.width()*4;
-
-    BMP_BITMAPV5HEADER bi ={0};
-    bi.bV5Size          = sizeof(BMP_BITMAPV5HEADER);
-    bi.bV5Width         = image.width();
-    bi.bV5Height        = image.height();
-    bi.bV5Planes        = 1;
-    bi.bV5BitCount      = 32;
-    bi.bV5Compression   = BI_BITFIELDS;
-    bi.bV5SizeImage     = bpl_bmp*image.height();
-    bi.bV5XPelsPerMeter = 0;
-    bi.bV5YPelsPerMeter = 0;
-    bi.bV5ClrUsed       = 0;
-    bi.bV5ClrImportant  = 0;
-    bi.bV5BlueMask      = 0x000000ff;
-    bi.bV5GreenMask     = 0x0000ff00;
-    bi.bV5RedMask       = 0x00ff0000;
-    bi.bV5AlphaMask     = 0xff000000;
-    bi.bV5CSType        = BMP_LCS_sRGB;         //LCS_sRGB
-    bi.bV5Intent        = BMP_LCS_GM_IMAGES;    //LCS_GM_IMAGES
-
-    d->write(reinterpret_cast<const char*>(&bi), bi.bV5Size);
-    if (s.status() != QDataStream::Ok)
-        return false;
-
-    DWORD colorSpace[3] = {0x00ff0000,0x0000ff00,0x000000ff};
-    d->write(reinterpret_cast<const char*>(colorSpace), sizeof(colorSpace));
-    if (s.status() != QDataStream::Ok)
-        return false;
-
-    if (image.format() != QImage::Format_ARGB32)
-        image = image.convertToFormat(QImage::Format_ARGB32);
-
-    uchar *buf = new uchar[bpl_bmp];
-    uchar *b;
-
-    memset(buf, 0, bpl_bmp);
-    for (int y=image.height()-1; y>=0; y--) {
-        // write the image bits
-        QRgb *p = (QRgb *)image.scanLine(y);
-        QRgb *end = p + image.width();
-        b = buf;
-        while (p < end) {
-            int alpha = qAlpha(*p);
-            if (alpha) {
-                *b++ = qBlue(*p);
-                *b++ = qGreen(*p);
-                *b++ = qRed(*p);
-            } else {
-                //white for fully transparent pixels.
-                *b++ = 0xff;
-                *b++ = 0xff;
-                *b++ = 0xff;
-            }
-            *b++ = alpha;
-            p++;
-        }
-        d->write((char*)buf, bpl_bmp);
-        if (s.status() != QDataStream::Ok) {
-            delete[] buf;
-            return false;
-        }
-    }
-    delete[] buf;
-    return true;
-}
-
-static int calc_shift(int mask)
-{
-    int result = 0;
-    while (!(mask & 1)) {
-        result++;
-        mask >>= 1;
-    }
-    return result;
-}
-
-//Supports only 32 bit DIBV5
-static bool qt_read_dibv5(QDataStream &s, QImage &image)
-{
-    BMP_BITMAPV5HEADER bi;
-    QIODevice* d = s.device();
-    if (d->atEnd())
-        return false;
-
-    d->read((char *)&bi, sizeof(bi));   // read BITMAPV5HEADER header
-    if (s.status() != QDataStream::Ok)
-        return false;
-
-    int nbits = bi.bV5BitCount;
-    int comp = bi.bV5Compression;
-    if (nbits != 32 || bi.bV5Planes != 1 || comp != BMP_BITFIELDS)
-        return false; //Unsupported DIBV5 format
-
-    int w = bi.bV5Width, h = bi.bV5Height;
-    int red_mask = bi.bV5RedMask;
-    int green_mask = bi.bV5GreenMask;
-    int blue_mask = bi.bV5BlueMask;
-    int alpha_mask = bi.bV5AlphaMask;
-    int red_shift = 0;
-    int green_shift = 0;
-    int blue_shift = 0;
-    int alpha_shift = 0;
-    QImage::Format format = QImage::Format_ARGB32;
-
-    if (bi.bV5Height < 0)
-        h = -h;     // support images with negative height
-    if (image.size() != QSize(w, h) || image.format() != format) {
-        image = QImage(w, h, format);
-        if (image.isNull())     // could not create image
-            return false;
-    }
-    image.setDotsPerMeterX(bi.bV5XPelsPerMeter);
-    image.setDotsPerMeterY(bi.bV5YPelsPerMeter);
-    // read color table
-    DWORD colorSpace[3];
-    if (d->read((char *)colorSpace, sizeof(colorSpace)) != sizeof(colorSpace))
-        return false;
-
-    red_shift = calc_shift(red_mask);
-    green_shift = calc_shift(green_mask);
-    blue_shift = calc_shift(blue_mask);
-    if (alpha_mask) {
-        alpha_shift = calc_shift(alpha_mask);
-    }
-
-    int  bpl = image.bytesPerLine();
-    uchar *data = image.bits();
-    register QRgb *p;
-    QRgb  *end;
-    uchar *buf24 = new uchar[bpl];
-    int    bpl24 = ((w*nbits+31)/32)*4;
-    uchar *b;
-    unsigned int c;
-
-    while (--h >= 0) {
-        p = (QRgb *)(data + h*bpl);
-        end = p + w;
-        if (d->read((char *)buf24,bpl24) != bpl24)
-            break;
-        b = buf24;
-        while (p < end) {
-            c = *b | (*(b+1))<<8 | (*(b+2))<<16 | (*(b+3))<<24;
-            *p++ = qRgba(((c & red_mask) >> red_shift) ,
-                                    ((c & green_mask) >> green_shift),
-                                    ((c & blue_mask) >> blue_shift),
-                                    ((c & alpha_mask) >> alpha_shift));
-            b += 4;
-        }
-    }
-    delete[] buf24;
-
-    if (bi.bV5Height < 0) {
-        // Flip the image
-        uchar *buf = new uchar[bpl];
-        h = -bi.bV5Height;
-        for (int y = 0; y < h/2; ++y) {
-            memcpy(buf, data + y*bpl, bpl);
-            memcpy(data + y*bpl, data + (h-y-1)*bpl, bpl);
-            memcpy(data + (h-y-1)*bpl, buf, bpl);
-        }
-        delete [] buf;
-    }
-
-    return true;
-}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qmultitouch_mac.mm b/src/gui/kernel/qmultitouch_mac.mm
deleted file mode 100644 (file)
index 197bbaa..0000000
+++ /dev/null
@@ -1,218 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qmultitouch_mac_p.h>
-#include <qcursor.h>
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-
-QHash<qint64, QCocoaTouch*> QCocoaTouch::_currentTouches;
-QPointF QCocoaTouch::_screenReferencePos;
-QPointF QCocoaTouch::_trackpadReferencePos;
-int QCocoaTouch::_idAssignmentCount = 0;
-int QCocoaTouch::_touchCount = 0;
-bool QCocoaTouch::_updateInternalStateOnly = true;
-
-QCocoaTouch::QCocoaTouch(NSTouch *nstouch)
-{
-    if (_currentTouches.size() == 0)
-        _idAssignmentCount = 0;
-
-    _touchPoint.setId(_idAssignmentCount++);
-    _touchPoint.setPressure(1.0);
-    _identity = qint64([nstouch identity]);
-    _currentTouches.insert(_identity, this);
-    updateTouchData(nstouch, NSTouchPhaseBegan);
-}
-
-QCocoaTouch::~QCocoaTouch()
-{
-    _currentTouches.remove(_identity);
-}
-
-void QCocoaTouch::updateTouchData(NSTouch *nstouch, NSTouchPhase phase)
-{
-    if (_touchCount == 1)
-        _touchPoint.setState(toTouchPointState(phase) | Qt::TouchPointPrimary);
-    else
-        _touchPoint.setState(toTouchPointState(phase));
-
-    // From the normalized position on the trackpad, calculate
-    // where on screen the touchpoint should be according to the
-    // reference position:
-    NSPoint npos = [nstouch normalizedPosition];
-    QPointF qnpos = QPointF(npos.x, 1 - npos.y);
-    _touchPoint.setNormalizedPos(qnpos);
-
-    if (_touchPoint.id() == 0 && phase == NSTouchPhaseBegan) {
-        _trackpadReferencePos = qnpos;
-        _screenReferencePos = QCursor::pos();
-    }
-
-    NSSize dsize = [nstouch deviceSize];
-    float ppiX = (qnpos.x() - _trackpadReferencePos.x()) * dsize.width;
-    float ppiY = (qnpos.y() - _trackpadReferencePos.y()) * dsize.height;
-    QPointF relativePos = _trackpadReferencePos - QPointF(ppiX, ppiY);
-    _touchPoint.setScreenPos(_screenReferencePos - relativePos);
-}
-
-QCocoaTouch *QCocoaTouch::findQCocoaTouch(NSTouch *nstouch)
-{
-    qint64 identity = qint64([nstouch identity]);
-    if (_currentTouches.contains(identity))
-        return _currentTouches.value(identity);
-    return 0;
-}
-
-Qt::TouchPointState QCocoaTouch::toTouchPointState(NSTouchPhase nsState)
-{
-    Qt::TouchPointState qtState = Qt::TouchPointReleased;
-    switch (nsState) {
-        case NSTouchPhaseBegan:
-            qtState = Qt::TouchPointPressed;
-            break;
-        case NSTouchPhaseMoved:
-            qtState = Qt::TouchPointMoved;
-            break;
-        case NSTouchPhaseStationary:
-            qtState = Qt::TouchPointStationary;
-            break;
-        case NSTouchPhaseEnded:
-        case NSTouchPhaseCancelled:
-            qtState = Qt::TouchPointReleased;
-            break;
-        default:
-            break;
-    }
-    return qtState;
-}
-
-QList<QTouchEvent::TouchPoint>
-QCocoaTouch::getCurrentTouchPointList(NSEvent *event, bool acceptSingleTouch)
-{
-    QMap<int, QTouchEvent::TouchPoint> touchPoints;
-    NSSet *ended = [event touchesMatchingPhase:NSTouchPhaseEnded | NSTouchPhaseCancelled inView:nil];
-    NSSet *active = [event
-        touchesMatchingPhase:NSTouchPhaseBegan | NSTouchPhaseMoved | NSTouchPhaseStationary
-        inView:nil];
-    _touchCount = [active count];
-
-    // First: remove touches that were ended by the user. If we are
-    // currently not accepting single touches, a corresponding 'begin'
-    // has never been send to the app for these events.
-    // So should therefore not send the following removes either.
-
-    for (int i=0; i<int([ended count]); ++i) {
-        NSTouch *touch = [[ended allObjects] objectAtIndex:i];
-        QCocoaTouch *qcocoaTouch = findQCocoaTouch(touch);
-        if (qcocoaTouch) {
-            qcocoaTouch->updateTouchData(touch, [touch phase]);
-            if (!_updateInternalStateOnly)
-                touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint);
-            delete qcocoaTouch;
-        }
-    }
-
-    bool wasUpdateInternalStateOnly = _updateInternalStateOnly;
-    _updateInternalStateOnly = !acceptSingleTouch && _touchCount < 2;
-
-    // Next: update, or create, existing touches.
-    // We always keep track of all touch points, even
-    // when not accepting single touches.
-
-    for (int i=0; i<int([active count]); ++i) {
-        NSTouch *touch = [[active allObjects] objectAtIndex:i];
-        QCocoaTouch *qcocoaTouch = findQCocoaTouch(touch);
-        if (!qcocoaTouch)
-            qcocoaTouch = new QCocoaTouch(touch);
-        else
-            qcocoaTouch->updateTouchData(touch, wasUpdateInternalStateOnly ? NSTouchPhaseBegan : [touch phase]);
-        if (!_updateInternalStateOnly)
-            touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint);
-    }
-
-    // Next: sadly, we need to check that our touch hash is in
-    // sync with cocoa. This is typically not the case after a system
-    // gesture happend (like a four-finger-swipe to show expose).
-
-    if (_touchCount != _currentTouches.size()) {
-        // Remove all instances, and basically start from scratch:
-        touchPoints.clear();
-        foreach (QCocoaTouch *qcocoaTouch, _currentTouches.values()) {
-            if (!_updateInternalStateOnly) {
-                qcocoaTouch->_touchPoint.setState(Qt::TouchPointReleased);
-                touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint);
-            }
-            delete qcocoaTouch;
-        }
-        _currentTouches.clear();
-        _updateInternalStateOnly = !acceptSingleTouch;
-        return touchPoints.values();
-    }
-
-    // Finally: If this call _started_ to reject single
-    // touches, we need to fake a relase for the remaining
-    // touch now (and refake a begin for it later, if needed).
-
-    if (_updateInternalStateOnly && !wasUpdateInternalStateOnly && !_currentTouches.isEmpty()) {
-        QCocoaTouch *qcocoaTouch = _currentTouches.values().first();
-        qcocoaTouch->_touchPoint.setState(Qt::TouchPointReleased);
-        touchPoints.insert(qcocoaTouch->_touchPoint.id(), qcocoaTouch->_touchPoint);
-        // Since this last touch also will end up beeing the first
-        // touch (if the user adds a second finger without lifting
-        // the first), we promote it to be the primary touch:
-        qcocoaTouch->_touchPoint.setId(0);
-        _idAssignmentCount = 1;
-    }
-
-    return touchPoints.values();
-}
-
-#endif
-
-QT_END_NAMESPACE
-
-#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
diff --git a/src/gui/kernel/qmultitouch_mac_p.h b/src/gui/kernel/qmultitouch_mac_p.h
deleted file mode 100644 (file)
index bd30295..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 QMULTITOUCH_MAC_P_H
-#define QMULTITOUCH_MAC_P_H
-
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-#endif
-
-#include <qevent.h>
-#include <qhash.h>
-#include <QtCore>
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-
-class QCocoaTouch
-{
-    public:
-        static QList<QTouchEvent::TouchPoint> getCurrentTouchPointList(NSEvent *event, bool acceptSingleTouch);
-        static void setMouseInDraggingState(bool inDraggingState);
-
-    private:
-        static QHash<qint64, QCocoaTouch*> _currentTouches;
-        static QPointF _screenReferencePos;
-        static QPointF _trackpadReferencePos;
-        static int _idAssignmentCount;
-        static int _touchCount;
-        static bool _updateInternalStateOnly;
-
-        QTouchEvent::TouchPoint _touchPoint;
-        qint64 _identity;
-
-        QCocoaTouch(NSTouch *nstouch);
-        ~QCocoaTouch();
-
-        void updateTouchData(NSTouch *nstouch, NSTouchPhase phase);
-        static QCocoaTouch *findQCocoaTouch(NSTouch *nstouch);
-        static Qt::TouchPointState toTouchPointState(NSTouchPhase nsState);
-};
-
-#endif // QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
-
-#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-
-#endif // QMULTITOUCH_MAC_P_H
-
diff --git a/src/gui/kernel/qnsframeview_mac_p.h b/src/gui/kernel/qnsframeview_mac_p.h
deleted file mode 100644 (file)
index 671d68c..0000000
+++ /dev/null
@@ -1,154 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
-// and many other.  This header file may change from version to version
-// without notice, or even be removed.
-//
-// We mean it.
-//
-
-// Private AppKit class (dumped from classdump).
-
-#import <Cocoa/Cocoa.h>
-
-@interface NSFrameView : NSView
-{
-    unsigned int styleMask;
-    NSString *_title;
-    NSCell *titleCell;
-    NSButton *closeButton;
-    NSButton *zoomButton;
-    NSButton *minimizeButton;
-    char resizeByIncrement;
-    char frameNeedsDisplay;
-    unsigned char tabViewCount;
-    NSSize resizeParameter;
-    int shadowState;
-}
-
-+ (void)initialize;
-+ (void)initTitleCell:fp8 styleMask:(unsigned int)fp12;
-+ (struct _NSRect)frameRectForContentRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24;
-+ (struct _NSRect)contentRectForFrameRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24;
-+ (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-+ (struct _NSSize)minContentSizeForMinFrameSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-+ (float)minFrameWidthWithTitle:fp8 styleMask:(unsigned int)fp12;
-+ (unsigned int)_validateStyleMask:(unsigned int)fp8;
-- initWithFrame:(struct _NSRect)fp8 styleMask:(unsigned int)fp24 owner:fp28;
-- initWithFrame:(struct _NSRect)fp8;
-- (void)dealloc;
-- (void)shapeWindow;
-- (void)tileAndSetWindowShape:(char)fp8;
-- (void)tile;
-- (void)drawRect:(struct _NSRect)fp8;
-- (void)_drawFrameRects:(struct _NSRect)fp8;
-- (void)drawFrame:(struct _NSRect)fp8;
-- (void)drawThemeContentFill:(struct _NSRect)fp8 inView:fp24;
-- (void)drawWindowBackgroundRect:(struct _NSRect)fp8;
-- (void)drawWindowBackgroundRegion:(void *)fp8;
-- (float)contentAlpha;
-- (void)_windowChangedKeyState;
-- (void)_updateButtonState;
-- (char)_isSheet;
-- (char)_isUtility;
-- (void)setShadowState:(int)fp8;
-- (int)shadowState;
-- (char)_canHaveToolbar;
-- (char)_toolbarIsInTransition;
-- (char)_toolbarIsShown;
-- (char)_toolbarIsHidden;
-- (void)_showToolbarWithAnimation:(char)fp8;
-- (void)_hideToolbarWithAnimation:(char)fp8;
-- (float)_distanceFromToolbarBaseToTitlebar;
-- (int)_shadowType;
-- (unsigned int)_shadowFlags;
-- (void)_setShadowParameters;
-- (void)_drawFrameShadowAndFlushContext:fp8;
-- (void)setUpGState;
-- (void)adjustHalftonePhase;
-- (void)systemColorsDidChange:fp8;
-- frameColor;
-- contentFill;
-- (void)tabViewAdded;
-- (void)tabViewRemoved;
-- title;
-- (void)setTitle:fp8;
-- titleCell;
-- (void)initTitleCell:fp8;
-- (void)setResizeIncrements:(struct _NSSize)fp8;
-- (struct _NSSize)resizeIncrements;
-- (void)setAspectRatio:(struct _NSSize)fp8;
-- (struct _NSSize)aspectRatio;
-- (unsigned int)styleMask;
-- representedFilename;
-- (void)setRepresentedFilename:fp8;
-- (void)setDocumentEdited:(char)fp8;
-- (void)_setFrameNeedsDisplay:(char)fp8;
-- (char)frameNeedsDisplay;
-- titleFont;
-- (struct _NSRect)_maxTitlebarTitleRect;
-- (struct _NSRect)titlebarRect;
-- (void)_setUtilityWindow:(char)fp8;
-- (void)_setNonactivatingPanel:(char)fp8;
-- (void)setIsClosable:(char)fp8;
-- (void)setIsResizable:(char)fp8;
-- closeButton;
-- minimizeButton;
-- zoomButton;
-- (struct _NSSize)miniaturizedSize;
-- (void)_clearDragMargins;
-- (void)_resetDragMargins;
-- (void)setTitle:fp8 andDefeatWrap:(char)fp12;
-- (struct _NSRect)frameRectForContentRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24;
-- (struct _NSRect)contentRectForFrameRect:(struct _NSRect)fp8 styleMask:(unsigned int)fp24;
-- (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-- (struct _NSRect)dragRectForFrameRect:(struct _NSRect)fp8;
-- (struct _NSRect)contentRect;
-- (struct _NSSize)minFrameSize;
-- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(struct _NSRect)fp8 isVisibleRect:(char)fp24 rectIsVisibleRectForView:fp28 topView:(char)fp32;
-
-@end
diff --git a/src/gui/kernel/qnsthemeframe_mac_p.h b/src/gui/kernel/qnsthemeframe_mac_p.h
deleted file mode 100644 (file)
index 572a56f..0000000
+++ /dev/null
@@ -1,246 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
-// and many other.  This header file may change from version to version
-// without notice, or even be removed.
-//
-// We mean it.
-//
-
-// Private AppKit class (dumped from classdump).
-
-#import <Cocoa/Cocoa.h>
-#import "qnstitledframe_mac_p.h"
-
-@interface NSThemeFrame : NSTitledFrame
-{
-    NSButton *toolbarButton;
-    int toolbarVisibleStatus;
-    NSImage *showToolbarTransitionImage;
-    NSSize showToolbarPreWindowSize;
-    NSButton *modeButton;
-    int leftGroupTrackingTagNum;
-    int rightGroupTrackingTagNum;
-    char mouseInsideLeftGroup;
-    char mouseInsideRightGroup;
-    int widgetState;
-    NSString *displayName;
-}
-
-+ (void)initialize;
-+ (float)_windowBorderThickness:(unsigned int)fp8;
-+ (float)_minXWindowBorderWidth:(unsigned int)fp8;
-+ (float)_maxXWindowBorderWidth:(unsigned int)fp8;
-+ (float)_minYWindowBorderHeight:(unsigned int)fp8;
-+ (float)_windowTitlebarButtonSpacingWidth:(unsigned int)fp8;
-+ (float)_windowFileButtonSpacingWidth:(unsigned int)fp8;
-+ (float)_minXTitlebarWidgetInset:(unsigned int)fp8;
-+ (float)_maxXTitlebarWidgetInset:(unsigned int)fp8;
-+ (float)minFrameWidthWithTitle:fp8 styleMask:(unsigned int)fp12;
-+ (float)_windowSideTitlebarTitleMinWidth:(unsigned int)fp8;
-+ (float)_windowTitlebarTitleMinHeight:(unsigned int)fp8;
-+ (float)_sideTitlebarWidth:(unsigned int)fp8;
-+ (float)_titlebarHeight:(unsigned int)fp8;
-+ (float)_resizeHeight:(unsigned int)fp8;
-+ (char)_resizeFromEdge;
-+ (struct _NSSize)sizeOfTitlebarButtons:(unsigned int)fp8;
-+ (float)_contentToFrameMinXWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMaxXWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMinYHeight:(unsigned int)fp8;
-+ (float)_contentToFrameMaxYHeight:(unsigned int)fp8;
-+ (unsigned int)_validateStyleMask:(unsigned int)fp8;
-- (struct _NSSize)_topCornerSize;
-- (struct _NSSize)_bottomCornerSize;
-- (void *)_createWindowOpaqueShape;
-- (void)shapeWindow;
-- (void)_recursiveDisplayRectIfNeededIgnoringOpacity:(NSRect)fp8 isVisibleRect:(char)fp24 rectIsVisibleRectForView:fp28 topView:(char)fp32;
-- (void *)_regionForOpaqueDescendants:(NSRect)fp8 forMove:(char)fp24;
-- (void)_drawFrameInterior:(NSRect *)fp8 clip:(NSRect)fp12;
-- (void)_setTextShadow:(char)fp8;
-- (void)_drawTitleBar:(NSRect)fp8;
-- (void)_drawResizeIndicators:(NSRect)fp8;
-- (void)_drawFrameRects:(NSRect)fp8;
-- (void)drawFrame:(NSRect)fp8;
-- contentFill;
-- (void)viewDidEndLiveResize;
-- (float)contentAlpha;
-- (void)setThemeFrameWidgetState:(int)fp8;
-- (char)constrainResizeEdge:(int *)fp8 withDelta:(struct _NSSize)fp12 elapsedTime:(float)fp20;
-- (void)addFileButton:fp8;
-- (void)_updateButtons;
-- (void)_updateButtonState;
-- newCloseButton;
-- newZoomButton;
-- newMiniaturizeButton;
-- newToolbarButton;
-- newFileButton;
-- (void)_resetTitleBarButtons;
-- (void)setDocumentEdited:(char)fp8;
-- toolbarButton;
-- modeButton;
-- initWithFrame:(NSRect)fp8 styleMask:(unsigned int)fp24 owner:fp28;
-- (void)dealloc;
-- (void)setFrameSize:(struct _NSSize)fp8;
-- (char)_canHaveToolbar;
-- (char)_toolbarIsInTransition;
-- (char)_toolbarIsShown;
-- (char)_toolbarIsHidden;
-- _toolbarView;
-- _toolbar;
-- (float)_distanceFromToolbarBaseToTitlebar;
-- (unsigned int)_shadowFlags;
-- (NSRect)frameRectForContentRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
-- (NSRect)contentRectForFrameRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
-- (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-- (NSRect)contentRect;
-- (NSRect)_contentRectExcludingToolbar;
-- (NSRect)_contentRectIncludingToolbarAtHome;
-- (void)_setToolbarShowHideResizeWeightingOptimizationOn:(char)fp8;
-- (char)_usingToolbarShowHideWeightingOptimization;
-- (void)handleSetFrameCommonRedisplay;
-- (void)_startLiveResizeAsTopLevel;
-- (void)_endLiveResizeAsTopLevel;
-- (void)_growContentReshapeContentAndToolbarView:(int)fp8 animate:(char)fp12;
-- (char)_growWindowReshapeContentAndToolbarView:(int)fp8 animate:(char)fp12;
-- (void)_reshapeContentAndToolbarView:(int)fp8 resizeWindow:(char)fp12 animate:(char)fp16;
-- (void)_toolbarFrameSizeChanged:fp8 oldSize:(struct _NSSize)fp12;
-- (void)_syncToolbarPosition;
-- (void)_showHideToolbar:(int)fp8 resizeWindow:(char)fp12 animate:(char)fp16;
-- (void)_showToolbarWithAnimation:(char)fp8;
-- (void)_hideToolbarWithAnimation:(char)fp8;
-- (void)_drawToolbarTransitionIfNecessary;
-- (void)drawRect:(NSRect)fp8;
-- (void)resetCursorRects;
-- (char)shouldBeTreatedAsInkEvent:fp8;
-- (char)_shouldBeTreatedAsInkEventInInactiveWindow:fp8;
-//- hitTest:(struct _NSPoint)fp8; // collides with hittest in qcocoasharedwindowmethods_mac_p.h
-- (NSRect)_leftGroupRect;
-- (NSRect)_rightGroupRect;
-- (void)_updateWidgets;
-- (void)_updateMouseTracking;
-- (void)mouseEntered:fp8;
-- (void)mouseExited:fp8;
-- (void)_setMouseEnteredGroup:(char)fp8 entered:(char)fp12;
-- (char)_mouseInGroup:fp8;
-- (struct _NSSize)miniaturizedSize;
-- (float)_minXTitlebarDecorationMinWidth;
-- (float)_maxXTitlebarDecorationMinWidth;
-- (struct _NSSize)minFrameSize;
-- (float)_windowBorderThickness;
-- (float)_windowTitlebarXResizeBorderThickness;
-- (float)_windowTitlebarYResizeBorderThickness;
-- (float)_windowResizeBorderThickness;
-- (float)_minXWindowBorderWidth;
-- (float)_maxXWindowBorderWidth;
-- (float)_minYWindowBorderHeight;
-- (float)_maxYWindowBorderHeight;
-- (float)_minYTitlebarButtonsOffset;
-- (float)_minYTitlebarTitleOffset;
-- (float)_sideTitlebarWidth;
-- (float)_titlebarHeight;
-- (NSRect)_titlebarTitleRect;
-- (NSRect)titlebarRect;
-- (float)_windowTitlebarTitleMinHeight;
-- (struct _NSSize)_sizeOfTitlebarFileButton;
-- (struct _NSSize)sizeOfTitlebarToolbarButton;
-- (float)_windowTitlebarButtonSpacingWidth;
-- (float)_windowFileButtonSpacingWidth;
-- (float)_minXTitlebarWidgetInset;
-- (float)_maxXTitlebarWidgetInset;
-- (float)_minXTitlebarButtonsWidth;
-- (float)_maxXTitlebarButtonsWidth;
-- (struct _NSPoint)_closeButtonOrigin;
-- (struct _NSPoint)_zoomButtonOrigin;
-- (struct _NSPoint)_collapseButtonOrigin;
-- (struct _NSPoint)_toolbarButtonOrigin;
-- (struct _NSPoint)_fileButtonOrigin;
-- (void)_tileTitlebar;
-- (NSRect)_commandPopupRect;
-- (void)_resetDragMargins;
-- (float)_maxYTitlebarDragHeight;
-- (float)_minXTitlebarDragWidth;
-- (float)_maxXTitlebarDragWidth;
-- (float)_contentToFrameMinXWidth;
-- (float)_contentToFrameMaxXWidth;
-- (float)_contentToFrameMinYHeight;
-- (float)_contentToFrameMaxYHeight;
-- (float)_windowResizeCornerThickness;
-- (NSRect)_minYResizeRect;
-- (NSRect)_minYminXResizeRect;
-- (NSRect)_minYmaxXResizeRect;
-- (NSRect)_minXResizeRect;
-- (NSRect)_minXminYResizeRect;
-- (NSRect)_minXmaxYResizeRect;
-- (NSRect)_maxYResizeRect;
-- (NSRect)_maxYminXResizeRect;
-- (NSRect)_maxYmaxXResizeRect;
-- (NSRect)_maxXResizeRect;
-- (NSRect)_maxXminYResizeRect;
-- (NSRect)_maxXmaxYResizeRect;
-- (NSRect)_minXTitlebarResizeRect;
-- (NSRect)_maxXTitlebarResizeRect;
-- (NSRect)_minXBorderRect;
-- (NSRect)_maxXBorderRect;
-- (NSRect)_maxYBorderRect;
-- (NSRect)_minYBorderRect;
-- (void)_setUtilityWindow:(char)fp8;
-- (char)_isUtility;
-- (float)_sheetHeightAdjustment;
-- (void)_setSheet:(char)fp8;
-- (char)_isSheet;
-- (char)_isResizable;
-- (char)_isClosable;
-- (char)_isMiniaturizable;
-- (char)_hasToolbar;
-- (NSRect)_growBoxRect;
-- (void)_drawGrowBoxWithClip:(NSRect)fp8;
-- (char)_inactiveButtonsNeedMask;
-- (void)mouseDown:fp8;
-- _displayName;
-- (void)_setDisplayName:fp8;
-
-@end
diff --git a/src/gui/kernel/qnstitledframe_mac_p.h b/src/gui/kernel/qnstitledframe_mac_p.h
deleted file mode 100644 (file)
index 468ae3b..0000000
+++ /dev/null
@@ -1,205 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
-// and many other.  This header file may change from version to version
-// without notice, or even be removed.
-//
-// We mean it.
-//
-
-// Private AppKit class (dumped from classdump).
-
-#import <Cocoa/Cocoa.h>
-#import "qnsframeview_mac_p.h"
-
-
-@interface NSTitledFrame : NSFrameView
-{
-    int resizeFlags;
-    id fileButton;      /* NSDocumentDragButton* */
-    NSSize titleCellSize;
-}
-
-+ (float)_windowBorderThickness:(unsigned int)fp8;
-+ (float)_minXWindowBorderWidth:(unsigned int)fp8;
-+ (float)_maxXWindowBorderWidth:(unsigned int)fp8;
-+ (float)_minYWindowBorderHeight:(unsigned int)fp8;
-+ (char)_resizeFromEdge;
-+ (NSRect)frameRectForContentRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
-+ (NSRect)contentRectForFrameRect:(NSRect)fp8 styleMask:(unsigned int)fp24;
-+ (struct _NSSize)minFrameSizeForMinContentSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-+ (struct _NSSize)minContentSizeForMinFrameSize:(struct _NSSize)fp8 styleMask:(unsigned int)fp16;
-+ (float)minFrameWidthWithTitle:fp8 styleMask:(unsigned int)fp12;
-+ (struct _NSSize)_titleCellSizeForTitle:fp8 styleMask:(unsigned int)fp12;
-+ (float)_titleCellHeight:(unsigned int)fp8;
-+ (float)_windowTitlebarTitleMinHeight:(unsigned int)fp8;
-+ (float)_titlebarHeight:(unsigned int)fp8;
-+ (struct _NSSize)sizeOfTitlebarButtons:(unsigned int)fp8;
-+ (float)windowTitlebarLinesSpacingWidth:(unsigned int)fp8;
-+ (float)windowTitlebarTitleLinesSpacingWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMinXWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMaxXWidth:(unsigned int)fp8;
-+ (float)_contentToFrameMinYHeight:(unsigned int)fp8;
-+ (float)_contentToFrameMaxYHeight:(unsigned int)fp8;
-- initWithFrame:(NSRect)fp8 styleMask:(unsigned int)fp24 owner:fp28;
-- (void)dealloc;
-- (void)setIsClosable:(char)fp8;
-- (void)setIsResizable:(char)fp8;
-- (void)_resetTitleFont;
-- (void)_setUtilityWindow:(char)fp8;
-- (char)isOpaque;
-- (char)worksWhenModal;
-- (void)propagateFrameDirtyRects:(NSRect)fp8;
-- (void)_showDrawRect:(NSRect)fp8;
-- (void)_drawFrameInterior:(NSRect *)fp8 clip:(NSRect)fp12;
-- (void)drawFrame:(NSRect)fp8;
-- (void)_drawFrameRects:(NSRect)fp8;
-- (void)_drawTitlebar:(NSRect)fp8;
-- (void)_drawTitlebarPattern:(int)fp8 inRect:(NSRect)fp12 clippedByRect:(NSRect)fp28 forKey:(char)fp44 alignment:(int)fp48;
-- (void)_drawTitlebarLines:(int)fp8 inRect:(NSRect)fp12 clippedByRect:(NSRect)fp28;
-- frameHighlightColor;
-- frameShadowColor;
-- (void)setFrameSize:(struct _NSSize)fp8;
-- (void)setFrameOrigin:(struct _NSPoint)fp8;
-- (void)tileAndSetWindowShape:(char)fp8;
-- (void)tile;
-- (void)_tileTitlebar;
-- (void)setTitle:fp8;
-- (char)_shouldRepresentFilename;
-- (void)setRepresentedFilename:fp8;
-- (void)_drawTitleStringIn:(NSRect)fp8 withColor:fp24;
-- titleFont;
-- (void)_drawResizeIndicators:(NSRect)fp8;
-- titleButtonOfClass:(Class)fp8;
-- initTitleButton:fp8;
-- newCloseButton;
-- newZoomButton;
-- newMiniaturizeButton;
-- newFileButton;
-- fileButton;
-- (void)_removeButtons;
-- (void)_updateButtons;
-- (char)_eventInTitlebar:fp8;
-- (char)acceptsFirstMouse:fp8;
-- (void)mouseDown:fp8;
-- (void)mouseUp:fp8;
-- (void)rightMouseDown:fp8;
-- (void)rightMouseUp:fp8;
-- (int)resizeEdgeForEvent:fp8;
-- (struct _NSSize)_resizeDeltaFromPoint:(struct _NSPoint)fp8 toEvent:fp16;
-- (NSRect)_validFrameForResizeFrame:(NSRect)fp8 fromResizeEdge:(int)fp24;
-- (NSRect)frame:(NSRect)fp8 resizedFromEdge:(int)fp24 withDelta:(struct _NSSize)fp28;
-- (char)constrainResizeEdge:(int *)fp8 withDelta:(struct _NSSize)fp12 elapsedTime:(float)fp20;
-- (void)resizeWithEvent:fp8;
-- (int)resizeFlags;
-- (void)resetCursorRects;
-- (void)setDocumentEdited:(char)fp8;
-- (struct _NSSize)miniaturizedSize;
-- (struct _NSSize)minFrameSize;
-- (float)_windowBorderThickness;
-- (float)_windowTitlebarXResizeBorderThickness;
-- (float)_windowTitlebarYResizeBorderThickness;
-- (float)_windowResizeBorderThickness;
-- (float)_minXWindowBorderWidth;
-- (float)_maxXWindowBorderWidth;
-- (float)_minYWindowBorderHeight;
-- (void)_invalidateTitleCellSize;
-- (void)_invalidateTitleCellWidth;
-- (float)_titleCellHeight;
-- (struct _NSSize)_titleCellSize;
-- (float)_titlebarHeight;
-- (NSRect)titlebarRect;
-- (NSRect)_maxTitlebarTitleRect;
-- (NSRect)_titlebarTitleRect;
-- (float)_windowTitlebarTitleMinHeight;
-- (NSRect)dragRectForFrameRect:(NSRect)fp8;
-- (struct _NSSize)sizeOfTitlebarButtons;
-- (struct _NSSize)_sizeOfTitlebarFileButton;
-- (float)_windowTitlebarButtonSpacingWidth;
-- (float)_minXTitlebarButtonsWidth;
-- (float)_maxXTitlebarButtonsWidth;
-- (int)_numberOfTitlebarLines;
-- (float)windowTitlebarLinesSpacingWidth;
-- (float)windowTitlebarTitleLinesSpacingWidth;
-- (float)_minLinesWidthWithSpace;
-- (NSRect)_minXTitlebarLinesRectWithTitleCellRect:(NSRect)fp8;
-- (NSRect)_maxXTitlebarLinesRectWithTitleCellRect:(NSRect)fp8;
-- (float)_minXTitlebarDecorationMinWidth;
-- (float)_maxXTitlebarDecorationMinWidth;
-- (struct _NSPoint)_closeButtonOrigin;
-- (struct _NSPoint)_zoomButtonOrigin;
-- (struct _NSPoint)_collapseButtonOrigin;
-- (struct _NSPoint)_fileButtonOrigin;
-- (float)_maxYTitlebarDragHeight;
-- (float)_minXTitlebarDragWidth;
-- (float)_maxXTitlebarDragWidth;
-- (float)_contentToFrameMinXWidth;
-- (float)_contentToFrameMaxXWidth;
-- (float)_contentToFrameMinYHeight;
-- (float)_contentToFrameMaxYHeight;
-- (NSRect)contentRect;
-- (float)_windowResizeCornerThickness;
-- (NSRect)_minYResizeRect;
-- (NSRect)_minYminXResizeRect;
-- (NSRect)_minYmaxXResizeRect;
-- (NSRect)_minXResizeRect;
-- (NSRect)_minXminYResizeRect;
-- (NSRect)_minXmaxYResizeRect;
-- (NSRect)_maxYResizeRect;
-- (NSRect)_maxYminXResizeRect;
-- (NSRect)_maxYmaxXResizeRect;
-- (NSRect)_maxXResizeRect;
-- (NSRect)_maxXminYResizeRect;
-- (NSRect)_maxXmaxYResizeRect;
-- (NSRect)_minXTitlebarResizeRect;
-- (NSRect)_maxXTitlebarResizeRect;
-- (NSRect)_minXBorderRect;
-- (NSRect)_maxXBorderRect;
-- (NSRect)_maxYBorderRect;
-- (NSRect)_minYBorderRect;
-
-@end
diff --git a/src/gui/kernel/qole_win.cpp b/src/gui/kernel/qole_win.cpp
deleted file mode 100644 (file)
index f53b819..0000000
+++ /dev/null
@@ -1,254 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qdnd_p.h"
-
-#if !(defined(QT_NO_DRAGANDDROP) && defined(QT_NO_CLIPBOARD))
-
-#if defined(Q_OS_WINCE)
-#include <shlobj.h>
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-QOleEnumFmtEtc::QOleEnumFmtEtc(const QVector<FORMATETC> &fmtetcs)
-{
-    m_isNull = false;
-    m_dwRefs = 1;
-    m_nIndex = 0;
-
-    for (int idx = 0; idx < fmtetcs.count(); ++idx) {
-        LPFORMATETC destetc = new FORMATETC();
-        if (copyFormatEtc(destetc, (LPFORMATETC)&(fmtetcs.at(idx)))) {
-            m_lpfmtetcs.append(destetc);
-        } else {
-            m_isNull = true;
-            delete destetc;
-            break;
-        }
-    }
-}
-
-QOleEnumFmtEtc::QOleEnumFmtEtc(const QVector<LPFORMATETC> &lpfmtetcs)
-{
-    m_isNull = false;
-    m_dwRefs = 1;
-    m_nIndex = 0;
-
-    for (int idx = 0; idx < lpfmtetcs.count(); ++idx) {
-        LPFORMATETC srcetc = lpfmtetcs.at(idx);
-        LPFORMATETC destetc = new FORMATETC();
-        if (copyFormatEtc(destetc, srcetc)) {
-            m_lpfmtetcs.append(destetc);
-        } else {
-            m_isNull = true;
-            delete destetc;
-            break;
-        }
-    }
-}
-
-QOleEnumFmtEtc::~QOleEnumFmtEtc()
-{
-    LPMALLOC pmalloc;
-
-#if !defined(Q_OS_WINCE)
-    if (CoGetMalloc(MEMCTX_TASK, &pmalloc) == NOERROR) {
-#else
-    if (SHGetMalloc(&pmalloc) == NOERROR) {
-#endif
-        for (int idx = 0; idx < m_lpfmtetcs.count(); ++idx) {
-            LPFORMATETC tmpetc = m_lpfmtetcs.at(idx);
-            if (tmpetc->ptd)
-                pmalloc->Free(tmpetc->ptd);
-            delete tmpetc;
-        }
-
-        pmalloc->Release();
-    }
-    m_lpfmtetcs.clear();
-}
-
-bool QOleEnumFmtEtc::isNull() const
-{
-    return m_isNull;
-}
-
-// IUnknown methods
-STDMETHODIMP
-QOleEnumFmtEtc::QueryInterface(REFIID riid, void FAR* FAR* ppvObj)
-{
-    if (riid == IID_IUnknown || riid == IID_IEnumFORMATETC) {
-        *ppvObj = this;
-        AddRef();
-        return NOERROR;
-    }
-    *ppvObj = NULL;
-    return ResultFromScode(E_NOINTERFACE);
-}
-
-STDMETHODIMP_(ULONG)
-QOleEnumFmtEtc::AddRef(void)
-{
-    return ++m_dwRefs;
-}
-
-STDMETHODIMP_(ULONG)
-QOleEnumFmtEtc::Release(void)
-{
-    if (--m_dwRefs == 0) {
-        delete this;
-        return 0;
-    }
-    return m_dwRefs;
-}
-
-// IEnumFORMATETC methods
-STDMETHODIMP
-QOleEnumFmtEtc::Next(ULONG celt, LPFORMATETC rgelt, ULONG FAR* pceltFetched)
-{
-    ULONG i=0;
-    ULONG nOffset;
-
-    if (rgelt == NULL)
-        return ResultFromScode(E_INVALIDARG);
-
-    while (i < celt) {
-        nOffset = m_nIndex + i;
-
-        if (nOffset < ULONG(m_lpfmtetcs.count())) {
-            copyFormatEtc((LPFORMATETC)&(rgelt[i]), m_lpfmtetcs.at(nOffset));
-            i++;
-        } else {
-            break;
-        }
-    }
-
-    m_nIndex += (WORD)i;
-
-    if (pceltFetched != NULL)
-        *pceltFetched = i;
-
-    if (i != celt)
-        return ResultFromScode(S_FALSE);
-
-    return NOERROR;
-}
-
-STDMETHODIMP
-QOleEnumFmtEtc::Skip(ULONG celt)
-{
-    ULONG i=0;
-    ULONG nOffset;
-
-    while (i < celt) {
-        nOffset = m_nIndex + i;
-
-        if (nOffset < ULONG(m_lpfmtetcs.count())) {
-            i++;
-        } else {
-            break;
-        }
-    }
-
-    m_nIndex += (WORD)i;
-
-    if (i != celt)
-        return ResultFromScode(S_FALSE);
-
-    return NOERROR;
-}
-
-STDMETHODIMP
-QOleEnumFmtEtc::Reset()
-{
-    m_nIndex = 0;
-    return NOERROR;
-}
-
-STDMETHODIMP
-QOleEnumFmtEtc::Clone(LPENUMFORMATETC FAR* newEnum)
-{
-    if (newEnum == NULL)
-        return ResultFromScode(E_INVALIDARG);
-
-    QOleEnumFmtEtc *result = new QOleEnumFmtEtc(m_lpfmtetcs);
-    result->m_nIndex = m_nIndex;
-
-    if (result->isNull()) {
-        delete result;
-        return ResultFromScode(E_OUTOFMEMORY);
-    } else {
-        *newEnum = result;
-    }
-
-    return NOERROR;
-}
-
-bool QOleEnumFmtEtc::copyFormatEtc(LPFORMATETC dest, LPFORMATETC src) const
-{
-    if (dest == NULL || src == NULL)
-        return false;
-
-    *dest = *src;
-
-    if (src->ptd) {
-        LPMALLOC pmalloc;
-
-#if !defined(Q_OS_WINCE)
-        if (CoGetMalloc(MEMCTX_TASK, &pmalloc) != NOERROR)
-#else
-        if (SHGetMalloc(&pmalloc) != NOERROR)
-#endif
-            return false;
-
-        pmalloc->Alloc(src->ptd->tdSize);
-        memcpy(dest->ptd, src->ptd, size_t(src->ptd->tdSize));
-
-        pmalloc->Release();
-    }
-
-    return true;
-}
-
-QT_END_NAMESPACE
-#endif // QT_NO_DRAGANDDROP && QT_NO_CLIPBOARD
diff --git a/src/gui/kernel/qsound_mac.mm b/src/gui/kernel/qsound_mac.mm
deleted file mode 100644 (file)
index a6c7865..0000000
+++ /dev/null
@@ -1,190 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#include <qapplication.h>
-#include "qsound.h"
-#include "qsound_p.h"
-#include <qt_mac_p.h>
-#include <qhash.h>
-#include <qdebug.h>
-#import <AppKit/AppKit.h>
-
-#include <AppKit/NSSound.h>
-
-QT_BEGIN_NAMESPACE
-
-void qt_mac_beep() 
-{
-    NSBeep();
-}
-
-QT_END_NAMESPACE
-
-#ifndef QT_NO_SOUND
-
-QT_BEGIN_NAMESPACE
-
-typedef QHash<QSound *, NSSound const *> Sounds;
-static Sounds sounds;
-
-class QAuServerMac : public QAuServer
-{
-    Q_OBJECT
-public:
-    QAuServerMac(QObject* parent) : QAuServer(parent) { }
-    void play(const QString& filename);
-    void play(QSound *s);
-    void stop(QSound*);
-    bool okay() { return true; }
-    using QAuServer::decLoop; // promote to public.
-protected:
-    NSSound *createNSSound(const QString &filename, QSound *qSound);
-};
-
-QT_END_NAMESPACE
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-@protocol NSSoundDelegate <NSObject>
--(void)sound:(NSSound *)sound didFinishPlaying:(BOOL)aBool;
-@end
-#endif
-
-QT_USE_NAMESPACE
-
-@interface QT_MANGLE_NAMESPACE(QMacSoundDelegate) : NSObject<NSSoundDelegate> {
-    QSound *qSound; // may be null.
-    QAuServerMac* server;
-}
--(id)initWithQSound:(QSound*)sound:(QAuServerMac*)server;
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QMacSoundDelegate)
--(id)initWithQSound:(QSound*)s:(QAuServerMac*)serv {
-    self = [super init];
-    if(self) {
-        qSound = s;
-        server = serv;
-    }
-    return self;
-}
-
-// Delegate function that gets called each time a sound finishes.
--(void)sound:(NSSound *)sound didFinishPlaying:(BOOL)finishedOk
-{
-    // qSound is null if this sound was started by play(QString),
-    // in which case there is no corresponding QSound object.
-    if (qSound == 0) {
-        [sound release];
-        [self release];
-        return;
-    }
-
-    // finishedOk is false if the sound cold not be played or
-    // if it was interrupted by stop().
-    if (finishedOk == false) {
-        sounds.remove(qSound);
-        [sound release];
-        [self release];
-        return;
-    }
-
-    // Check if the sound should loop "forever" (until stop).
-    if (qSound->loops() == -1) { 
-        [sound play];
-        return;
-    }
-
-    const int remainingIterations = server->decLoop(qSound);
-    if (remainingIterations > 0) {
-        [sound play];
-    } else {
-        sounds.remove(qSound);
-        [sound release];
-        [self release];
-    }
-}
-@end
-
-QT_BEGIN_NAMESPACE
-
-void QAuServerMac::play(const QString &fileName)
-{
-    QMacCocoaAutoReleasePool pool;
-    NSSound * const nsSound = createNSSound(fileName, 0);
-    [nsSound play];
-}
-
-void QAuServerMac::play(QSound *qSound)
-{
-    QMacCocoaAutoReleasePool pool;
-    NSSound * const nsSound = createNSSound(qSound->fileName(), qSound);
-    [nsSound play];
-    // Keep track of the nsSound object so we can find it again in stop().
-    sounds[qSound] = nsSound;
-}
-
-void QAuServerMac::stop(QSound *qSound)
-{
-    Sounds::const_iterator it = sounds.constFind(qSound);
-    if (it != sounds.constEnd())
-        [*it stop];
-}
-
-// Creates an NSSound object and installs a "sound finished" callack delegate on it.
-NSSound *QAuServerMac::createNSSound(const QString &fileName, QSound *qSound)
-{
-    NSString *nsFileName = const_cast<NSString *>(reinterpret_cast<const NSString *>(QCFString::toCFStringRef(fileName)));
-    NSSound * const nsSound = [[NSSound alloc] initWithContentsOfFile: nsFileName byReference:YES];
-    QT_MANGLE_NAMESPACE(QMacSoundDelegate) * const delegate = [[QT_MANGLE_NAMESPACE(QMacSoundDelegate) alloc] initWithQSound:qSound:this];
-    [nsSound setDelegate:delegate];
-    [nsFileName release];
-    return nsSound;
-}
-
-QAuServer* qt_new_audio_server()
-{
-    return new QAuServerMac(qApp);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qsound_mac.mm"
-
-#endif // QT_NO_SOUND
diff --git a/src/gui/kernel/qsound_win.cpp b/src/gui/kernel/qsound_win.cpp
deleted file mode 100644 (file)
index 908b1a7..0000000
+++ /dev/null
@@ -1,205 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsound.h"
-
-#ifndef QT_NO_SOUND
-
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include <qfile.h>
-#include "qpointer.h"
-#include "qsound_p.h"
-
-#include <qt_windows.h>
-
-QT_BEGIN_NAMESPACE
-
-class QAuServerWindows : public QAuServer {
-    Q_OBJECT
-
-public:
-    QAuServerWindows(QObject* parent);
-    ~QAuServerWindows();
-
-    void playHelper(const QString &filename, int loop, QSound *snd);
-    void play(const QString& filename, int loop);
-    void play(QSound*);
-
-    void stop(QSound*);
-    bool okay();
-
-    int decLoop(QSound *snd) { return QAuServer::decLoop(snd); }
-
-    HANDLE current;
-    HANDLE mutex;
-    HANDLE event;
-};
-
-QAuServerWindows::QAuServerWindows(QObject* parent) :
-    QAuServer(parent), current(0)
-{
-    mutex = CreateMutex(0, 0, 0);
-    event = CreateEvent(0, FALSE, FALSE, 0);
-}
-
-QAuServerWindows::~QAuServerWindows()
-{
-    HANDLE mtx = mutex;
-    WaitForSingleObject(mtx, INFINITE);
-    mutex = 0;
-
-    ReleaseMutex(mtx);
-    CloseHandle(mtx);
-    CloseHandle(event);
-}
-
-struct SoundInfo
-{
-    SoundInfo(const QString &fn, int lp, QSound *snd, QAuServerWindows *srv)
-        : sound(snd), server(srv), filename(fn), loops(lp)
-    {
-    }
-
-    QSound *sound;
-    QAuServerWindows *server;
-    QString filename;
-    int loops;
-};
-
-DWORD WINAPI SoundPlayProc(LPVOID param)
-{
-    SoundInfo *info = (SoundInfo*)param;
-
-    // copy data before waking up GUI thread
-    QAuServerWindows *server = info->server;
-    QSound *sound = info->sound;
-    int loops = info->loops;
-    QString filename = info->filename;
-    HANDLE mutex = server->mutex;
-    HANDLE event = server->event;
-    info = 0;
-
-    // server must not be destroyed until thread finishes
-    // and all other sounds have to wait
-    WaitForSingleObject(mutex, INFINITE);
-
-    if (loops <= 1) {
-        server->current = 0;
-        int flags = SND_FILENAME|SND_ASYNC;
-        if (loops == -1)
-            flags |= SND_LOOP;
-
-        PlaySound((wchar_t*)filename.utf16(), 0, flags);
-        if (sound && loops == 1)
-            server->decLoop(sound);
-
-        // GUI thread continues, but we are done as well.
-        SetEvent(event);
-    } else {
-        // signal GUI thread to continue - sound might be reset!
-        QPointer<QSound> guarded_sound = sound;
-        SetEvent(event);
-
-        for (int l = 0; l < loops && server->current; ++l) {
-            PlaySound((wchar_t*)filename.utf16(), 0, SND_FILENAME | SND_SYNC);
-
-            if (guarded_sound)
-                server->decLoop(guarded_sound);
-        }
-        server->current = 0;
-    }
-    ReleaseMutex(mutex);
-
-    return 0;
-}
-
-void QAuServerWindows::playHelper(const QString &filename, int loop, QSound *snd)
-{
-    if (loop == 0)
-        return;
-    // busy?
-    if (WaitForSingleObject(mutex, 0) == WAIT_TIMEOUT)
-        return;
-    ReleaseMutex(mutex);
-
-    DWORD threadid = 0;
-    SoundInfo info(filename, loop, snd, this);
-    current = CreateThread(0, 0, SoundPlayProc, &info, 0, &threadid);
-    CloseHandle(current);
-
-    WaitForSingleObject(event, INFINITE);
-}
-
-void QAuServerWindows::play(const QString& filename, int loop)
-{
-    playHelper(filename, loop, 0);
-}
-
-void QAuServerWindows::play(QSound* s)
-{
-    playHelper(s->fileName(), s->loops(), s);
-}
-
-void QAuServerWindows::stop(QSound*)
-{
-    // stop unlooped sound
-    if (!current)
-        PlaySound(0, 0, 0);
-    // stop after loop is done
-    current = 0;
-}
-
-bool QAuServerWindows::okay()
-{
-    return true;
-}
-
-QAuServer* qt_new_audio_server()
-{
-    return new QAuServerWindows(qApp);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qsound_win.cpp"
-
-#endif // QT_NO_SOUND
diff --git a/src/gui/kernel/qt_cocoa_helpers_mac.mm b/src/gui/kernel/qt_cocoa_helpers_mac.mm
deleted file mode 100644 (file)
index 25ab5a5..0000000
+++ /dev/null
@@ -1,1835 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#include <qcore_mac_p.h>
-#include <qaction.h>
-#include <qwidget.h>
-#include <qdesktopwidget.h>
-#include <qevent.h>
-#include <qpixmapcache.h>
-#include <qvarlengtharray.h>
-#include <qevent_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qt_mac_p.h>
-#include <qapplication_p.h>
-#include <qcocoaapplication_mac_p.h>
-#include <qcocoawindow_mac_p.h>
-#include <qcocoaview_mac_p.h>
-#include <qkeymapper_p.h>
-#include <qwidget_p.h>
-#include <qcocoawindow_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifdef QT_MAC_USE_COCOA
-// Cmd + left mousebutton should produce a right button
-//  press (mainly for mac users with one-button mice):
-static bool qt_leftButtonIsRightButton = false;
-#endif
-
-Q_GLOBAL_STATIC(QMacWindowFader, macwindowFader);
-
-QMacWindowFader::QMacWindowFader()
-    : m_duration(0.250)
-{
-}
-
-QMacWindowFader *QMacWindowFader::currentFader()
-{
-    return macwindowFader();
-}
-
-void QMacWindowFader::registerWindowToFade(QWidget *window)
-{
-    m_windowsToFade.append(window);
-}
-
-void QMacWindowFader::performFade()
-{
-    const QWidgetList myWidgetsToFade = m_windowsToFade;
-    const int widgetCount = myWidgetsToFade.count();
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    [NSAnimationContext beginGrouping];
-    [[NSAnimationContext currentContext] setDuration:NSTimeInterval(m_duration)];
-#endif
-
-    for (int i = 0; i < widgetCount; ++i) {
-        QWidget *widget = m_windowsToFade.at(i);
-        OSWindowRef window = qt_mac_window_for(widget);
-#ifdef QT_MAC_USE_COCOA
-        [[window animator] setAlphaValue:0.0];
-        QTimer::singleShot(qRound(m_duration * 1000), widget, SLOT(hide()));
-#else
-        TransitionWindowOptions options = {0, m_duration, 0, 0};
-        TransitionWindowWithOptions(window, kWindowFadeTransitionEffect, kWindowHideTransitionAction,
-                                    0, 1, &options);
-#endif
-    }
-#ifdef QT_MAC_USE_COCOA
-    [NSAnimationContext endGrouping];
-#endif
-    m_duration = 0.250;
-    m_windowsToFade.clear();
-}
-
-extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); // qapplication.cpp;
-extern QWidget * mac_mouse_grabber;
-extern QWidget *qt_button_down; //qapplication_mac.cpp
-extern QPointer<QWidget> qt_last_mouse_receiver;
-extern OSViewRef qt_mac_effectiveview_for(const QWidget *w);
-extern void qt_mac_updateCursorWithWidgetUnderMouse(QWidget *widgetUnderMouse); // qcursor_mac.mm
-
-void macWindowFade(void * /*OSWindowRef*/ window, float durationSeconds)
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-#endif
-    OSWindowRef wnd = static_cast<OSWindowRef>(window);
-    if (wnd) {
-        QWidget *widget;
-#ifdef QT_MAC_USE_COCOA
-        widget = [wnd QT_MANGLE_NAMESPACE(qt_qwidget)];
-#else
-    const UInt32 kWidgetCreatorQt = kEventClassQt;
-    enum {
-        kWidgetPropertyQWidget = 'QWId' //QWidget *
-    };
-        if (GetWindowProperty(static_cast<WindowRef>(window), kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(widget), 0, &widget) != noErr)
-            widget = 0;
-#endif
-        if (widget) {
-            QMacWindowFader::currentFader()->setFadeDuration(durationSeconds);
-            QMacWindowFader::currentFader()->registerWindowToFade(widget);
-            QMacWindowFader::currentFader()->performFade();
-        }
-    }
-}
-struct dndenum_mapper
-{
-    NSDragOperation mac_code;
-    Qt::DropAction qt_code;
-    bool Qt2Mac;
-};
-
-#if defined(QT_MAC_USE_COCOA) && defined(__OBJC__)
-
-static dndenum_mapper dnd_enums[] = {
-    { NSDragOperationLink,  Qt::LinkAction, true },
-    { NSDragOperationMove,  Qt::MoveAction, true },
-    { NSDragOperationCopy,  Qt::CopyAction, true },
-    { NSDragOperationGeneric,  Qt::CopyAction, false },
-    { NSDragOperationEvery, Qt::ActionMask, false },
-    { NSDragOperationNone, Qt::IgnoreAction, false }
-};
-
-NSDragOperation qt_mac_mapDropAction(Qt::DropAction action)
-{
-    for (int i=0; dnd_enums[i].qt_code; i++) {
-        if (dnd_enums[i].Qt2Mac && (action & dnd_enums[i].qt_code)) {
-            return dnd_enums[i].mac_code;
-        }
-    }
-    return NSDragOperationNone;
-}
-
-NSDragOperation qt_mac_mapDropActions(Qt::DropActions actions)
-{
-    NSDragOperation nsActions = NSDragOperationNone;
-    for (int i=0; dnd_enums[i].qt_code; i++) {
-        if (dnd_enums[i].Qt2Mac && (actions & dnd_enums[i].qt_code))
-            nsActions |= dnd_enums[i].mac_code;
-    }
-    return nsActions;
-}
-
-Qt::DropAction qt_mac_mapNSDragOperation(NSDragOperation nsActions)
-{
-    Qt::DropAction action = Qt::IgnoreAction;
-    for (int i=0; dnd_enums[i].mac_code; i++) {
-        if (nsActions & dnd_enums[i].mac_code)
-            return dnd_enums[i].qt_code;
-    }
-    return action;
-}
-
-Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions)
-{
-    Qt::DropActions actions = Qt::IgnoreAction;
-    for (int i=0; dnd_enums[i].mac_code; i++) {
-        if (nsActions & dnd_enums[i].mac_code)
-            actions |= dnd_enums[i].qt_code;
-    }
-    return actions;
-}
-
-Q_GLOBAL_STATIC(DnDParams, currentDnDParameters);
-DnDParams *macCurrentDnDParameters()
-{
-    return currentDnDParameters();
-}
-#endif
-
-bool macWindowIsTextured( void * /*OSWindowRef*/ window )
-{
-    OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#ifdef QT_MAC_USE_COCOA
-    return ( [wnd styleMask] & NSTexturedBackgroundWindowMask ) ? true : false;
-#else
-    WindowAttributes currentAttributes;
-    GetWindowAttributes(wnd, &currentAttributes);
-    return (currentAttributes & kWindowMetalAttribute) ? true : false;
-#endif
-}
-
-void macWindowToolbarShow(const QWidget *widget, bool show )
-{
-    OSWindowRef wnd = qt_mac_window_for(widget);
-#ifdef QT_MAC_USE_COCOA
-    if (NSToolbar *toolbar = [wnd toolbar]) {
-        QMacCocoaAutoReleasePool pool;
-        if (show != [toolbar isVisible]) {
-           [toolbar setVisible:show];
-        } else {
-            // The toolbar may be in sync, but we are not, update our framestrut.
-            qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
-        }
-    }
-#else
-    qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
-    ShowHideWindowToolbar(wnd, show, false);
-#endif
-}
-
-
-void macWindowToolbarSet( void * /*OSWindowRef*/ window, void *toolbarRef  )
-{
-    OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#ifdef QT_MAC_USE_COCOA
-    [wnd setToolbar:static_cast<NSToolbar *>(toolbarRef)];
-#else
-    SetWindowToolbar(wnd, static_cast<HIToolbarRef>(toolbarRef));
-#endif
-}
-
-bool macWindowToolbarIsVisible( void * /*OSWindowRef*/ window )
-{
-    OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#ifdef QT_MAC_USE_COCOA
-    if (NSToolbar *toolbar = [wnd toolbar])
-        return [toolbar isVisible];
-    return false;
-#else
-    return IsWindowToolbarVisible(wnd);
-#endif
-}
-
-void macWindowSetHasShadow( void * /*OSWindowRef*/ window, bool hasShadow  )
-{
-    OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#ifdef QT_MAC_USE_COCOA
-    [wnd setHasShadow:BOOL(hasShadow)];
-#else
-    if (hasShadow)
-        ChangeWindowAttributes(wnd, 0, kWindowNoShadowAttribute);
-    else
-        ChangeWindowAttributes(wnd, kWindowNoShadowAttribute, 0);
-#endif
-}
-
-void macWindowFlush(void * /*OSWindowRef*/ window)
-{
-    OSWindowRef wnd = static_cast<OSWindowRef>(window);
-#ifdef QT_MAC_USE_COCOA
-    [wnd flushWindowIfNeeded];
-#else
-    HIWindowFlush(wnd);
-#endif
-}
-
-void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm)
-{
-    QMacCocoaAutoReleasePool pool;
-    if(QCFType<CGImageRef> image = pm.toMacCGImageRef()) {
-        NSImage *newImage = 0;
-        NSRect imageRect = NSMakeRect(0.0, 0.0, CGImageGetWidth(image), CGImageGetHeight(image));
-        newImage = [[NSImage alloc] initWithSize:imageRect.size];
-        [newImage lockFocus];
-        {
-            CGContextRef imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
-            CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
-        }
-        [newImage unlockFocus];
-        return newImage;
-    }
-    return 0;
-}
-
-void qt_mac_update_mouseTracking(QWidget *widget)
-{
-#ifdef QT_MAC_USE_COCOA
-    [qt_mac_nativeview_for(widget) updateTrackingAreas];
-#else
-    Q_UNUSED(widget);
-#endif
-}
-
-OSStatus qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage)
-{
-    // Verbatim copy if HIViewDrawCGImage (as shown on Carbon-Dev)
-    OSStatus err = noErr;
-
-    require_action(inContext != NULL, InvalidContext, err = paramErr);
-    require_action(inBounds != NULL, InvalidBounds, err = paramErr);
-    require_action(inImage != NULL, InvalidImage, err = paramErr);
-
-    CGContextSaveGState( inContext );
-    CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
-    CGContextScaleCTM(inContext, 1, -1);
-
-    CGContextDrawImage(inContext, *inBounds, inImage);
-
-    CGContextRestoreGState(inContext);
-InvalidImage:
-InvalidBounds:
-InvalidContext:
-       return err;
-}
-
-bool qt_mac_checkForNativeSizeGrip(const QWidget *widget)
-{
-#ifndef QT_MAC_USE_COCOA
-    OSViewRef nativeSizeGrip = 0;
-    HIViewFindByID(HIViewGetRoot(HIViewGetWindow(HIViewRef(widget->winId()))), kHIViewWindowGrowBoxID, &nativeSizeGrip);
-    return (nativeSizeGrip != 0);
-#else
-    return [[reinterpret_cast<NSView *>(widget->effectiveWinId()) window] showsResizeIndicator];
-#endif
-}
-struct qt_mac_enum_mapper
-{
-    int mac_code;
-    int qt_code;
-#if defined(DEBUG_MOUSE_MAPS)
-#   define QT_MAC_MAP_ENUM(x) x, #x
-    const char *desc;
-#else
-#   define QT_MAC_MAP_ENUM(x) x
-#endif
-};
-
-//mouse buttons
-static qt_mac_enum_mapper qt_mac_mouse_symbols[] = {
-{ kEventMouseButtonPrimary, QT_MAC_MAP_ENUM(Qt::LeftButton) },
-{ kEventMouseButtonSecondary, QT_MAC_MAP_ENUM(Qt::RightButton) },
-{ kEventMouseButtonTertiary, QT_MAC_MAP_ENUM(Qt::MidButton) },
-{ 4, QT_MAC_MAP_ENUM(Qt::XButton1) },
-{ 5, QT_MAC_MAP_ENUM(Qt::XButton2) },
-{ 0, QT_MAC_MAP_ENUM(0) }
-};
-Qt::MouseButtons qt_mac_get_buttons(int buttons)
-{
-#ifdef DEBUG_MOUSE_MAPS
-    qDebug("Qt: internal: **Mapping buttons: %d (0x%04x)", buttons, buttons);
-#endif
-    Qt::MouseButtons ret = Qt::NoButton;
-    for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
-        if (buttons & (0x01<<(qt_mac_mouse_symbols[i].mac_code-1))) {
-#ifdef DEBUG_MOUSE_MAPS
-            qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
-#endif
-            ret |= Qt::MouseButtons(qt_mac_mouse_symbols[i].qt_code);
-        }
-    }
-    return ret;
-}
-Qt::MouseButton qt_mac_get_button(EventMouseButton button)
-{
-#ifdef DEBUG_MOUSE_MAPS
-    qDebug("Qt: internal: **Mapping button: %d (0x%04x)", button, button);
-#endif
-    for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
-        if (button == qt_mac_mouse_symbols[i].mac_code) {
-#ifdef DEBUG_MOUSE_MAPS
-            qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
-#endif
-            return Qt::MouseButton(qt_mac_mouse_symbols[i].qt_code);
-        }
-    }
-    return Qt::NoButton;
-}
-
-void macSendToolbarChangeEvent(QWidget *widget)
-{
-    QToolBarChangeEvent ev(!(GetCurrentKeyModifiers() & cmdKey));
-    qt_sendSpontaneousEvent(widget, &ev);
-}
-
-Q_GLOBAL_STATIC(QMacTabletHash, tablet_hash)
-QMacTabletHash *qt_mac_tablet_hash()
-{
-    return tablet_hash();
-}
-
-#ifdef QT_MAC_USE_COCOA
-
-// Clears the QWidget pointer that each QCocoaView holds.
-void qt_mac_clearCocoaViewQWidgetPointers(QWidget *widget)
-{
-    QT_MANGLE_NAMESPACE(QCocoaView) *cocoaView = reinterpret_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(qt_mac_nativeview_for(widget));
-    if (cocoaView && [cocoaView respondsToSelector:@selector(qt_qwidget)]) {
-        [cocoaView qt_clearQWidget];
-    }
-}
-
-void qt_dispatchTabletProximityEvent(void * /*NSEvent * */ tabletEvent)
-{
-    NSEvent *proximityEvent = static_cast<NSEvent *>(tabletEvent);
-    // simply construct a Carbon proximity record and handle it all in one spot.
-    TabletProximityRec carbonProximityRec = { [proximityEvent vendorID],
-                                              [proximityEvent tabletID],
-                                              [proximityEvent pointingDeviceID],
-                                              [proximityEvent deviceID],
-                                              [proximityEvent systemTabletID],
-                                              [proximityEvent vendorPointingDeviceType],
-                                              [proximityEvent pointingDeviceSerialNumber],
-                                              [proximityEvent uniqueID],
-                                              [proximityEvent capabilityMask],
-                                              [proximityEvent pointingDeviceType],
-                                              [proximityEvent isEnteringProximity] };
-    qt_dispatchTabletProximityEvent(carbonProximityRec);
-}
-#endif // QT_MAC_USE_COCOA
-
-void qt_dispatchTabletProximityEvent(const ::TabletProximityRec &proxRec)
-{
-    QTabletDeviceData proximityDevice;
-    proximityDevice.tabletUniqueID = proxRec.uniqueID;
-    proximityDevice.capabilityMask = proxRec.capabilityMask;
-
-    switch (proxRec.pointerType) {
-        case NSUnknownPointingDevice:
-        default:
-            proximityDevice.tabletPointerType = QTabletEvent::UnknownPointer;
-            break;
-        case NSPenPointingDevice:
-            proximityDevice.tabletPointerType = QTabletEvent::Pen;
-            break;
-        case NSCursorPointingDevice:
-            proximityDevice.tabletPointerType = QTabletEvent::Cursor;
-            break;
-        case NSEraserPointingDevice:
-            proximityDevice.tabletPointerType = QTabletEvent::Eraser;
-            break;
-    }
-    uint bits = proxRec.vendorPointerType;
-    if (bits == 0 && proximityDevice.tabletUniqueID != 0) {
-        // Fallback. It seems that the driver doesn't always include all the information.
-        // High-End Wacom devices store their "type" in the uper bits of the Unique ID.
-        // I'm not sure how to handle it for consumer devices, but I'll test that in a bit.
-        bits = proximityDevice.tabletUniqueID >> 32;
-    }
-    // Defined in the "EN0056-NxtGenImpGuideX"
-    // on Wacom's Developer Website (www.wacomeng.com)
-    if (((bits & 0x0006) == 0x0002) && ((bits & 0x0F06) != 0x0902)) {
-        proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
-    } else {
-        switch (bits & 0x0F06) {
-            case 0x0802:
-                proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
-                break;
-            case 0x0902:
-                proximityDevice.tabletDeviceType = QTabletEvent::Airbrush;
-                break;
-            case 0x0004:
-                proximityDevice.tabletDeviceType = QTabletEvent::FourDMouse;
-                break;
-            case 0x0006:
-                proximityDevice.tabletDeviceType = QTabletEvent::Puck;
-                break;
-            case 0x0804:
-                proximityDevice.tabletDeviceType = QTabletEvent::RotationStylus;
-                break;
-            default:
-                proximityDevice.tabletDeviceType = QTabletEvent::NoDevice;
-        }
-    }
-    // The deviceID is "unique" while in the proximity, it's a key that we can use for
-    // linking up TabletDeviceData to an event (especially if there are two devices in action).
-    bool entering = proxRec.enterProximity;
-    if (entering) {
-        qt_mac_tablet_hash()->insert(proxRec.deviceID, proximityDevice);
-    } else {
-        qt_mac_tablet_hash()->remove(proxRec.deviceID);
-    }
-
-    QTabletEvent qtabletProximity(entering ? QEvent::TabletEnterProximity
-                                  : QEvent::TabletLeaveProximity,
-                                  QPoint(), QPoint(), QPointF(), proximityDevice.tabletDeviceType,
-                                  proximityDevice.tabletPointerType, 0., 0, 0, 0., 0., 0, 0,
-                                  proximityDevice.tabletUniqueID);
-
-    qt_sendSpontaneousEvent(qApp, &qtabletProximity);
-}
-
-// Use this method to keep all the information in the TextSegment. As long as it is ordered
-// we are in OK shape, and we can influence that ourselves.
-struct KeyPair
-{
-    QChar cocoaKey;
-    Qt::Key qtKey;
-};
-
-bool operator==(const KeyPair &entry, QChar qchar)
-{
-    return entry.cocoaKey == qchar;
-}
-
-bool operator<(const KeyPair &entry, QChar qchar)
-{
-    return entry.cocoaKey < qchar;
-}
-
-bool operator<(QChar qchar, const KeyPair &entry)
-{
-    return qchar < entry.cocoaKey;
-}
-
-bool operator<(const Qt::Key &key, const KeyPair &entry)
-{
-    return key < entry.qtKey;
-}
-
-bool operator<(const KeyPair &entry, const Qt::Key &key)
-{
-    return entry.qtKey < key;
-}
-
-static bool qtKey2CocoaKeySortLessThan(const KeyPair &entry1, const KeyPair &entry2)
-{
-    return entry1.qtKey < entry2.qtKey;
-}
-
-static const int NumEntries = 59;
-static const KeyPair entries[NumEntries] = {
-    { NSEnterCharacter, Qt::Key_Enter },
-    { NSBackspaceCharacter, Qt::Key_Backspace },
-    { NSTabCharacter, Qt::Key_Tab },
-    { NSNewlineCharacter, Qt::Key_Return },
-    { NSCarriageReturnCharacter, Qt::Key_Return },
-    { NSBackTabCharacter, Qt::Key_Backtab },
-    { kEscapeCharCode, Qt::Key_Escape },
-    // Cocoa sends us delete when pressing backspace!
-    // (NB when we reverse this list in qtKey2CocoaKey, there
-    // will be two indices of Qt::Key_Backspace. But is seems to work
-    // ok for menu shortcuts (which uses that function):
-    { NSDeleteCharacter, Qt::Key_Backspace },
-    { NSUpArrowFunctionKey, Qt::Key_Up },
-    { NSDownArrowFunctionKey, Qt::Key_Down },
-    { NSLeftArrowFunctionKey, Qt::Key_Left },
-    { NSRightArrowFunctionKey, Qt::Key_Right },
-    { NSF1FunctionKey, Qt::Key_F1 },
-    { NSF2FunctionKey, Qt::Key_F2 },
-    { NSF3FunctionKey, Qt::Key_F3 },
-    { NSF4FunctionKey, Qt::Key_F4 },
-    { NSF5FunctionKey, Qt::Key_F5 },
-    { NSF6FunctionKey, Qt::Key_F6 },
-    { NSF7FunctionKey, Qt::Key_F7 },
-    { NSF8FunctionKey, Qt::Key_F8 },
-    { NSF9FunctionKey, Qt::Key_F9 },
-    { NSF10FunctionKey, Qt::Key_F10 },
-    { NSF11FunctionKey, Qt::Key_F11 },
-    { NSF12FunctionKey, Qt::Key_F12 },
-    { NSF13FunctionKey, Qt::Key_F13 },
-    { NSF14FunctionKey, Qt::Key_F14 },
-    { NSF15FunctionKey, Qt::Key_F15 },
-    { NSF16FunctionKey, Qt::Key_F16 },
-    { NSF17FunctionKey, Qt::Key_F17 },
-    { NSF18FunctionKey, Qt::Key_F18 },
-    { NSF19FunctionKey, Qt::Key_F19 },
-    { NSF20FunctionKey, Qt::Key_F20 },
-    { NSF21FunctionKey, Qt::Key_F21 },
-    { NSF22FunctionKey, Qt::Key_F22 },
-    { NSF23FunctionKey, Qt::Key_F23 },
-    { NSF24FunctionKey, Qt::Key_F24 },
-    { NSF25FunctionKey, Qt::Key_F25 },
-    { NSF26FunctionKey, Qt::Key_F26 },
-    { NSF27FunctionKey, Qt::Key_F27 },
-    { NSF28FunctionKey, Qt::Key_F28 },
-    { NSF29FunctionKey, Qt::Key_F29 },
-    { NSF30FunctionKey, Qt::Key_F30 },
-    { NSF31FunctionKey, Qt::Key_F31 },
-    { NSF32FunctionKey, Qt::Key_F32 },
-    { NSF33FunctionKey, Qt::Key_F33 },
-    { NSF34FunctionKey, Qt::Key_F34 },
-    { NSF35FunctionKey, Qt::Key_F35 },
-    { NSInsertFunctionKey, Qt::Key_Insert },
-    { NSDeleteFunctionKey, Qt::Key_Delete },
-    { NSHomeFunctionKey, Qt::Key_Home },
-    { NSEndFunctionKey, Qt::Key_End },
-    { NSPageUpFunctionKey, Qt::Key_PageUp },
-    { NSPageDownFunctionKey, Qt::Key_PageDown },
-    { NSPrintScreenFunctionKey, Qt::Key_Print },
-    { NSScrollLockFunctionKey, Qt::Key_ScrollLock },
-    { NSPauseFunctionKey, Qt::Key_Pause },
-    { NSSysReqFunctionKey, Qt::Key_SysReq },
-    { NSMenuFunctionKey, Qt::Key_Menu },
-    { NSHelpFunctionKey, Qt::Key_Help },
-};
-#ifdef QT_MAC_USE_COCOA
-static const KeyPair * const end = entries + NumEntries;
-#endif
-
-QChar qtKey2CocoaKey(Qt::Key key)
-{
-    // The first time this function is called, create a reverse
-    // looup table sorted on Qt Key rather than Cocoa key:
-    static QVector<KeyPair> rev_entries(NumEntries);
-    static bool mustInit = true;
-    if (mustInit){
-        mustInit = false;
-        for (int i=0; i<NumEntries; ++i)
-            rev_entries[i] = entries[i];
-        qSort(rev_entries.begin(), rev_entries.end(), qtKey2CocoaKeySortLessThan);
-    }
-    const QVector<KeyPair>::iterator i
-            = qBinaryFind(rev_entries.begin(), rev_entries.end(), key);
-    if (i == rev_entries.end())
-        return QChar();
-    return i->cocoaKey;
-}
-
-#ifdef QT_MAC_USE_COCOA
-static Qt::Key cocoaKey2QtKey(QChar keyCode)
-{
-    const KeyPair *i = qBinaryFind(entries, end, keyCode);
-    if (i == end)
-        return Qt::Key(keyCode.unicode());
-    return i->qtKey;
-}
-
-Qt::KeyboardModifiers qt_cocoaModifiers2QtModifiers(ulong modifierFlags)
-{
-    Qt::KeyboardModifiers qtMods =Qt::NoModifier;
-    if (modifierFlags &  NSShiftKeyMask)
-        qtMods |= Qt::ShiftModifier;
-    if (modifierFlags & NSControlKeyMask)
-        qtMods |= Qt::MetaModifier;
-    if (modifierFlags & NSAlternateKeyMask)
-        qtMods |= Qt::AltModifier;
-    if (modifierFlags & NSCommandKeyMask)
-        qtMods |= Qt::ControlModifier;
-    if (modifierFlags & NSNumericPadKeyMask)
-        qtMods |= Qt::KeypadModifier;
-    return qtMods;
-}
-
-NSString *qt_mac_removePrivateUnicode(NSString* string)
-{
-    int len = [string length];
-    if (len) {
-        QVarLengthArray <unichar, 10> characters(len);
-        bool changed = false;
-        for (int i = 0; i<len; i++) {
-            characters[i] = [string characterAtIndex:i];
-            // check if they belong to key codes in private unicode range
-            // currently we need to handle only the NSDeleteFunctionKey
-            if (characters[i] == NSDeleteFunctionKey) {
-                characters[i] = NSDeleteCharacter;
-                changed = true;
-            }
-        }
-        if (changed)
-            return [NSString stringWithCharacters:characters.data() length:len];
-    }
-    return string;
-}
-
-Qt::KeyboardModifiers qt_cocoaDragOperation2QtModifiers(uint dragOperations)
-{
-    Qt::KeyboardModifiers qtMods =Qt::NoModifier;
-    if (dragOperations &  NSDragOperationLink)
-        qtMods |= Qt::MetaModifier;
-    if (dragOperations & NSDragOperationGeneric)
-        qtMods |= Qt::ControlModifier;
-    if (dragOperations & NSDragOperationCopy)
-        qtMods |= Qt::AltModifier;
-    return qtMods;
-}
-
-static inline QEvent::Type cocoaEvent2QtEvent(NSUInteger eventType)
-{
-    // Handle the trivial cases that can be determined from the type.
-    switch (eventType) {
-    case NSKeyDown:
-        return QEvent::KeyPress;
-    case NSKeyUp:
-        return QEvent::KeyRelease;
-    case NSLeftMouseDown:
-    case NSRightMouseDown:
-    case NSOtherMouseDown:
-        return QEvent::MouseButtonPress;
-    case NSLeftMouseUp:
-    case NSRightMouseUp:
-    case NSOtherMouseUp:
-        return QEvent::MouseButtonRelease;
-    case NSMouseMoved:
-    case NSLeftMouseDragged:
-    case NSRightMouseDragged:
-    case NSOtherMouseDragged:
-        return QEvent::MouseMove;
-    case NSScrollWheel:
-        return QEvent::Wheel;
-    }
-    return QEvent::None;
-}
-
-static bool mustUseCocoaKeyEvent()
-{
-    QCFType<TISInputSourceRef> source = TISCopyCurrentKeyboardInputSource();
-    return TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) == 0;
-}
-
-bool qt_dispatchKeyEventWithCocoa(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
-{
-    NSEvent *event = static_cast<NSEvent *>(keyEvent);
-    NSString *keyChars = [event charactersIgnoringModifiers];
-    int keyLength = [keyChars length];
-    if (keyLength == 0)
-        return false; // Dead Key, nothing to do!
-    bool ignoreText = false;
-    Qt::Key qtKey = Qt::Key_unknown;
-    if (keyLength == 1) {
-        QChar ch([keyChars characterAtIndex:0]);
-        if (ch.isLower())
-            ch = ch.toUpper();
-        qtKey = cocoaKey2QtKey(ch);
-        // Do not set the text for Function-Key Unicodes characters (0xF700–0xF8FF).
-        ignoreText = (ch.unicode() >= 0xF700 && ch.unicode() <= 0xF8FF);
-    }
-    Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
-    QString text;
-
-    // To quote from the Carbon port: This is actually wrong--but it is the best that
-    // can be done for now because of the Control/Meta mapping issues
-    // (we always get text on the Mac)
-    if (!ignoreText && !(keyMods & (Qt::ControlModifier | Qt::MetaModifier)))
-        text = QCFString::toQString(reinterpret_cast<CFStringRef>(keyChars));
-
-    UInt32 macScanCode = 1;
-    QKeyEvent ke(cocoaEvent2QtEvent([event type]), qtKey, keyMods,
-                   macScanCode, [event keyCode], [event modifierFlags],
-                   text, [event isARepeat], qMax(1, keyLength));
-    return qt_sendSpontaneousEvent(widgetToGetEvent, &ke) && ke.isAccepted();
-}
-#endif
-
-Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum)
-{
-    if (buttonNum == 0)
-        return Qt::LeftButton;
-    if (buttonNum == 1)
-        return Qt::RightButton;
-    if (buttonNum == 2)
-        return Qt::MidButton;
-    if (buttonNum == 3)
-        return Qt::XButton1;
-    if (buttonNum == 4)
-        return Qt::XButton2;
-    return Qt::NoButton;
-}
-
-bool qt_dispatchKeyEvent(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
-{
-#ifndef QT_MAC_USE_COCOA
-    Q_UNUSED(keyEvent);
-    Q_UNUSED(widgetToGetEvent);
-    return false;
-#else
-    NSEvent *event = static_cast<NSEvent *>(keyEvent);
-    EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
-    Q_ASSERT(key_event);
-    unsigned int info = 0;
-
-    if ([event type] == NSKeyDown) {
-        NSString *characters = [event characters];
-        if ([characters length]) {
-            unichar value = [characters characterAtIndex:0];
-            qt_keymapper_private()->updateKeyMap(0, key_event, (void *)&value);
-            info = value;
-        }
-    }
-
-    if (qt_mac_sendMacEventToWidget(widgetToGetEvent, key_event))
-        return true;
-
-    if (mustUseCocoaKeyEvent())
-        return qt_dispatchKeyEventWithCocoa(keyEvent, widgetToGetEvent);
-
-    bool consumed = qt_keymapper_private()->translateKeyEvent(widgetToGetEvent, 0, key_event, &info, true);
-    return consumed && (info != 0);
-#endif
-}
-
-void qt_dispatchModifiersChanged(void * /*NSEvent * */flagsChangedEvent, QWidget *widgetToGetEvent)
-{
-#ifndef QT_MAC_USE_COCOA
-    Q_UNUSED(flagsChangedEvent);
-    Q_UNUSED(widgetToGetEvent);
-#else
-    UInt32 modifiers = 0;
-    // Sync modifiers with Qt
-    NSEvent *event = static_cast<NSEvent *>(flagsChangedEvent);
-    EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
-    Q_ASSERT(key_event);
-    GetEventParameter(key_event, kEventParamKeyModifiers, typeUInt32, 0,
-                      sizeof(modifiers), 0, &modifiers);
-    extern void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object);
-    qt_mac_send_modifiers_changed(modifiers, widgetToGetEvent);
-#endif
-}
-
-QPointF flipPoint(const NSPoint &p)
-{
-    return QPointF(p.x, flipYCoordinate(p.y));
-}
-
-NSPoint flipPoint(const QPoint &p)
-{
-    return NSMakePoint(p.x(), flipYCoordinate(p.y()));
-}
-
-NSPoint flipPoint(const QPointF &p)
-{
-    return NSMakePoint(p.x(), flipYCoordinate(p.y()));
-}
-
-#if defined(QT_MAC_USE_COCOA) && defined(__OBJC__)
-
-void qt_mac_handleNonClientAreaMouseEvent(NSWindow *window, NSEvent *event)
-{
-    QWidget *widgetToGetEvent = [window QT_MANGLE_NAMESPACE(qt_qwidget)];
-    if (widgetToGetEvent == 0)
-        return;
-
-    NSEventType evtType = [event type];
-    QPoint qlocalPoint;
-    QPoint qglobalPoint;
-    bool processThisEvent = false;
-    bool fakeNCEvents = false;
-    bool fakeMouseEvents = false;
-
-    // Check if this is a mouse event.
-    if (evtType == NSLeftMouseDown || evtType == NSLeftMouseUp
-        || evtType == NSRightMouseDown || evtType == NSRightMouseUp
-        || evtType == NSOtherMouseDown || evtType == NSOtherMouseUp
-        || evtType == NSMouseMoved     || evtType == NSLeftMouseDragged
-        || evtType == NSRightMouseDragged || evtType == NSOtherMouseDragged) {
-        // Check if we want to pass this message to another window
-        if (mac_mouse_grabber  && mac_mouse_grabber != widgetToGetEvent) {
-            NSWindow *grabWindow = static_cast<NSWindow *>(qt_mac_window_for(mac_mouse_grabber));
-            if (window != grabWindow) {
-                window = grabWindow;
-                widgetToGetEvent = mac_mouse_grabber;
-                fakeNCEvents = true;
-            }
-        }
-        // Dont generate normal NC mouse events for Left Button dragged
-        if(evtType != NSLeftMouseDragged || fakeNCEvents) {
-            NSPoint windowPoint = [event locationInWindow];
-            NSPoint globalPoint = [[event window] convertBaseToScreen:windowPoint];
-            NSRect frameRect = [window frame];
-            if (fakeNCEvents || NSMouseInRect(globalPoint, frameRect, NO)) {
-                NSRect contentRect = [window contentRectForFrameRect:frameRect];
-                qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
-                QWidget *w = widgetToGetEvent->childAt(widgetToGetEvent->mapFromGlobal(qglobalPoint));
-                // check that the mouse pointer is on the non-client area and
-                // there are not widgets in it.
-                if (fakeNCEvents || (!NSMouseInRect(globalPoint, contentRect, NO) && !w)) {
-                    qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
-                    qlocalPoint = widgetToGetEvent->mapFromGlobal(qglobalPoint);
-                    processThisEvent = true;
-                }
-            }
-        }
-    }
-    // This is not an NC area mouse message.
-    if (!processThisEvent)
-        return;
-
-    // If the window is frame less, generate fake mouse events instead. (floating QToolBar)
-    // or if someone already got an explicit or implicit grab
-    if (mac_mouse_grabber || qt_button_down ||
-        (fakeNCEvents && (widgetToGetEvent->window()->windowFlags() & Qt::FramelessWindowHint)))
-        fakeMouseEvents = true;
-
-    Qt::MouseButton button;
-    QEvent::Type eventType;
-    // Convert to Qt::Event type
-    switch (evtType) {
-        case NSLeftMouseDown:
-            button = Qt::LeftButton;
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
-                                           : QEvent::MouseButtonPress;
-            break;
-        case NSLeftMouseUp:
-            button = Qt::LeftButton;
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
-                                           : QEvent::MouseButtonRelease;
-            break;
-        case NSRightMouseDown:
-            button = Qt::RightButton;
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
-                                           : QEvent::MouseButtonPress;
-            break;
-        case NSRightMouseUp:
-            button = Qt::RightButton;
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
-                                           : QEvent::MouseButtonRelease;
-            break;
-        case NSOtherMouseDown:
-            button = cocoaButton2QtButton([event buttonNumber]);
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
-                                           : QEvent::MouseButtonPress;
-            break;
-        case NSOtherMouseUp:
-            button = cocoaButton2QtButton([event buttonNumber]);
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
-                                           : QEvent::MouseButtonRelease;
-            break;
-        case NSMouseMoved:
-            button = Qt::NoButton;
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
-                                           : QEvent::MouseMove;
-            break;
-        case NSLeftMouseDragged:
-            button = Qt::LeftButton;
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
-                                           : QEvent::MouseMove;
-            break;
-        case NSRightMouseDragged:
-            button = Qt::RightButton;
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
-                                           : QEvent::MouseMove;
-            break;
-        case NSOtherMouseDragged:
-            button = cocoaButton2QtButton([event buttonNumber]);
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
-                                           : QEvent::MouseMove;
-            break;
-        default:
-            qWarning("not handled! Non client area mouse message");
-            return;
-    }
-
-    Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
-    if (eventType == QEvent::NonClientAreaMouseButtonPress || eventType == QEvent::MouseButtonPress) {
-        NSInteger clickCount = [event clickCount];
-        if (clickCount % 2 == 0)
-            eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonDblClick
-                                           : QEvent::MouseButtonDblClick;
-        if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
-            button = Qt::RightButton;
-            qt_leftButtonIsRightButton = true;
-        }
-    } else if (eventType == QEvent::NonClientAreaMouseButtonRelease || eventType == QEvent::MouseButtonRelease) {
-        if (button == Qt::LeftButton && qt_leftButtonIsRightButton) {
-            button = Qt::RightButton;
-            qt_leftButtonIsRightButton = false;
-        }
-    }
-
-    Qt::MouseButtons buttons = 0;
-    {
-        UInt32 mac_buttons;
-        if (GetEventParameter((EventRef)[event eventRef], kEventParamMouseChord, typeUInt32, 0,
-                              sizeof(mac_buttons), 0, &mac_buttons) == noErr)
-            buttons = qt_mac_get_buttons(mac_buttons);
-    }
-
-    QMouseEvent qme(eventType, qlocalPoint, qglobalPoint, button, buttons, keyMods);
-    qt_sendSpontaneousEvent(widgetToGetEvent, &qme);
-
-    // We don't need to set the implicit grab widget here because we won't
-    // reach this point if then event type is Press over a Qt widget.
-    // However we might need to unset it if the event is Release.
-    if (eventType == QEvent::MouseButtonRelease)
-        qt_button_down = 0;
-}
-
-QWidget *qt_mac_getTargetForKeyEvent(QWidget *widgetThatReceivedEvent)
-{
-    if (QWidget *popup = QApplication::activePopupWidget()) {
-        QWidget *focusInPopup = popup->focusWidget();
-        return focusInPopup ? focusInPopup : popup;
-    }
-
-    QWidget *widgetToGetKey = qApp->focusWidget();
-    if (!widgetToGetKey)
-        widgetToGetKey = widgetThatReceivedEvent;
-
-    return widgetToGetKey;
-}
-
-// This function will find the widget that should receive the
-// mouse event. Because of explicit/implicit mouse grabs, popups,
-// etc, this might not end up being the same as the widget under
-// the mouse (which is more interresting when handling enter/leave
-// events
-QWidget *qt_mac_getTargetForMouseEvent(
-    // You can call this function without providing an event.
-    NSEvent *event,
-    QEvent::Type eventType,
-    QPoint &returnLocalPoint,
-    QPoint &returnGlobalPoint,
-    QWidget *nativeWidget,
-    QWidget **returnWidgetUnderMouse)
-{
-    Q_UNUSED(event);
-    NSPoint nsglobalpoint = event ? [[event window] convertBaseToScreen:[event locationInWindow]] : [NSEvent mouseLocation];
-    QPointF globalPointF = flipPoint(nsglobalpoint);
-    // Always truncate to convert to integer, same as Cocoa does for clicks
-    returnGlobalPoint = QPoint(globalPointF.x(), globalPointF.y());
-    QWidget *mouseGrabber = QWidget::mouseGrabber();
-    bool buttonDownNotBlockedByModal = qt_button_down && !QApplicationPrivate::isBlockedByModal(qt_button_down);
-    QWidget *popup = QApplication::activePopupWidget();
-
-    // Resolve the widget under the mouse:
-    QWidget *widgetUnderMouse = 0;
-    if (popup || qt_button_down || !nativeWidget || !nativeWidget->isVisible()) {
-        // Using QApplication::widgetAt for finding the widget under the mouse
-        // is most safe, since it ignores cocoas own mouse down redirections (which
-        // we need to be prepared for when using nativeWidget as starting point).
-        // (the only exception is for QMacNativeWidget, where QApplication::widgetAt fails).
-        // But it is also slower (I guess), so we try to avoid it and use nativeWidget if we can:
-        widgetUnderMouse = QApplication::widgetAt(returnGlobalPoint);
-    }
-
-    if (!widgetUnderMouse && nativeWidget) {
-        // Entering here should be the common case. We
-        // also handle the QMacNativeWidget fallback case.
-        QPoint p = nativeWidget->mapFromGlobal(returnGlobalPoint);
-        widgetUnderMouse = nativeWidget->childAt(p);
-        if (!widgetUnderMouse && nativeWidget->rect().contains(p))
-            widgetUnderMouse = nativeWidget;
-    }
-
-    if (widgetUnderMouse) {
-        // Check if widgetUnderMouse is blocked by a modal
-        // window, or the mouse if over the frame strut:
-        if (widgetUnderMouse == qt_button_down) {
-            // Small optimization to avoid an extra call to isBlockedByModal:
-            if (buttonDownNotBlockedByModal == false)
-                widgetUnderMouse = 0;
-        } else if (QApplicationPrivate::isBlockedByModal(widgetUnderMouse)) {
-            widgetUnderMouse = 0;
-        }
-
-        if (widgetUnderMouse && widgetUnderMouse->isWindow()) {
-            // Exclude the titlebar (and frame strut) when finding widget under mouse:
-            QPoint p = widgetUnderMouse->mapFromGlobal(returnGlobalPoint);
-            if (!widgetUnderMouse->rect().contains(p))
-                widgetUnderMouse = 0;
-        }
-    }
-    if (returnWidgetUnderMouse)
-        *returnWidgetUnderMouse = widgetUnderMouse;
-
-    // Resolve the target for the mouse event. Default will be
-    // widgetUnderMouse, except if there is a grab (popup/mouse/button-down):
-    if (popup && !mouseGrabber) {
-        // We special case handling of popups, since they have an implicitt mouse grab.
-        QWidget *candidate = buttonDownNotBlockedByModal ? qt_button_down : widgetUnderMouse;
-        if (!popup->isAncestorOf(candidate)) {
-            // INVARIANT: we have a popup, but the candidate is not
-            // in it. But the popup will grab the mouse anyway,
-            // except if the user scrolls:
-            if (eventType == QEvent::Wheel)
-                return 0;
-            returnLocalPoint = popup->mapFromGlobal(returnGlobalPoint);
-            return popup;
-        } else if (popup == candidate) {
-            // INVARIANT: The candidate is the popup itself, and not a child:
-            returnLocalPoint = popup->mapFromGlobal(returnGlobalPoint);
-            return popup;
-        } else {
-            // INVARIANT: The candidate is a child inside the popup:
-            returnLocalPoint = candidate->mapFromGlobal(returnGlobalPoint);
-            return candidate;
-        }
-    }
-
-    QWidget *target = mouseGrabber;
-    if (!target && buttonDownNotBlockedByModal)
-        target = qt_button_down;
-    if (!target)
-        target = widgetUnderMouse;
-    if (!target)
-        return 0;
-
-    returnLocalPoint = target->mapFromGlobal(returnGlobalPoint);
-    return target;
-}
-
-QPointer<QWidget> qt_last_native_mouse_receiver = 0;
-
-static inline void qt_mac_checkEnterLeaveForNativeWidgets(QWidget *maybeEnterWidget)
-{
-    // Dispatch enter/leave for the cases where QApplicationPrivate::sendMouseEvent do
-    // not. This will in general be the cases when alien widgets are not involved:
-    // 1. from a native widget to another native widget or
-    // 2. from a native widget to no widget
-    // 3. from no widget to a native or alien widget
-
-    if (qt_button_down || QWidget::mouseGrabber())
-        return;
-
-    if ((maybeEnterWidget == qt_last_native_mouse_receiver) && qt_last_native_mouse_receiver)
-        return;
-    if (maybeEnterWidget) {
-        if (!qt_last_native_mouse_receiver) {
-            // case 3
-            QApplicationPrivate::dispatchEnterLeave(maybeEnterWidget, 0);
-            qt_last_native_mouse_receiver = maybeEnterWidget->internalWinId() ? maybeEnterWidget : maybeEnterWidget->nativeParentWidget();
-        } else if (maybeEnterWidget->internalWinId()) {
-            // case 1
-            QApplicationPrivate::dispatchEnterLeave(maybeEnterWidget, qt_last_native_mouse_receiver);
-            qt_last_native_mouse_receiver = maybeEnterWidget->internalWinId() ? maybeEnterWidget : maybeEnterWidget->nativeParentWidget();
-        } // else at lest one of the widgets are alien, so enter/leave will be handled in QApplicationPrivate
-    } else {
-        if (qt_last_native_mouse_receiver) {
-            // case 2
-            QApplicationPrivate::dispatchEnterLeave(0, qt_last_native_mouse_receiver);
-            qt_last_mouse_receiver = 0;
-            qt_last_native_mouse_receiver = 0;
-        }
-    }
-}
-
-bool qt_mac_handleMouseEvent(NSEvent *event, QEvent::Type eventType, Qt::MouseButton button, QWidget *nativeWidget, bool fakeEvent)
-{
-    // Give the Input Manager a chance to process the mouse events.
-    NSInputManager *currentIManager = [NSInputManager currentInputManager];
-    if (currentIManager && [currentIManager wantsToHandleMouseEvents]) {
-        [currentIManager handleMouseEvent:event];
-    }
-
-    // Find the widget that should receive the event, and the widget under the mouse. Those
-    // can differ if an implicit or explicit mouse grab is active:
-    QWidget *widgetUnderMouse = 0;
-    QPoint localPoint, globalPoint;
-    QWidget *widgetToGetMouse = qt_mac_getTargetForMouseEvent(event, eventType, localPoint, globalPoint, nativeWidget, &widgetUnderMouse);
-    if (!widgetToGetMouse)
-        return false;
-
-    // From here on, we let nativeWidget actually be the native widget under widgetUnderMouse. The reason
-    // for this, is that qt_mac_getTargetForMouseEvent will set cocoa's mouse event redirection aside when
-    // determining which widget is under the mouse (in other words, it will usually ignore nativeWidget).
-    // nativeWidget will be used in QApplicationPrivate::sendMouseEvent to correctly dispatch enter/leave events.
-    if (widgetUnderMouse)
-        nativeWidget = widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget();
-    if (!nativeWidget)
-        return false;
-    NSView *view = qt_mac_effectiveview_for(nativeWidget);
-
-    // Handle tablet events (if any) first.
-    if (qt_mac_handleTabletEvent(view, event)) {
-        // Tablet event was handled. In Qt we aren't supposed to send the mouse event.
-        return true;
-    }
-
-    EventRef carbonEvent = static_cast<EventRef>(const_cast<void *>([event eventRef]));
-    if (qt_mac_sendMacEventToWidget(widgetToGetMouse, carbonEvent))
-        return true;
-
-    // Keep previousButton to make sure we don't send double click
-    // events when the user double clicks using two different buttons:
-    static Qt::MouseButton previousButton = Qt::NoButton;
-
-    Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
-    NSInteger clickCount = [event clickCount];
-    Qt::MouseButtons buttons = 0;
-    {
-        UInt32 mac_buttons;
-        if (GetEventParameter(carbonEvent, kEventParamMouseChord, typeUInt32, 0,
-                              sizeof(mac_buttons), 0, &mac_buttons) == noErr)
-            buttons = qt_mac_get_buttons(mac_buttons);
-        if (fakeEvent && buttons == 0)
-            buttons = qt_mac_get_buttons(QApplication::mouseButtons());
-    }
-
-    // Send enter/leave events for the cases when QApplicationPrivate::sendMouseEvent do not:
-    qt_mac_checkEnterLeaveForNativeWidgets(widgetUnderMouse);
-
-    switch (eventType) {
-    default:
-        qWarning("not handled! %d", eventType);
-        break;
-    case QEvent::MouseMove:
-        if (button == Qt::LeftButton && qt_leftButtonIsRightButton)
-            button = Qt::RightButton;
-        break;
-    case QEvent::MouseButtonPress:
-        qt_button_down = widgetUnderMouse;
-        if (clickCount % 2 == 0 && (previousButton == Qt::NoButton || previousButton == button))
-            eventType = QEvent::MouseButtonDblClick;
-        if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
-            button = Qt::RightButton;
-            qt_leftButtonIsRightButton = true;
-        }
-        break;
-    case QEvent::MouseButtonRelease:
-        if (button == Qt::LeftButton && qt_leftButtonIsRightButton) {
-            button = Qt::RightButton;
-            qt_leftButtonIsRightButton = false;
-        }
-        qt_button_down = 0;
-        break;
-    }
-
-    qt_mac_updateCursorWithWidgetUnderMouse(widgetUnderMouse);
-
-    DnDParams *dndParams = currentDnDParameters();
-    dndParams->view = view;
-    dndParams->theEvent = event;
-    dndParams->globalPoint = globalPoint;
-
-    // Send the mouse event:
-    QMouseEvent qme(eventType, localPoint, globalPoint, button, buttons, keyMods);
-    QApplicationPrivate::sendMouseEvent(
-                widgetToGetMouse, &qme, widgetUnderMouse, nativeWidget,
-                &qt_button_down, qt_last_mouse_receiver, true);
-
-    if (eventType == QEvent::MouseButtonPress && button == Qt::RightButton) {
-        QContextMenuEvent qcme(QContextMenuEvent::Mouse, localPoint, globalPoint, keyMods);
-        qt_sendSpontaneousEvent(widgetToGetMouse, &qcme);
-    }
-
-    if (eventType == QEvent::MouseButtonRelease) {
-        // A mouse button was released, which means that the implicit grab was
-        // released. We therefore need to re-check if should send (delayed) enter leave events:
-        // qt_button_down has now become NULL since the call at the top of the function. Also, since
-        // the relase might have closed a window, we dont give the nativeWidget hint
-        qt_mac_getTargetForMouseEvent(0, QEvent::None, localPoint, globalPoint, nativeWidget, &widgetUnderMouse);
-        qt_mac_checkEnterLeaveForNativeWidgets(widgetUnderMouse);
-    }
-
-    previousButton = button;
-    return true;
-}
-#endif
-
-bool qt_mac_handleTabletEvent(void * /*QCocoaView * */view, void * /*NSEvent * */tabletEvent)
-{
-#ifndef QT_MAC_USE_COCOA
-    Q_UNUSED(view);
-    Q_UNUSED(tabletEvent);
-    return false;
-#else
-    QT_MANGLE_NAMESPACE(QCocoaView) *theView = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
-    NSView *theNSView = static_cast<NSView *>(view);
-    NSEvent *theTabletEvent = static_cast<NSEvent *>(tabletEvent);
-
-    NSEventType eventType = [theTabletEvent type];
-    if (eventType != NSTabletPoint && [theTabletEvent subtype] != NSTabletPointEventSubtype)
-        return false; // Not a tablet event.
-
-    NSPoint windowPoint = [theTabletEvent locationInWindow];
-    NSPoint globalPoint = [[theTabletEvent window] convertBaseToScreen:windowPoint];
-
-    QWidget *qwidget = [theView qt_qwidget];
-    QWidget *widgetToGetMouse = qwidget;
-    QWidget *popup = qAppInstance()->activePopupWidget();
-    if (popup && popup != qwidget->window())
-        widgetToGetMouse = popup;
-
-    if (qt_mac_sendMacEventToWidget(widgetToGetMouse,
-                                static_cast<EventRef>(const_cast<void *>([theTabletEvent eventRef]))))
-        return true;
-    if (widgetToGetMouse != qwidget) {
-        theNSView = qt_mac_nativeview_for(widgetToGetMouse);
-        windowPoint = [[theNSView window] convertScreenToBase:globalPoint];
-    }
-    NSPoint localPoint = [theNSView convertPoint:windowPoint fromView:nil];
-    // Tablet events do not handle WA_TransparentForMouseEvents ATM
-    // In theory, people who set the WA_TransparentForMouseEvents attribute won't handle
-    // tablet events either in which case they will fall into the mouse event case and get
-    // them passed on. This will NOT handle the raw events, but that might not be a big problem.
-
-    const QMacTabletHash *tabletHash = qt_mac_tablet_hash();
-    if (!tabletHash->contains([theTabletEvent deviceID])) {
-        qWarning("QCocoaView handleTabletEvent: This tablet device is unknown"
-                 " (received no proximity event for it). Discarding event.");
-        return false;
-    }
-    const QTabletDeviceData &deviceData = tabletHash->value([theTabletEvent deviceID]);
-
-
-    QEvent::Type qType;
-    switch (eventType) {
-    case NSLeftMouseDown:
-    case NSRightMouseDown:
-        qType = QEvent::TabletPress;
-        break;
-    case NSLeftMouseUp:
-    case NSRightMouseUp:
-        qType = QEvent::TabletRelease;
-        break;
-    case NSMouseMoved:
-    case NSTabletPoint:
-    case NSLeftMouseDragged:
-    case NSRightMouseDragged:
-    default:
-        qType = QEvent::TabletMove;
-        break;
-    }
-
-    qreal pressure;
-    if (eventType != NSMouseMoved) {
-        pressure = [theTabletEvent pressure];
-    } else {
-        pressure = 0.0;
-    }
-
-    NSPoint tilt = [theTabletEvent tilt];
-    int xTilt = qRound(tilt.x * 60.0);
-    int yTilt = qRound(tilt.y * -60.0);
-    qreal tangentialPressure = 0;
-    qreal rotation = 0;
-    int z = 0;
-    if (deviceData.capabilityMask & 0x0200)
-        z = [theTabletEvent absoluteZ];
-
-    if (deviceData.capabilityMask & 0x0800)
-        tangentialPressure = [theTabletEvent tangentialPressure];
-
-    rotation = [theTabletEvent rotation];
-    QPointF hiRes = flipPoint(globalPoint);
-    QTabletEvent qtabletEvent(qType, QPoint(localPoint.x, localPoint.y),
-                              hiRes.toPoint(), hiRes,
-                              deviceData.tabletDeviceType, deviceData.tabletPointerType,
-                              pressure, xTilt, yTilt, tangentialPressure, rotation, z,
-                              qt_cocoaModifiers2QtModifiers([theTabletEvent modifierFlags]),
-                              deviceData.tabletUniqueID);
-
-    qt_sendSpontaneousEvent(widgetToGetMouse, &qtabletEvent);
-    return qtabletEvent.isAccepted();
-#endif
-}
-
-void qt_mac_updateContentBorderMetricts(void * /*OSWindowRef */window, const ::HIContentBorderMetrics &metrics)
-{
-    OSWindowRef theWindow = static_cast<OSWindowRef>(window);
-#if !defined(QT_MAC_USE_COCOA)
-#  if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-        ::HIWindowSetContentBorderThickness(theWindow, &metrics);
-    }
-#  else
-    Q_UNUSED(window);
-    Q_UNUSED(metrics);
-#  endif
-#else
-    if ([theWindow styleMask] & NSTexturedBackgroundWindowMask)
-        [theWindow setContentBorderThickness:metrics.top forEdge:NSMaxYEdge];
-    [theWindow setContentBorderThickness:metrics.bottom forEdge:NSMinYEdge];
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-void qt_mac_replaceDrawRect(void * /*OSWindowRef */window, QWidgetPrivate *widget)
-{
-    QMacCocoaAutoReleasePool pool;
-    OSWindowRef theWindow = static_cast<OSWindowRef>(window);
-    if(!theWindow)
-        return;
-    id theClass = [[[theWindow contentView] superview] class];
-    // What we do here is basically to add a new selector to NSThemeFrame called
-    // "drawRectOriginal:" which will contain the original implementation of
-    // "drawRect:". After that we get the new implementation from QCocoaWindow
-    // and exchange them. The new implementation is called drawRectSpecial.
-    // We cannot just add the method because it might have been added before and since
-    // we cannot remove a method once it has been added we need to ask QCocoaWindow if
-    // we did the swap or not.
-    if(!widget->drawRectOriginalAdded) {
-        Method m2 = class_getInstanceMethod(theClass, @selector(drawRect:));
-        if(!m2) {
-            // This case is pretty extreme, no drawRect means no drawing!
-            return;
-        }
-        class_addMethod(theClass, @selector(drawRectOriginal:), method_getImplementation(m2), method_getTypeEncoding(m2));
-        widget->drawRectOriginalAdded = true;
-    }
-    if(widget->originalDrawMethod) {
-        Method m0 = class_getInstanceMethod([theWindow class], @selector(drawRectSpecial:));
-        if(!m0) {
-            // Ok, this means the methods were never swapped. Just ignore
-            return;
-        }
-        Method m1 = class_getInstanceMethod(theClass, @selector(drawRect:));
-        if(!m1) {
-            // Ok, this means the methods were never swapped. Just ignore
-            return;
-        }
-        // We have the original method here. Proceed and swap the methods.
-        method_exchangeImplementations(m1, m0);
-        widget->originalDrawMethod = false;
-        [theWindow display];
-    }
-}
-
-void qt_mac_replaceDrawRectOriginal(void * /*OSWindowRef */window, QWidgetPrivate *widget)
-{
-    QMacCocoaAutoReleasePool pool;
-    OSWindowRef theWindow = static_cast<OSWindowRef>(window);
-    id theClass = [[[theWindow contentView] superview] class];
-    // Now we need to revert the methods to their original state.
-    // We cannot remove the method, so we just keep track of it in QCocoaWindow.
-    Method m0 = class_getInstanceMethod([theWindow class], @selector(drawRectSpecial:));
-    if(!m0) {
-        // Ok, this means the methods were never swapped. Just ignore
-        return;
-    }
-    Method m1 = class_getInstanceMethod(theClass, @selector(drawRect:));
-    if(!m1) {
-        // Ok, this means the methods were never swapped. Just ignore
-        return;
-    }
-    method_exchangeImplementations(m1, m0);
-    widget->originalDrawMethod = true;
-    [theWindow display];
-}
-#endif // QT_MAC_USE_COCOA
-
-#ifdef QT_MAC_USE_COCOA
-void qt_mac_showBaseLineSeparator(void * /*OSWindowRef */window, bool show)
-{
-    if(!window)
-        return;
-    QMacCocoaAutoReleasePool pool;
-    OSWindowRef theWindow = static_cast<OSWindowRef>(window);
-    NSToolbar *macToolbar = [theWindow toolbar];
-    [macToolbar setShowsBaselineSeparator:show];
-}
-#endif // QT_MAC_USE_COCOA
-
-QStringList qt_mac_NSArrayToQStringList(void *nsarray)
-{
-    QStringList result;
-    NSArray *array = static_cast<NSArray *>(nsarray);
-    for (NSUInteger i=0; i<[array count]; ++i)
-        result << qt_mac_NSStringToQString([array objectAtIndex:i]);
-    return result;
-}
-
-void *qt_mac_QStringListToNSMutableArrayVoid(const QStringList &list)
-{
-    NSMutableArray *result = [NSMutableArray arrayWithCapacity:list.size()];
-    for (int i=0; i<list.size(); ++i){
-        [result addObject:reinterpret_cast<const NSString *>(QCFString::toCFStringRef(list[i]))];
-    }
-    return result;
-}
-
-#ifdef QT_MAC_USE_COCOA
-void qt_syncCocoaTitleBarButtons(OSWindowRef window, QWidget *widgetForWindow)
-{
-    if (!widgetForWindow)
-        return;
-
-    Qt::WindowFlags flags = widgetForWindow->windowFlags();
-    bool customize = flags & Qt::CustomizeWindowHint;
-
-    NSButton *btn = [window standardWindowButton:NSWindowZoomButton];
-    // BOOL is not an int, so the bitwise AND doesn't work.
-    bool go = uint(customize && !(flags & Qt::WindowMaximizeButtonHint)) == 0;
-    [btn setEnabled:go];
-
-    btn = [window standardWindowButton:NSWindowMiniaturizeButton];
-    go = uint(customize && !(flags & Qt::WindowMinimizeButtonHint)) == 0;
-    [btn setEnabled:go];
-
-    btn = [window standardWindowButton:NSWindowCloseButton];
-    go = uint(customize && !(flags & Qt::WindowSystemMenuHint
-                             || flags & Qt::WindowCloseButtonHint)) == 0;
-    [btn setEnabled:go];
-
-    [window setShowsToolbarButton:uint(flags & Qt::MacWindowToolBarButtonHint) != 0];
-}
-#endif // QT_MAC_USE_COCOA
-
-// Carbon: Make sure you call QDEndContext on the context when done with it.
-CGContextRef qt_mac_graphicsContextFor(QWidget *widget)
-{
-    if (!widget)
-        return 0;
-
-#ifndef QT_MAC_USE_COCOA
-    CGContextRef context;
-    CGrafPtr port = GetWindowPort(qt_mac_window_for(widget));
-    QDBeginCGContext(port, &context);
-#else
-    CGContextRef context = (CGContextRef)[[NSGraphicsContext graphicsContextWithWindow:qt_mac_window_for(widget)] graphicsPort];
-#endif
-    return context;
-}
-
-void qt_mac_dispatchPendingUpdateRequests(QWidget *widget)
-{
-    if (!widget)
-        return;
-#ifndef QT_MAC_USE_COCOA
-    HIViewRender(qt_mac_nativeview_for(widget));
-#else
-    [qt_mac_nativeview_for(widget) displayIfNeeded];
-#endif
-}
-
-CGFloat qt_mac_get_scalefactor()
-{
-#ifndef QT_MAC_USE_COCOA
-    return HIGetScaleFactor();
-#endif
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
-    NSScreen *mainScreen = [NSScreen mainScreen];
-    if ([mainScreen respondsToSelector:@selector(backingScaleFactor)])
-        return [mainScreen backingScaleFactor];
-#endif
-    return 1.0;
-}
-
-QString qt_mac_get_pasteboardString(OSPasteboardRef paste)
-{
-    QMacCocoaAutoReleasePool pool;
-    NSPasteboard *pb = nil;
-    CFStringRef pbname;
-    if (PasteboardCopyName(paste, &pbname) == noErr) {
-        pb = [NSPasteboard pasteboardWithName:const_cast<NSString *>(reinterpret_cast<const NSString *>(pbname))];
-        CFRelease(pbname);
-    } else {
-        pb = [NSPasteboard generalPasteboard];
-    }
-    if (pb) {
-        NSString *text = [pb stringForType:NSStringPboardType];
-        if (text)
-            return qt_mac_NSStringToQString(text);
-    }
-    return QString();
-}
-
-QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height)
-{
-    QPixmap ret(width, height);
-    ret.fill(QColor(0, 0, 0, 0));
-
-    CGRect rect = CGRectMake(0, 0, width, height);
-
-    CGContextRef ctx = qt_mac_cg_context(&ret);
-    CGAffineTransform old_xform = CGContextGetCTM(ctx);
-    CGContextConcatCTM(ctx, CGAffineTransformInvert(old_xform));
-    CGContextConcatCTM(ctx, CGAffineTransformIdentity);
-
-    ::RGBColor b;
-    b.blue = b.green = b.red = 255*255;
-    PlotIconRefInContext(ctx, &rect, kAlignNone, kTransformNone, &b, kPlotIconRefNormalFlags, icon);
-    CGContextRelease(ctx);
-    return ret;
-}
-
-void qt_mac_constructQIconFromIconRef(const IconRef icon, const IconRef overlayIcon, QIcon *retIcon, QStyle::StandardPixmap standardIcon)
-{
-    int size = 16;
-    while (size <= 128) {
-
-        const QString cacheKey = QLatin1String("qt_mac_constructQIconFromIconRef") + QString::number(standardIcon) + QString::number(size);
-        QPixmap mainIcon;
-        if (standardIcon >= QStyle::SP_CustomBase) {
-            mainIcon = qt_mac_convert_iconref(icon, size, size);
-        } else if (QPixmapCache::find(cacheKey, mainIcon) == false) {
-            mainIcon = qt_mac_convert_iconref(icon, size, size);
-            QPixmapCache::insert(cacheKey, mainIcon);
-        }
-
-        if (overlayIcon) {
-            int littleSize = size / 2;
-            QPixmap overlayPix = qt_mac_convert_iconref(overlayIcon, littleSize, littleSize);
-            QPainter painter(&mainIcon);
-            painter.drawPixmap(size - littleSize, size - littleSize, overlayPix);
-        }
-
-        retIcon->addPixmap(mainIcon);
-        size += size;  // 16 -> 32 -> 64 -> 128
-    }
-}
-
-#ifdef QT_MAC_USE_COCOA
-void qt_mac_menu_collapseSeparators(void */*NSMenu **/ theMenu, bool collapse)
-{
-    QMacCocoaAutoReleasePool pool;
-    OSMenuRef menu = static_cast<OSMenuRef>(theMenu);
-    if (collapse) {
-        bool previousIsSeparator = true; // setting to true kills all the separators placed at the top.
-        NSMenuItem *previousItem = nil;
-            
-        NSArray *itemArray = [menu itemArray];
-        for (unsigned int i = 0; i < [itemArray count]; ++i) {
-            NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]);
-            if ([item isSeparatorItem]) {
-                [item setHidden:previousIsSeparator];
-            }
-
-            if (![item isHidden]) {
-                previousItem = item;
-                previousIsSeparator = ([previousItem isSeparatorItem]);
-            }
-        }
-
-        // We now need to check the final item since we don't want any separators at the end of the list.
-        if (previousItem && previousIsSeparator)
-            [previousItem setHidden:YES];
-    } else {
-        NSArray *itemArray = [menu itemArray];
-        for (unsigned int i = 0; i < [itemArray count]; ++i) {
-            NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]);
-            if (QAction *action = reinterpret_cast<QAction *>([item tag]))
-                [item setHidden:!action->isVisible()];
-        }
-    }
-}
-
-class CocoaPostMessageAfterEventLoopExitHelp : public QObject
-{
-    id target;
-    SEL selector;
-    int argCount;
-    id arg1;
-    id arg2;
-public:
-    CocoaPostMessageAfterEventLoopExitHelp(id target, SEL selector, int argCount, id arg1, id arg2)
-        : target(target), selector(selector), argCount(argCount), arg1(arg1), arg2(arg2){
-        deleteLater();
-    }
-
-    ~CocoaPostMessageAfterEventLoopExitHelp()
-    {
-        qt_cocoaPostMessage(target, selector, argCount, arg1, arg2);
-    }
-};
-
-void qt_cocoaPostMessage(id target, SEL selector, int argCount, id arg1, id arg2)
-{
-    // WARNING: data1 and data2 is truncated to from 64-bit to 32-bit on OS 10.5!
-    // That is why we need to split the address in two parts:
-    QCocoaPostMessageArgs *args = new QCocoaPostMessageArgs(target, selector, argCount, arg1, arg2);
-    quint32 lower = quintptr(args);
-    quint32 upper = quintptr(args) >> 32;
-    NSEvent *e = [NSEvent otherEventWithType:NSApplicationDefined
-        location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0
-        context:nil subtype:QtCocoaEventSubTypePostMessage data1:lower data2:upper];
-    [[NSApplication sharedApplication] postEvent:e atStart:NO];
-}
-
-void qt_cocoaPostMessageAfterEventLoopExit(id target, SEL selector, int argCount, id arg1, id arg2)
-{
-    if (QApplicationPrivate::instance()->threadData->eventLoops.size() <= 1)
-        qt_cocoaPostMessage(target, selector, argCount, arg1, arg2);
-    else
-        new CocoaPostMessageAfterEventLoopExitHelp(target, selector, argCount, arg1, arg2);
-}
-
-#endif
-
-QMacCocoaAutoReleasePool::QMacCocoaAutoReleasePool()
-{
-#ifndef QT_MAC_USE_COCOA
-    NSApplicationLoad();
-#endif
-    pool = (void*)[[NSAutoreleasePool alloc] init];
-}
-
-QMacCocoaAutoReleasePool::~QMacCocoaAutoReleasePool()
-{
-    [(NSAutoreleasePool*)pool release];
-}
-
-void qt_mac_post_retranslateAppMenu()
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    qt_cocoaPostMessage([[NSApplication sharedApplication] QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)], @selector(qtTranslateApplicationMenu));
-#endif
-}
-
-QWidgetPrivate *QMacScrollOptimization::_target = 0;
-bool QMacScrollOptimization::_inWheelEvent = false;
-int QMacScrollOptimization::_dx = 0;
-int QMacScrollOptimization::_dy = 0;
-QRect QMacScrollOptimization::_scrollRect = QRect(0, 0, -1, -1);
-
-#ifdef QT_MAC_USE_COCOA
-// This method implements the magic for the drawRectSpecial method.
-// We draw a line at the upper edge of the content view in order to
-// override the title baseline.
-void macDrawRectOnTop(void * /*OSWindowRef */window)
-{
-    OSWindowRef theWindow = static_cast<OSWindowRef>(window);
-    NSView *contentView = [theWindow contentView];
-    if(!contentView)
-        return;
-    // Get coordinates of the content view
-    NSRect contentRect = [contentView frame];
-    // Draw a line on top of the already drawn line.
-    // We need to check if we are active or not to use the proper color.
-    if([theWindow isKeyWindow] || [theWindow isMainWindow]) {
-        [[NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0] set];
-    } else {
-        [[NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0] set];
-    }
-    NSPoint origin = NSMakePoint(0, contentRect.size.height);
-    NSPoint end = NSMakePoint(contentRect.size.width, contentRect.size.height);
-    [NSBezierPath strokeLineFromPoint:origin toPoint:end];
-}
-
-// This method will (or at least should) get called only once.
-// Its mission is to find out if we are active or not. If we are active
-// we assume that we were launched via finder, otherwise we assume
-// we were called from the command line. The distinction is important,
-// since in the first case we don't need to trigger a paintEvent, while
-// in the second case we do.
-void macSyncDrawingOnFirstInvocation(void * /*OSWindowRef */window)
-{
-    OSWindowRef theWindow = static_cast<OSWindowRef>(window);
-    NSApplication *application = [NSApplication sharedApplication];
-    NSToolbar *toolbar = [theWindow toolbar];
-    if([application isActive]) {
-        // Launched from finder
-        [toolbar setShowsBaselineSeparator:NO];
-    } else {
-        // Launched from commandline
-        [toolbar setVisible:false];
-        [toolbar setShowsBaselineSeparator:NO];
-        [toolbar setVisible:true];
-        [theWindow display];
-    }
-}
-
-void qt_cocoaStackChildWindowOnTopOfOtherChildren(QWidget *childWidget)
-{
-    if (!childWidget)
-        return;
-
-    QWidget *parent = childWidget->parentWidget();
-    if (childWidget->isWindow() && parent) {
-        if ([[qt_mac_window_for(parent) childWindows] containsObject:qt_mac_window_for(childWidget)]) {
-            QWidgetPrivate *d = qt_widget_private(childWidget);
-            d->setSubWindowStacking(false);
-            d->setSubWindowStacking(true);
-        }
-    }
-}
-
-void qt_mac_display(QWidget *widget)
-{
-    NSView *theNSView = qt_mac_nativeview_for(widget);
-    [theNSView display];
-}
-
-void qt_mac_setNeedsDisplay(QWidget *widget)
-{
-    NSView *theNSView = qt_mac_nativeview_for(widget);
-    [theNSView setNeedsDisplay:YES];
-}
-
-void qt_mac_setNeedsDisplayInRect(QWidget *widget, QRegion region)
-{
-    NSView *theNSView = qt_mac_nativeview_for(widget);
-    if (region.isEmpty()) {
-        [theNSView setNeedsDisplay:YES];
-        return;
-    }
-
-    QVector<QRect> rects = region.rects();
-    for (int i = 0; i < rects.count(); ++i) {
-        const QRect &rect = rects.at(i);
-        NSRect nsrect = NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height());
-        [theNSView setNeedsDisplayInRect:nsrect];
-    }
-
-}
-
-#endif // QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qt_cocoa_helpers_mac_p.h b/src/gui/kernel/qt_cocoa_helpers_mac_p.h
deleted file mode 100644 (file)
index c22687f..0000000
+++ /dev/null
@@ -1,340 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#ifndef QT_COCOA_HELPERS_MAC_P_H
-#define QT_COCOA_HELPERS_MAC_P_H
-
-//
-//  W A R N I N G
-//  -------------
-//
-// This file is not part of the Qt API.  It exists for the convenience
-// of qapplication_*.cpp, qwidget*.cpp, qcolor_x11.cpp, qfiledialog.cpp
-// and many other.  This header file may change from version to version
-// without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <qt_mac_p.h>
-
-#include <qapplication.h>
-#include <qdesktopwidget.h>
-#include <qwidget.h>
-#include <qevent.h>
-#include <qhash.h>
-#include <qlabel.h>
-#include <qpointer.h>
-#include <qstyle.h>
-#include <qstyleoption.h>
-#include <qstylepainter.h>
-#include <qtimer.h>
-#include <qtooltip.h>
-#include <qeffects_p.h>
-#include <qwidget_p.h>
-#include <qtextdocument.h>
-#include <qdebug.h>
-#include <qpoint.h>
-#include "qt_mac_p.h"
-
-struct HIContentBorderMetrics;
-struct TabletProximityRec;
-
-#ifdef Q_WS_MAC32
-typedef struct _NSPoint NSPoint; // Just redefine here so I don't have to pull in all of Cocoa.
-#else
-typedef struct CGPoint NSPoint;
-#endif
-
-QT_BEGIN_NAMESPACE
-
-enum {
-    QtCocoaEventSubTypeWakeup       = SHRT_MAX,
-    QtCocoaEventSubTypePostMessage  = SHRT_MAX-1
-};
-
-Qt::MouseButtons qt_mac_get_buttons(int buttons);
-Qt::MouseButton qt_mac_get_button(EventMouseButton button);
-void macWindowFade(void * /*OSWindowRef*/ window, float durationSeconds = 0.15);
-bool macWindowIsTextured(void * /*OSWindowRef*/ window);
-void macWindowToolbarShow(const QWidget *widget, bool show );
-void macWindowToolbarSet( void * /*OSWindowRef*/ window, void* toolbarRef );
-bool macWindowToolbarIsVisible( void * /*OSWindowRef*/ window );
-void macWindowSetHasShadow( void * /*OSWindowRef*/ window, bool hasShadow );
-void macWindowFlush(void * /*OSWindowRef*/ window);
-void macSendToolbarChangeEvent(QWidget *widget);
-void qt_mac_updateContentBorderMetricts(void * /*OSWindowRef */window, const ::HIContentBorderMetrics &metrics);
-void qt_mac_replaceDrawRect(void * /*OSWindowRef */window, QWidgetPrivate *widget);
-void qt_mac_replaceDrawRectOriginal(void * /*OSWindowRef */window, QWidgetPrivate *widget);
-void qt_mac_showBaseLineSeparator(void * /*OSWindowRef */window, bool show);
-void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm);
-void qt_mac_update_mouseTracking(QWidget *widget);
-OSStatus qt_mac_drawCGImage(CGContextRef cg, const CGRect *inbounds, CGImageRef);
-bool qt_mac_checkForNativeSizeGrip(const QWidget *widget);
-void qt_dispatchTabletProximityEvent(void * /*NSEvent * */ tabletEvent);
-#ifdef QT_MAC_USE_COCOA
-bool qt_dispatchKeyEventWithCocoa(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent);
-// These methods exists only for supporting unified mode.
-void macDrawRectOnTop(void * /*OSWindowRef */ window);
-void macSyncDrawingOnFirstInvocation(void * /*OSWindowRef */window);
-void qt_cocoaStackChildWindowOnTopOfOtherChildren(QWidget *widget);
-void qt_mac_menu_collapseSeparators(void * /*NSMenu */ menu, bool collapse);
-#endif
-bool qt_dispatchKeyEvent(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent);
-void qt_dispatchModifiersChanged(void * /*NSEvent * */flagsChangedEvent, QWidget *widgetToGetEvent);
-bool qt_mac_handleTabletEvent(void * /*QCocoaView * */view, void * /*NSEvent * */event);
-inline QApplication *qAppInstance() { return static_cast<QApplication *>(QCoreApplication::instance()); }
-void qt_dispatchTabletProximityEvent(const ::TabletProximityRec &proxRec);
-Qt::KeyboardModifiers qt_cocoaModifiers2QtModifiers(ulong modifierFlags);
-Qt::KeyboardModifiers qt_cocoaDragOperation2QtModifiers(uint dragOperations);
-QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height);
-void qt_mac_constructQIconFromIconRef(const IconRef icon, const IconRef overlayIcon, QIcon *retIcon,
-                                      QStyle::StandardPixmap standardIcon = QStyle::SP_CustomBase);
-
-#if defined(QT_MAC_USE_COCOA) && defined(__OBJC__)
-struct DnDParams
-{
-    NSView *view;
-    NSEvent *theEvent;
-    QPoint globalPoint;
-    NSDragOperation performedAction;
-};
-
-DnDParams *macCurrentDnDParameters();
-NSDragOperation qt_mac_mapDropAction(Qt::DropAction action);
-NSDragOperation qt_mac_mapDropActions(Qt::DropActions actions);
-Qt::DropAction qt_mac_mapNSDragOperation(NSDragOperation nsActions);
-Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions);
-
-QWidget *qt_mac_getTargetForKeyEvent(QWidget *widgetThatReceivedEvent);
-QWidget *qt_mac_getTargetForMouseEvent(NSEvent *event, QEvent::Type eventType,
-    QPoint &returnLocalPoint, QPoint &returnGlobalPoint, QWidget *nativeWidget, QWidget **returnWidgetUnderMouse);
-bool qt_mac_handleMouseEvent(NSEvent *event, QEvent::Type eventType, Qt::MouseButton button, QWidget *nativeWidget, bool fakeEvent = false);
-void qt_mac_handleNonClientAreaMouseEvent(NSWindow *window, NSEvent *event);
-#endif
-
-inline int flipYCoordinate(int y)
-{
-    return QApplication::desktop()->screenGeometry(0).height() - y;    
-}
-
-inline qreal flipYCoordinate(qreal y)
-{
-    return QApplication::desktop()->screenGeometry(0).height() - y;
-}
-
-QPointF flipPoint(const NSPoint &p);
-NSPoint flipPoint(const QPoint &p);
-NSPoint flipPoint(const QPointF &p);
-
-QStringList qt_mac_NSArrayToQStringList(void *nsarray);
-void *qt_mac_QStringListToNSMutableArrayVoid(const QStringList &list);
-
-void qt_syncCocoaTitleBarButtons(OSWindowRef window, QWidget *widgetForWindow);
-
-CGFloat qt_mac_get_scalefactor();
-QString qt_mac_get_pasteboardString(OSPasteboardRef paste);
-
-#ifdef __OBJC__
-inline NSMutableArray *qt_mac_QStringListToNSMutableArray(const QStringList &qstrlist)
-{ return reinterpret_cast<NSMutableArray *>(qt_mac_QStringListToNSMutableArrayVoid(qstrlist)); }
-
-inline QString qt_mac_NSStringToQString(const NSString *nsstr)
-{ return QCFString::toQString(reinterpret_cast<const CFStringRef>(nsstr)); }
-
-inline NSString *qt_mac_QStringToNSString(const QString &qstr)
-{ return [const_cast<NSString *>(reinterpret_cast<const NSString *>(QCFString::toCFStringRef(qstr))) autorelease]; }
-
-#ifdef QT_MAC_USE_COCOA
-class QCocoaPostMessageArgs {
-public:
-    id target;
-    SEL selector;
-    int argCount;
-    id arg1;
-    id arg2;
-    QCocoaPostMessageArgs(id target, SEL selector, int argCount=0, id arg1=0, id arg2=0)
-        : target(target), selector(selector), argCount(argCount), arg1(arg1), arg2(arg2)
-    {
-        [target retain];
-        [arg1 retain];
-        [arg2 retain];
-    }
-
-    ~QCocoaPostMessageArgs()
-    {
-        [arg2 release];
-        [arg1 release];
-        [target release];
-    }
-};
-void qt_cocoaPostMessage(id target, SEL selector, int argCount=0, id arg1=0, id arg2=0);
-void qt_cocoaPostMessageAfterEventLoopExit(id target, SEL selector, int argCount=0, id arg1=0, id arg2=0);
-#endif
-
-#endif
-
-class QMacScrollOptimization {
-    // This class is made to optimize for the case when the user
-    // scrolls both horizontally and vertically at the same
-    // time. This will result in two QWheelEvents (one for each
-    // direction), which will typically result in two calls to
-    // QWidget::_scroll_sys. Rather than copying pixels twize on
-    // screen because of this, we add this helper class to try to
-    // get away with only one blit.
-    static QWidgetPrivate *_target;
-    static bool _inWheelEvent;
-    static int _dx;
-    static int _dy;
-    static QRect _scrollRect;
-
-public:
-    static void initDelayedScroll()
-    {
-        _inWheelEvent = true;
-    }
-
-    static bool delayScroll(QWidgetPrivate *target, int dx, int dy, const QRect &scrollRect)
-    {
-        if (!_inWheelEvent)
-            return false;
-        if (_target && _target != target)
-            return false;
-        if (_scrollRect.width() != -1 && _scrollRect != scrollRect)
-            return false;
-
-        _target = target;
-        _dx += dx;
-        _dy += dy;
-        _scrollRect = scrollRect;
-        return true;
-    }
-
-    static void performDelayedScroll()
-    {
-        if (!_inWheelEvent)
-            return;
-        _inWheelEvent = false;
-        if (!_target)
-            return;
-
-        _target->scroll_sys(_dx, _dy, _scrollRect);
-
-        _target = 0;
-        _dx = 0;
-        _dy = 0;
-        _scrollRect = QRect(0, 0, -1, -1);
-    }
-};
-
-void qt_mac_post_retranslateAppMenu();
-
-#ifdef QT_MAC_USE_COCOA
-void qt_mac_display(QWidget *widget);
-void qt_mac_setNeedsDisplay(QWidget *widget);
-void qt_mac_setNeedsDisplayInRect(QWidget *widget, QRegion region);
-#endif // QT_MAC_USE_COCOA
-
-
-// Utility functions to ease the use of Core Graphics contexts.
-
-inline void qt_mac_retain_graphics_context(CGContextRef context)
-{
-    CGContextRetain(context);
-    CGContextSaveGState(context);
-}
-
-inline void qt_mac_release_graphics_context(CGContextRef context)
-{
-    CGContextRestoreGState(context);
-    CGContextRelease(context);
-}
-
-inline void qt_mac_draw_image(CGContextRef context, CGContextRef imageContext, CGRect area, CGRect drawingArea)
-{
-    CGImageRef image = CGBitmapContextCreateImage(imageContext);
-    CGImageRef subImage = CGImageCreateWithImageInRect(image, area);
-
-    CGContextTranslateCTM (context, 0, drawingArea.origin.y + CGRectGetMaxY(drawingArea));
-    CGContextScaleCTM(context, 1, -1);
-    CGContextDrawImage(context, drawingArea, subImage);
-
-    CGImageRelease(subImage);
-    CGImageRelease(image);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_COCOA_HELPERS_MAC_P_H
diff --git a/src/gui/kernel/qt_mac.cpp b/src/gui/kernel/qt_mac.cpp
deleted file mode 100644 (file)
index 445edf9..0000000
+++ /dev/null
@@ -1,173 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qt_mac_p.h>
-#include <qimage.h>
-#include <qdebug.h>
-#include <qfont.h>
-
-QT_BEGIN_NAMESPACE
-#ifdef QT_MAC_USE_COCOA
-static CTFontRef CopyCTThemeFont(ThemeFontID themeID)
-{
-    CTFontUIFontType ctID = HIThemeGetUIFontType(themeID);
-    return CTFontCreateUIFontForLanguage(ctID, 0, 0);
-}
-#endif
-
-QFont qfontForThemeFont(ThemeFontID themeID)
-{
-#ifndef QT_MAC_USE_COCOA
-    static const ScriptCode Script = smRoman;
-    Str255 f_name;
-    SInt16 f_size;
-    Style f_style;
-    GetThemeFont(themeID, Script, f_name, &f_size, &f_style);
-    return QFont(qt_mac_from_pascal_string(f_name), f_size,
-                 (f_style & ::bold) ? QFont::Bold : QFont::Normal,
-                 (bool)(f_style & ::italic));
-#else
-    QCFType<CTFontRef> ctfont = CopyCTThemeFont(themeID);
-    QString familyName = QCFString(CTFontCopyFamilyName(ctfont));
-    QCFType<CFDictionaryRef> dict = CTFontCopyTraits(ctfont);
-    CFNumberRef num = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, kCTFontWeightTrait));
-    float fW;
-    CFNumberGetValue(num, kCFNumberFloat32Type, &fW);
-    QFont::Weight wght = fW > 0. ? QFont::Bold : QFont::Normal;
-    num = static_cast<CFNumberRef>(CFDictionaryGetValue(dict, kCTFontSlantTrait));
-    CFNumberGetValue(num, kCFNumberFloatType, &fW);
-    bool italic = (fW != 0.0);
-    return QFont(familyName, CTFontGetSize(ctfont), wght, italic);
-#endif
-}
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-static QColor qcolorFromCGColor(CGColorRef cgcolor)
-{
-    QColor pc;
-    CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(cgcolor));
-    const CGFloat *components = CGColorGetComponents(cgcolor);
-    if (model == kCGColorSpaceModelRGB) {
-        pc.setRgbF(components[0], components[1], components[2], components[3]);
-    } else if (model == kCGColorSpaceModelCMYK) {
-        pc.setCmykF(components[0], components[1], components[2], components[3]);
-    } else if (model == kCGColorSpaceModelMonochrome) {
-        pc.setRgbF(components[0], components[0], components[0], components[1]);
-    } else {
-        // Colorspace we can't deal with.
-        qWarning("Qt: qcolorFromCGColor: cannot convert from colorspace model: %d", model);
-        Q_ASSERT(false);
-    }
-    return pc;
-}
-
-static inline QColor leopardBrush(ThemeBrush brush)
-{
-    QCFType<CGColorRef> cgClr = 0;
-    HIThemeBrushCreateCGColor(brush, &cgClr);
-    return qcolorFromCGColor(cgClr);
-}
-#endif
-
-QColor qcolorForTheme(ThemeBrush brush)
-{
-#ifndef QT_MAC_USE_COCOA
-#  if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-        return leopardBrush(brush);
-    } else
-#  endif
-    {
-        RGBColor rgbcolor;
-        GetThemeBrushAsColor(brush, 32, true, &rgbcolor);
-        return QColor(rgbcolor.red / 256, rgbcolor.green / 256, rgbcolor.blue / 256);
-    }
-#else
-    return leopardBrush(brush);
-#endif
-}
-
-QColor qcolorForThemeTextColor(ThemeTextColor themeColor)
-{
-#ifdef Q_OS_MAC32
-    RGBColor c;
-    GetThemeTextColor(themeColor, 32, true, &c);
-    QColor color = QColor(c.red / 256, c.green / 256, c.blue / 256);
-    return color;
-#else
-    // There is no equivalent to GetThemeTextColor in 64-bit and it was rather bad that
-    // I didn't file a request to implement this for Snow Leopard. So, in the meantime
-    // I've encoded the values from the GetThemeTextColor. This is not exactly ideal
-    // as if someone really wants to mess with themeing, these colors will be wrong.
-    // It also means that we need to make sure the values for differences between
-    // OS releases (and it will be likely that we are a step behind.)
-    switch (themeColor) {
-    case kThemeTextColorAlertActive:
-    case kThemeTextColorTabFrontActive:
-    case kThemeTextColorBevelButtonActive:
-    case kThemeTextColorListView:
-    case kThemeTextColorPlacardActive:
-    case kThemeTextColorPopupButtonActive:
-    case kThemeTextColorPopupLabelActive:
-    case kThemeTextColorPushButtonActive:
-        return Qt::black;
-    case kThemeTextColorAlertInactive:
-    case kThemeTextColorDialogInactive:
-    case kThemeTextColorPlacardInactive:
-        return QColor(69, 69, 69, 255);
-    case kThemeTextColorPopupButtonInactive:
-    case kThemeTextColorPopupLabelInactive:
-    case kThemeTextColorPushButtonInactive:
-    case kThemeTextColorTabFrontInactive:
-    case kThemeTextColorBevelButtonInactive:
-        return QColor(127, 127, 127, 255);
-    default: {
-        QImage nativeImage(16,16, QImage::systemFormat());
-        CGRect cgrect = CGRectMake(0, 0, 16, 16);
-        HIThemeSetTextFill(themeColor, 0, nativeImage.cg, kHIThemeOrientationNormal);
-        CGContextFillRect(nativeImage.cg, cgrect);
-        QColor color = nativeImage.pixel(0,0);
-        return QColor(nativeImage.pixel(0 , 0));
-    }
-    }
-#endif
-}
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qt_mac_p.h b/src/gui/kernel/qt_mac_p.h
deleted file mode 100644 (file)
index 1725875..0000000
+++ /dev/null
@@ -1,342 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QT_MAC_P_H
-#define QT_MAC_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 "qmacdefines_mac.h"
-
-#ifdef __OBJC__
-#include <Cocoa/Cocoa.h>
-#ifdef QT_MAC_USE_COCOA
-#include <objc/runtime.h>
-#endif // QT_MAC_USE_COCOA
-#endif
-
-#include <CoreServices/CoreServices.h>
-
-#include "QtCore/qglobal.h"
-#include "QtCore/qvariant.h"
-#include "QtCore/qmimedata.h"
-#include "QtCore/qpointer.h"
-#include "qcore_mac_p.h"
-
-
-#include "QtGui/qpainter.h"
-
-#include <Carbon/Carbon.h>
-
-#if !defined(QT_MAC_USE_COCOA) && defined(MAC_OS_X_VERSION_10_7) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
-    // Some deprecated functions have been removed from the the 10.7 SDK, but the symbols are
-    // still exported by the 32-bit QD.framework (a subframework of ApplicationServices).
-    extern "C" {
-        // from QuickdrawAPI.h
-        // https://developer.apple.com/legacy/library/documentation/Carbon/reference/QuickDraw_Ref/QuickDraw_Ref.pdf
-        void          CopyBits(const BitMap *srcBits, const BitMap *dstBits, const Rect *srcRect, const Rect *dstRect, short mode, RgnHandle maskRgn);
-        void          CopyRgn(RgnHandle srcRgn, RgnHandle dstRgn);
-        void          DisposeRgn(RgnHandle rgn);
-        GDHandle      GetMainDevice(void);
-        const BitMap *GetPortBitMapForCopyBits(CGrafPtr port);
-        Rect         *GetRegionBounds(RgnHandle region, Rect *bounds);
-        RgnHandle     NewRgn(void);
-        OSStatus      QDRegionToRects(RgnHandle rgn, QDRegionParseDirection dir, RegionToRectsUPP proc, void *userData);
-        void          SetEmptyRgn(RgnHandle rgn);
-        void          SetRect(Rect* r, short left, short top, short right, short bottom);
-        void          SetRectRgn(RgnHandle rgn, short left, short top, short right, short bottom);
-        void          UnionRgn(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn);
-        enum {
-            kQDRegionToRectsMsgInit       = 1,
-            kQDRegionToRectsMsgParse      = 2,
-            kQDRegionToRectsMsgTerminate  = 3
-        };
-        enum {
-            kQDParseRegionFromTop         = (1 << 0),
-            kQDParseRegionFromBottom      = (1 << 1),
-            kQDParseRegionFromLeft        = (1 << 2),
-            kQDParseRegionFromRight       = (1 << 3),
-            kQDParseRegionFromTopLeft     = kQDParseRegionFromTop | kQDParseRegionFromLeft,
-            kQDParseRegionFromBottomRight = kQDParseRegionFromBottom | kQDParseRegionFromRight
-        };
-
-        // from Fonts.h
-        // https://developer.apple.com/legacy/library/documentation/Carbon/reference/Font_Manager/fm_reference.pdf
-        OSStatus         FMCreateFontIterator(const FMFilter *iFilter, void *iRefCon, OptionBits iOptions, FMFontIterator *ioIterator);
-        OSStatus         FMDisposeFontIterator(FMFontIterator *ioIterator);
-        ATSFontFamilyRef FMGetATSFontFamilyRefFromFont(FMFontFamily iFamily);
-        ATSFontFamilyRef FMGetATSFontFamilyRefFromFontFamily(FMFontFamily iFamily);
-        ATSFontRef       FMGetATSFontRefFromFont(FMFont iFont);
-        OSStatus         FMGetFontFamilyInstanceFromFont(FMFont iFont, FMFontFamily *oFontFamily, FMFontStyle *oStyle);
-        FMFontFamily     FMGetFontFamilyFromATSFontFamilyRef(ATSFontFamilyRef iFamily);
-        FMFont           FMGetFontFromATSFontRef(ATSFontRef iFont);
-        OSStatus         FMGetFontFromFontFamilyInstance(FMFontFamily iFontFamily, FMFontStyle iStyle, FMFont *oFont, FMFontStyle *oIntrinsicStyle);
-        OSStatus         FMGetNextFont(FMFontIterator *ioIterator, FMFont *oFont);
-        enum {
-            kFMUseGlobalScopeOption       = 0x00000001
-        };
-        enum {
-            commandMark                   = 17,
-            checkMark                     = 18,
-            diamondMark                   = 19,
-            appleMark                     = 20
-        };
-    }
-#endif
-
-QT_BEGIN_NAMESPACE
-class QWidget;
-class QDragMoveEvent;
-
-/* Event masks */
-// internal Qt types
-
- // Event class for our own Carbon events.
-#if defined(QT_NAMESPACE) && defined(QT_NAMESPACE_MAC_CRC)
-// Take the CRC we generated at configure time. This *may* result in a
-// collision with another value If that is the case, please change the value
-// here to something other than 'Cute'.
-const UInt32 kEventClassQt = QT_NAMESPACE_MAC_CRC;
-#else
-const UInt32 kEventClassQt = 'Cute';
-#endif
-
-enum {
-    //AE types
-    typeAEClipboardChanged = 1,
-    //types
-    typeQWidget = 1,  /* QWidget *  */
-    //params
-    kEventParamQWidget = 'qwid',   /* typeQWidget */
-    //events
-    kEventQtRequestContext = 13,
-    kEventQtRequestMenubarUpdate = 14,
-    kEventQtRequestShowSheet = 17,
-    kEventQtRequestActivate = 18,
-    kEventQtRequestWindowChange = 20
-};
-
-// Simple class to manage short-lived regions
-class QMacSmartQuickDrawRegion
-{
-    RgnHandle qdRgn;
-    Q_DISABLE_COPY(QMacSmartQuickDrawRegion)
-public:
-    explicit QMacSmartQuickDrawRegion(RgnHandle rgn) : qdRgn(rgn) {}
-    ~QMacSmartQuickDrawRegion() {
-        extern void qt_mac_dispose_rgn(RgnHandle); // qregion_mac.cpp
-        qt_mac_dispose_rgn(qdRgn);
-    }
-    operator RgnHandle() {
-        return qdRgn;
-    }
-};
-
-// Class for chaining to gether a bunch of fades. It pretty much is only used for qmenu fading.
-class QMacWindowFader
-{
-    QWidgetList m_windowsToFade;
-    float m_duration;
-    Q_DISABLE_COPY(QMacWindowFader)
-public:
-    QMacWindowFader(); // PLEASE DON'T CALL THIS.
-    static QMacWindowFader *currentFader();
-    void registerWindowToFade(QWidget *window);
-    void setFadeDuration(float durationInSecs) { m_duration = durationInSecs; }
-    float fadeDuration() const { return m_duration; }
-    void performFade();
-};
-
-class Q_GUI_EXPORT QMacCocoaAutoReleasePool
-{
-private:
-    void *pool;
-public:
-    QMacCocoaAutoReleasePool();
-    ~QMacCocoaAutoReleasePool();
-
-    inline void *handle() const { return pool; }
-};
-
-QString qt_mac_removeMnemonics(const QString &original); //implemented in qmacstyle_mac.cpp
-
-class Q_GUI_EXPORT QMacWindowChangeEvent
-{
-private:
-    static QList<QMacWindowChangeEvent*> *change_events;
-public:
-    QMacWindowChangeEvent() {
-    }
-    virtual ~QMacWindowChangeEvent() {
-    }
-    static inline void exec(bool ) {
-    }
-protected:
-    virtual void windowChanged() = 0;
-    virtual void flushWindowChanged() = 0;
-};
-
-class QMacCGContext
-{
-    CGContextRef context;
-public:
-    QMacCGContext(QPainter *p); //qpaintengine_mac.cpp
-    inline QMacCGContext() { context = 0; }
-    inline QMacCGContext(const QPaintDevice *pdev) {
-        extern CGContextRef qt_mac_cg_context(const QPaintDevice *);
-        context = qt_mac_cg_context(pdev);
-    }
-    inline QMacCGContext(CGContextRef cg, bool takeOwnership=false) {
-        context = cg;
-        if(!takeOwnership)
-            CGContextRetain(context);
-    }
-    inline QMacCGContext(const QMacCGContext &copy) : context(0) { *this = copy; }
-    inline ~QMacCGContext() {
-        if(context)
-            CGContextRelease(context);
-    }
-    inline bool isNull() const { return context; }
-    inline operator CGContextRef() { return context; }
-    inline QMacCGContext &operator=(const QMacCGContext &copy) {
-        if(context)
-            CGContextRelease(context);
-        context = copy.context;
-        CGContextRetain(context);
-        return *this;
-    }
-    inline QMacCGContext &operator=(CGContextRef cg) {
-        if(context)
-            CGContextRelease(context);
-        context = cg;
-        CGContextRetain(context); //we do not take ownership
-        return *this;
-    }
-};
-
-class QMacPasteboardMime;
-class QMimeData;
-
-class QMacPasteboard
-{
-    struct Promise {
-        Promise() : itemId(0), convertor(0) { }
-        Promise(int itemId, QMacPasteboardMime *c, QString m, QVariant d, int o=0) : itemId(itemId), offset(o), convertor(c), mime(m), data(d) { }
-        int itemId, offset;
-        QMacPasteboardMime *convertor;
-        QString mime;
-        QVariant data;
-    };
-    QList<Promise> promises;
-
-    OSPasteboardRef paste;
-    uchar mime_type;
-    mutable QPointer<QMimeData> mime;
-    mutable bool mac_mime_source;
-    static OSStatus promiseKeeper(OSPasteboardRef, PasteboardItemID, CFStringRef, void *);
-    void clear_helper();
-public:
-    QMacPasteboard(OSPasteboardRef p, uchar mime_type=0);
-    QMacPasteboard(uchar mime_type);
-    QMacPasteboard(CFStringRef name=0, uchar mime_type=0);
-    ~QMacPasteboard();
-
-    bool hasFlavor(QString flavor) const;
-    bool hasOSType(int c_flavor) const;
-
-    OSPasteboardRef pasteBoard() const;
-    QMimeData *mimeData() const;
-    void setMimeData(QMimeData *mime);
-
-    QStringList formats() const;
-    bool hasFormat(const QString &format) const;
-    QVariant retrieveData(const QString &format, QVariant::Type) const;
-
-    void clear();
-    bool sync() const;
-};
-
-extern QPaintDevice *qt_mac_safe_pdev; //qapplication_mac.cpp
-
-extern OSWindowRef qt_mac_window_for(const QWidget*); //qwidget_mac.mm
-extern OSViewRef qt_mac_nativeview_for(const QWidget *); //qwidget_mac.mm
-extern QPoint qt_mac_nativeMapFromParent(const QWidget *child, const QPoint &pt); //qwidget_mac.mm
-
-#ifdef check
-# undef check
-#endif
-
-QFont qfontForThemeFont(ThemeFontID themeID);
-
-QColor qcolorForTheme(ThemeBrush brush);
-
-QColor qcolorForThemeTextColor(ThemeTextColor themeColor);
-
-struct QMacDndAnswerRecord {
-    QRect rect;
-    Qt::KeyboardModifiers modifiers;
-    Qt::MouseButtons buttons;
-    Qt::DropAction lastAction;
-    unsigned int lastOperation;
-    void clear() {
-        rect = QRect();
-        modifiers = Qt::NoModifier;
-        buttons = Qt::NoButton;
-        lastAction = Qt::IgnoreAction;
-        lastOperation = 0;
-    }
-};
-extern QMacDndAnswerRecord qt_mac_dnd_answer_rec;
-void qt_mac_copy_answer_rect(const QDragMoveEvent &event);
-bool qt_mac_mouse_inside_answer_rect(QPoint mouse);
-
-QT_END_NAMESPACE
-
-#endif // QT_MAC_P_H
diff --git a/src/gui/kernel/qwidget_mac.mm b/src/gui/kernel/qwidget_mac.mm
deleted file mode 100644 (file)
index 3b0d1e1..0000000
+++ /dev/null
@@ -1,5446 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#include <qt_mac_p.h>
-#include <qeventdispatcher_mac_p.h>
-
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qfileinfo.h"
-#include "qimage.h"
-#include "qlayout.h"
-#include "qmenubar.h"
-#include <qbackingstore_p.h>
-#include <qwindowsurface_mac_p.h>
-#include <qpaintengine_mac_p.h>
-#include "qpainter.h"
-#include "qstyle.h"
-#include "qtimer.h"
-#include "qfocusframe.h"
-#include "qdebug.h"
-#include <qmainwindowlayout_p.h>
-#include <qthread_p.h>
-
-#include <qabstractscrollarea_p.h>
-#include <qabstractscrollarea.h>
-#include <ApplicationServices/ApplicationServices.h>
-#include <limits.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qcocoaview_mac_p.h>
-#include <qcocoawindow_mac_p.h>
-#include <qcocoawindowdelegate_mac_p.h>
-#include <qcocoapanel_mac_p.h>
-
-#include "qwidget_p.h"
-#include "qevent_p.h"
-#include "qdnd_p.h"
-#include <QtGui/qgraphicsproxywidget.h>
-#include "qmainwindow.h"
-
-QT_BEGIN_NAMESPACE
-
-// qmainwindow.cpp
-extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
-
-#define XCOORD_MAX 16383
-#define WRECT_MAX 8191
-
-#ifndef QT_MAC_USE_COCOA
-
-extern "C" {
-    extern OSStatus _HIViewScrollRectWithOptions(HIViewRef, const HIRect *, CGFloat, CGFloat,
-                                                 OptionBits) __attribute__ ((weak));
-}
-#define kHIViewScrollRectAdjustInvalid 1
-#define kHIViewScrollRectDontInvalidateRevealedArea 2
-#endif
-
-
-/*****************************************************************************
-  QWidget debug facilities
- *****************************************************************************/
-//#define DEBUG_WINDOW_RGNS
-//#define DEBUG_WINDOW_CREATE
-//#define DEBUG_WINDOW_STATE
-//#define DEBUG_WIDGET_PAINT
-
-/*****************************************************************************
-  QWidget globals
- *****************************************************************************/
-#ifndef QT_MAC_USE_COCOA
-typedef QHash<Qt::WindowFlags, WindowGroupRef> WindowGroupHash;
-Q_GLOBAL_STATIC(WindowGroupHash, qt_mac_window_groups)
-const UInt32 kWidgetCreatorQt = kEventClassQt;
-enum {
-    kWidgetPropertyQWidget = 'QWId' //QWidget *
-};
-#endif
-
-static bool qt_mac_raise_process = true;
-static OSWindowRef qt_root_win = 0;
-QWidget *mac_mouse_grabber = 0;
-QWidget *mac_keyboard_grabber = 0;
-
-#ifndef QT_MAC_USE_COCOA
-#ifdef QT_NAMESPACE
-
-// produce the string "com.trolltech.qt-namespace.widget", where "namespace" is the contents of QT_NAMESPACE.
-#define SS(x) #x
-#define S0(x) SS(x)
-#define S "com.trolltech.qt-" S0(QT_NAMESPACE) ".widget"
-
-static CFStringRef kObjectQWidget = CFSTR(S);
-
-#undef SS
-#undef S0
-#undef S
-
-#else
-static CFStringRef kObjectQWidget = CFSTR("com.trolltech.qt.widget");
-#endif // QT_NAMESPACE
-#endif // QT_MAC_USE_COCOA
-
-/*****************************************************************************
-  Externals
- *****************************************************************************/
-extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
-extern QWidget *qt_mac_modal_blocked(QWidget *); //qapplication_mac.mm
-extern void qt_event_request_activate(QWidget *); //qapplication_mac.mm
-extern bool qt_event_remove_activate(); //qapplication_mac.mm
-extern void qt_mac_event_release(QWidget *w); //qapplication_mac.mm
-extern void qt_event_request_showsheet(QWidget *); //qapplication_mac.mm
-extern void qt_event_request_window_change(QWidget *); //qapplication_mac.mm
-extern QPointer<QWidget> qt_last_mouse_receiver; //qapplication_mac.mm
-extern QPointer<QWidget> qt_last_native_mouse_receiver; //qt_cocoa_helpers_mac.mm
-extern IconRef qt_mac_create_iconref(const QPixmap &); //qpixmap_mac.cpp
-extern void qt_mac_set_cursor(const QCursor *, const QPoint &); //qcursor_mac.mm
-extern void qt_mac_update_cursor(); //qcursor_mac.mm
-extern bool qt_nograb();
-extern CGImageRef qt_mac_create_cgimage(const QPixmap &, bool); //qpixmap_mac.cpp
-extern RgnHandle qt_mac_get_rgn(); //qregion_mac.cpp
-extern QRegion qt_mac_convert_mac_region(RgnHandle rgn); //qregion_mac.cpp
-extern void qt_mac_setMouseGrabCursor(bool set, QCursor *cursor = 0); // qcursor_mac.mm
-extern QPointer<QWidget> topLevelAt_cache; // qapplication_mac.mm
-/*****************************************************************************
-  QWidget utility functions
- *****************************************************************************/
-void Q_GUI_EXPORT qt_mac_set_raise_process(bool b) { qt_mac_raise_process = b; }
-static QSize qt_mac_desktopSize()
-{
-    int w = 0, h = 0;
-    CGDisplayCount cg_count;
-    CGGetActiveDisplayList(0, 0, &cg_count);
-    QVector<CGDirectDisplayID> displays(cg_count);
-    CGGetActiveDisplayList(cg_count, displays.data(), &cg_count);
-    Q_ASSERT(cg_count == (CGDisplayCount)displays.size());
-    for(int i = 0; i < (int)cg_count; ++i) {
-        CGRect r = CGDisplayBounds(displays.at(i));
-        w = qMax<int>(w, qRound(r.origin.x + r.size.width));
-        h = qMax<int>(h, qRound(r.origin.y + r.size.height));
-    }
-    return QSize(w, h);
-}
-
-#ifdef QT_MAC_USE_COCOA
-static NSDrawer *qt_mac_drawer_for(const QWidget *widget)
-{
-    NSView *widgetView = reinterpret_cast<NSView *>(widget->window()->effectiveWinId());
-    NSArray *windows = [[NSApplication sharedApplication] windows];
-    for (NSWindow *window in windows) {
-        NSArray *drawers = [window drawers];
-        for (NSDrawer *drawer in drawers) {
-            if ([drawer contentView] == widgetView)
-                return drawer;
-        }
-    }
-    return 0;
-}
-#endif
-
-static void qt_mac_destructView(OSViewRef view)
-{
-#ifdef QT_MAC_USE_COCOA
-    NSWindow *window = [view window];
-    if ([window contentView] == view) {
-        NSView* newView = [[NSView alloc] initWithFrame:[view bounds]];
-        [window setContentView:newView];
-        [newView release];
-    } else {
-        [view removeFromSuperview];
-        [view release];
-    }
-#else
-    HIViewRemoveFromSuperview(view);
-    CFRelease(view);
-#endif
-}
-
-static void qt_mac_destructWindow(OSWindowRef window)
-{
-#ifdef QT_MAC_USE_COCOA
-    if ([window isVisible] && [window isSheet]){
-        [[NSApplication sharedApplication] endSheet:window];
-        [window orderOut:window];
-    }
-
-    [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] resignDelegateForWindow:window];
-    [window release];
-#else
-    // Remove property to clean up memory:
-    RemoveWindowProperty(window, kWidgetCreatorQt, kWidgetPropertyQWidget);
-    CFRelease(window);
-#endif
-}
-
-static void qt_mac_destructDrawer(NSDrawer *drawer)
-{
-#ifdef QT_MAC_USE_COCOA
-    [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] resignDelegateForDrawer:drawer];
-    [drawer release];
-#else
-    Q_UNUSED(drawer);
-#endif
-}
-
-bool qt_mac_can_clickThrough(const QWidget *w)
-{
-    static int qt_mac_carbon_clickthrough = -1;
-    if (qt_mac_carbon_clickthrough < 0)
-        qt_mac_carbon_clickthrough = !qgetenv("QT_MAC_NO_COCOA_CLICKTHROUGH").isEmpty();
-    bool ret = !qt_mac_carbon_clickthrough;
-    for ( ; w; w = w->parentWidget()) {
-        if (w->testAttribute(Qt::WA_MacNoClickThrough)) {
-            ret = false;
-            break;
-        }
-    }
-    return ret;
-}
-
-bool qt_mac_is_macsheet(const QWidget *w)
-{
-    if (!w)
-        return false;
-
-    Qt::WindowModality modality = w->windowModality();
-    if (modality == Qt::ApplicationModal)
-        return false;
-    return w->parentWidget() && (modality == Qt::WindowModal || w->windowType() == Qt::Sheet);
-}
-
-bool qt_mac_is_macdrawer(const QWidget *w)
-{
-    return (w && w->parentWidget() && w->windowType() == Qt::Drawer);
-}
-
-bool qt_mac_insideKeyWindow(const QWidget *w)
-{
-#ifdef QT_MAC_USE_COCOA
-    return [[reinterpret_cast<NSView *>(w->effectiveWinId()) window] isKeyWindow];
-#else
-    Q_UNUSED(w);
-#endif
-    return false;
-}
-
-bool qt_mac_set_drawer_preferred_edge(QWidget *w, Qt::DockWidgetArea where) //users of Qt for Mac OS X can use this..
-{
-    if(!qt_mac_is_macdrawer(w))
-        return false;
-
-#ifdef QT_MAC_USE_COCOA
-    NSDrawer *drawer = qt_mac_drawer_for(w);
-    if (!drawer)
-        return false;
-       NSRectEdge      edge;
-    if (where & Qt::LeftDockWidgetArea)
-        edge = NSMinXEdge;
-    else if (where & Qt::RightDockWidgetArea)
-        edge = NSMaxXEdge;
-    else if (where & Qt::TopDockWidgetArea)
-               edge = NSMaxYEdge;
-    else if (where & Qt::BottomDockWidgetArea)
-        edge = NSMinYEdge;
-    else
-        return false;
-
-    if (edge == [drawer preferredEdge]) //no-op
-        return false;
-
-    if (w->isVisible()) {
-           [drawer close];
-           [drawer openOnEdge:edge];
-       }
-       [drawer setPreferredEdge:edge];
-#else
-    OSWindowRef window = qt_mac_window_for(w);
-    OptionBits edge;
-    if(where & Qt::LeftDockWidgetArea)
-        edge = kWindowEdgeLeft;
-    else if(where & Qt::RightDockWidgetArea)
-        edge = kWindowEdgeRight;
-    else if(where & Qt::TopDockWidgetArea)
-        edge = kWindowEdgeTop;
-    else if(where & Qt::BottomDockWidgetArea)
-        edge = kWindowEdgeBottom;
-    else
-        return false;
-
-    if(edge == GetDrawerPreferredEdge(window)) //no-op
-        return false;
-
-    //do it
-    SetDrawerPreferredEdge(window, edge);
-    if(w->isVisible()) {
-        CloseDrawer(window, false);
-        OpenDrawer(window, edge, true);
-    }
-#endif
-    return true;
-}
-
-#ifndef QT_MAC_USE_COCOA
-Q_GUI_EXPORT
-#endif
-QPoint qt_mac_posInWindow(const QWidget *w)
-{
-    QPoint ret = w->data->wrect.topLeft();
-    while(w && !w->isWindow()) {
-        ret += w->pos();
-        w =  w->parentWidget();
-    }
-    return ret;
-}
-
-//find a QWidget from a OSWindowRef
-QWidget *qt_mac_find_window(OSWindowRef window)
-{
-#ifdef QT_MAC_USE_COCOA
-    return [window QT_MANGLE_NAMESPACE(qt_qwidget)];
-#else
-    if(!window)
-        return 0;
-
-    QWidget *ret;
-    if(GetWindowProperty(window, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(ret), 0, &ret) == noErr)
-        return ret;
-    return 0;
-#endif
-}
-
-inline static void qt_mac_set_fullscreen_mode(bool b)
-{
-    extern bool qt_mac_app_fullscreen; //qapplication_mac.mm
-    if(qt_mac_app_fullscreen == b)
-        return;
-    qt_mac_app_fullscreen = b;
-    if (b) {
-        SetSystemUIMode(kUIModeAllHidden, kUIOptionAutoShowMenuBar);
-    } else {
-        SetSystemUIMode(kUIModeNormal, 0);
-    }
-}
-
-Q_GUI_EXPORT OSViewRef qt_mac_nativeview_for(const QWidget *w)
-{
-    return reinterpret_cast<OSViewRef>(w->internalWinId());
-}
-
-Q_GUI_EXPORT OSViewRef qt_mac_effectiveview_for(const QWidget *w)
-{
-    // Get the first non-alien (parent) widget for
-    // w, and return its NSView (if it has one):
-    return reinterpret_cast<OSViewRef>(w->effectiveWinId());
-}
-
-Q_GUI_EXPORT OSViewRef qt_mac_get_contentview_for(OSWindowRef w)
-{
-#ifdef QT_MAC_USE_COCOA
-    return [w contentView];
-#else
-    HIViewRef contentView = 0;
-    OSStatus err = GetRootControl(w, &contentView);  // Returns the window's content view (Apple QA1214)
-    if (err == errUnknownControl) {
-        contentView = HIViewGetRoot(w);
-    } else if (err != noErr) {
-        qWarning("Qt:Could not get content or root view of window! %s:%d [%ld]",
-                 __FILE__, __LINE__, err);
-    }
-    return contentView;
-#endif
-}
-
-bool qt_mac_sendMacEventToWidget(QWidget *widget, EventRef ref)
-{
-    return widget->macEvent(0, ref);
-}
-
-Q_GUI_EXPORT OSWindowRef qt_mac_window_for(OSViewRef view)
-{
-#ifdef QT_MAC_USE_COCOA
-    if (view)
-        return [view window];
-    return 0;
-#else
-    return HIViewGetWindow(view);
-#endif
-}
-
-static bool qt_isGenuineQWidget(OSViewRef ref)
-{
-#ifdef QT_MAC_USE_COCOA
-    return [ref isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]];
-#else
-    return HIObjectIsOfClass(HIObjectRef(ref), kObjectQWidget);
-#endif
-}
-
-bool qt_isGenuineQWidget(const QWidget *window)
-{
-    if (!window)
-        return false;
-
-    if (!window->internalWinId())
-        return true;  //alien
-
-    return qt_isGenuineQWidget(OSViewRef(window->internalWinId()));
-}
-
-Q_GUI_EXPORT OSWindowRef qt_mac_window_for(const QWidget *w)
-{
-    if (OSViewRef hiview = qt_mac_effectiveview_for(w)) {
-        OSWindowRef window = qt_mac_window_for(hiview);
-        if (window)
-            return window;
-
-        if (qt_isGenuineQWidget(hiview)) {
-            // This is a workaround for NSToolbar. When a widget is hidden
-            // by clicking the toolbar button, Cocoa reparents the widgets
-            // to another window (but Qt doesn't know about it).
-            // When we start showing them, it reparents back,
-            // but at this point it's window is nil, but the window it's being brought
-            // into (the Qt one) is for sure created.
-            // This stops the hierarchy moving under our feet.
-            QWidget *toplevel = w->window();
-            if (toplevel != w) {
-                hiview = qt_mac_nativeview_for(toplevel);
-                if (OSWindowRef w = qt_mac_window_for(hiview))
-                    return w;
-            }
-
-            toplevel->d_func()->createWindow_sys();
-            // Reget the hiview since "create window" could potentially move the view (I guess).
-            hiview = qt_mac_nativeview_for(toplevel);
-            return qt_mac_window_for(hiview);
-        }
-    }
-    return 0;
-}
-
-#ifndef QT_MAC_USE_COCOA
-/*  Checks if the current group is a 'stay on top' group. If so, the
-    group gets removed from the hash table */
-static void qt_mac_release_stays_on_top_group(WindowGroupRef group)
-{
-    for (WindowGroupHash::iterator it = qt_mac_window_groups()->begin(); it != qt_mac_window_groups()->end(); ++it) {
-        if (it.value() == group) {
-            qt_mac_window_groups()->remove(it.key());
-            return;
-        }
-    }
-}
-
-/* Use this function instead of ReleaseWindowGroup, this will be sure to release the
-   stays on top window group (created with qt_mac_get_stays_on_top_group below) */
-static void qt_mac_release_window_group(WindowGroupRef group)
-{
-    ReleaseWindowGroup(group);
-    if (GetWindowGroupRetainCount(group) == 0)
-        qt_mac_release_stays_on_top_group(group);
-}
-#define ReleaseWindowGroup(x) Are you sure you wanted to do that? (you wanted qt_mac_release_window_group)
-
-SInt32 qt_mac_get_group_level(WindowClass wclass)
-{
-    SInt32 group_level;
-    CGWindowLevel tmpLevel;
-    GetWindowGroupLevelOfType(GetWindowGroupOfClass(wclass), kWindowGroupLevelActive, &tmpLevel);
-    group_level = tmpLevel;
-    return group_level;
-}
-#endif
-
-#ifndef QT_MAC_USE_COCOA
-static void qt_mac_set_window_group(OSWindowRef window, Qt::WindowFlags flags, int level)
-{
-    WindowGroupRef group = 0;
-    if (qt_mac_window_groups()->contains(flags)) {
-        group = qt_mac_window_groups()->value(flags);
-        RetainWindowGroup(group);
-    } else {
-        CreateWindowGroup(kWindowActivationScopeNone, &group);
-        SetWindowGroupLevel(group, level);
-        SetWindowGroupParent(group, GetWindowGroupOfClass(kAllWindowClasses));
-        qt_mac_window_groups()->insert(flags, group);
-    }
-    SetWindowGroup(window, group);
-}
-
-inline static void qt_mac_set_window_group_to_stays_on_top(OSWindowRef window, Qt::WindowType type)
-{
-    // We create one static stays on top window group so that
-    // all stays on top (aka popups) will fall into the same
-    // group and be able to be raise()'d with releation to one another (from
-    // within the same window group).
-    qt_mac_set_window_group(window, type|Qt::WindowStaysOnTopHint, qt_mac_get_group_level(kOverlayWindowClass));
-}
-
-inline static void qt_mac_set_window_group_to_tooltip(OSWindowRef window)
-{
-    // Since new groups are created for 'stays on top' windows, the
-    // same must be done for tooltips. Otherwise, tooltips would be drawn
-    // below 'stays on top' widgets even tough they are on the same level.
-    // Also, add 'two' to the group level to make sure they also get on top of popups.
-    qt_mac_set_window_group(window, Qt::ToolTip, qt_mac_get_group_level(kHelpWindowClass)+2);
-}
-
-inline static void qt_mac_set_window_group_to_popup(OSWindowRef window)
-{
-    // In Qt, a popup is seen as a 'stay on top' window.
-    // Since new groups are created for 'stays on top' windows, the
-    // same must be done for popups. Otherwise, popups would be drawn
-    // below 'stays on top' windows. Add 1 to get above pure stay-on-top windows.
-    qt_mac_set_window_group(window, Qt::Popup, qt_mac_get_group_level(kOverlayWindowClass)+1);
-}
-#endif
-
-inline static bool updateRedirectedToGraphicsProxyWidget(QWidget *widget, const QRect &rect)
-{
-    if (!widget)
-        return false;
-
-#ifndef QT_NO_GRAPHICSVIEW
-    QWidget *tlw = widget->window();
-    QWExtra *extra = qt_widget_private(tlw)->extra;
-    if (extra && extra->proxyWidget) {
-        extra->proxyWidget->update(rect.translated(widget->mapTo(tlw, QPoint())));
-        return true;
-    }
-#endif
-
-    return false;
-}
-
-inline static bool updateRedirectedToGraphicsProxyWidget(QWidget *widget, const QRegion &rgn)
-{
-    if (!widget)
-        return false;
-
-#ifndef QT_NO_GRAPHICSVIEW
-    QWidget *tlw = widget->window();
-    QWExtra *extra = qt_widget_private(tlw)->extra;
-    if (extra && extra->proxyWidget) {
-        const QPoint offset(widget->mapTo(tlw, QPoint()));
-        const QVector<QRect> rects = rgn.rects();
-        for (int i = 0; i < rects.size(); ++i)
-            extra->proxyWidget->update(rects.at(i).translated(offset));
-        return true;
-    }
-#endif
-
-    return false;
-}
-
-void QWidgetPrivate::macSetNeedsDisplay(QRegion region)
-{
-    Q_Q(QWidget);
-#ifndef QT_MAC_USE_COCOA
-    if (region.isEmpty())
-        HIViewSetNeedsDisplay(qt_mac_nativeview_for(q), true);
-    else if (RgnHandle rgnHandle = region.toQDRgnForUpdate_sys())
-        HIViewSetNeedsDisplayInRegion(qt_mac_nativeview_for(q), QMacSmartQuickDrawRegion(rgnHandle), true);
-    else
-        HIViewSetNeedsDisplay(qt_mac_nativeview_for(q), true); // do a complete repaint on overflow.
-#else
-    if (NSView *nativeView = qt_mac_nativeview_for(q)) {
-        // INVARIANT: q is _not_ alien. So we can optimize a little:
-        if (region.isEmpty()) {
-            [nativeView setNeedsDisplay:YES];
-        } else {
-            QVector<QRect> rects = region.rects();
-            for (int i = 0; i<rects.count(); ++i) {
-                const QRect &rect = rects.at(i);
-                NSRect nsrect = NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height());
-                [nativeView setNeedsDisplayInRect:nsrect];
-            }
-        }
-    } else if (QWidget *effectiveWidget = q->nativeParentWidget()) {
-        // INVARIANT: q is alien, and effectiveWidget is native.
-        if (NSView *effectiveView = qt_mac_nativeview_for(effectiveWidget)) {
-            if (region.isEmpty()) {
-                const QRect &rect = q->rect();
-                QPoint p = q->mapTo(effectiveWidget, rect.topLeft());
-                NSRect nsrect = NSMakeRect(p.x(), p.y(), rect.width(), rect.height());
-                [effectiveView setNeedsDisplayInRect:nsrect];
-            } else {
-                QVector<QRect> rects = region.rects();
-                for (int i = 0; i<rects.count(); ++i) {
-                    const QRect &rect = rects.at(i);
-                    QPoint p = q->mapTo(effectiveWidget, rect.topLeft());
-                    NSRect nsrect = NSMakeRect(p.x(), p.y(), rect.width(), rect.height());
-                    [effectiveView setNeedsDisplayInRect:nsrect];
-                }
-            }
-        }
-    }
-#endif
-}
-
-void QWidgetPrivate::macUpdateIsOpaque()
-{
-    Q_Q(QWidget);
-    if (!q->testAttribute(Qt::WA_WState_Created))
-        return;
-#ifndef QT_MAC_USE_COCOA
-    HIViewFeatures bits;
-    HIViewRef hiview = qt_mac_nativeview_for(q);
-    HIViewGetFeatures(hiview, &bits);
-    if ((bits & kHIViewIsOpaque) == isOpaque)
-        return;
-    if (isOpaque) {
-        HIViewChangeFeatures(hiview, kHIViewIsOpaque, 0);
-    } else {
-        HIViewChangeFeatures(hiview, 0, kHIViewIsOpaque);
-    }
-    if (q->isVisible())
-        HIViewReshapeStructure(qt_mac_nativeview_for(q));
-#else
-    if (isRealWindow() && !q->testAttribute(Qt::WA_MacBrushedMetal)) {
-        bool opaque = isOpaque;
-        if (extra && extra->imageMask)
-            opaque = false; // we are never opaque when we have a mask.
-        [qt_mac_window_for(q) setOpaque:opaque];
-    }
-#endif
-}
-#ifdef QT_MAC_USE_COCOA
-static OSWindowRef qt_mac_create_window(QWidget *widget, WindowClass wclass,
-                                        NSUInteger wattr, const QRect &crect)
-{
-    // Determine if we need to add in our "custom window" attribute. Cocoa is rather clever
-    // in deciding if we need the maximize button or not (i.e., it's resizeable, so you
-    // must need a maximize button). So, the only buttons we have control over are the
-    // close and minimize buttons. If someone wants to customize and NOT have the maximize
-    // button, then we have to do our hack. We only do it for these cases because otherwise
-    // the window looks different when activated. This "QtMacCustomizeWindow" attribute is
-    // intruding on a public space and WILL BREAK in the future.
-    // One can hope that there is a more public API available by that time.
-    Qt::WindowFlags flags = widget ? widget->windowFlags() : Qt::WindowFlags(0);
-    if ((flags & Qt::CustomizeWindowHint)) {
-        if ((flags & (Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint
-                      | Qt::WindowMinimizeButtonHint | Qt::WindowTitleHint))
-            && !(flags & Qt::WindowMaximizeButtonHint))
-            wattr |= QtMacCustomizeWindow;
-    }
-
-    // If we haven't created the desktop widget, you have to pass the rectangle
-    // in "cocoa coordinates" (i.e., top points to the lower left coordinate).
-    // Otherwise, we do the conversion for you. Since we are the only ones that
-    // create the desktop widget, this is OK (but confusing).
-    NSRect geo = NSMakeRect(crect.left(),
-                            (qt_root_win != 0) ? flipYCoordinate(crect.bottom() + 1) : crect.top(),
-                            crect.width(), crect.height());
-    QMacCocoaAutoReleasePool pool;
-    OSWindowRef window;
-    switch (wclass) {
-    case kMovableModalWindowClass:
-    case kModalWindowClass:
-    case kSheetWindowClass:
-    case kFloatingWindowClass:
-    case kOverlayWindowClass:
-    case kHelpWindowClass: {
-        NSPanel *panel;
-        BOOL needFloating = NO;
-        BOOL worksWhenModal = widget && (widget->windowType() == Qt::Popup);
-        // Add in the extra flags if necessary.
-        switch (wclass) {
-        case kSheetWindowClass:
-            wattr |= NSDocModalWindowMask;
-            break;
-        case kFloatingWindowClass:
-        case kHelpWindowClass:
-            needFloating = YES;
-            wattr |= NSUtilityWindowMask;
-            break;
-        default:
-            break;
-        }
-        panel = [[QT_MANGLE_NAMESPACE(QCocoaPanel) alloc] QT_MANGLE_NAMESPACE(qt_initWithQWidget):widget contentRect:geo styleMask:wattr];
-        [panel setFloatingPanel:needFloating];
-        [panel setWorksWhenModal:worksWhenModal];
-        window = panel;
-        break;
-    }
-    case kDrawerWindowClass: {
-        NSDrawer *drawer = [[NSDrawer alloc] initWithContentSize:geo.size preferredEdge:NSMinXEdge];
-        [[QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate] becomeDelegateForDrawer:drawer widget:widget];
-        QWidget *parentWidget = widget->parentWidget();
-        if (parentWidget)
-            [drawer setParentWindow:qt_mac_window_for(parentWidget)];
-        [drawer setLeadingOffset:0.0];
-        [drawer setTrailingOffset:25.0];
-        window = [[drawer contentView] window];  // Just to make sure we actually return a window
-        break;
-    }
-    default:
-        window = [[QT_MANGLE_NAMESPACE(QCocoaWindow) alloc] QT_MANGLE_NAMESPACE(qt_initWithQWidget):widget contentRect:geo styleMask:wattr];
-        break;
-    }
-    qt_syncCocoaTitleBarButtons(window, widget);
-    return window;
-}
-#else
-static OSWindowRef qt_mac_create_window(QWidget *, WindowClass wclass, WindowAttributes wattr,
-                                        const QRect &crect)
-{
-    OSWindowRef window;
-    Rect geo;
-    SetRect(&geo, crect.left(), crect.top(), crect.right() + 1, crect.bottom() + 1);
-    OSStatus err;
-    if(geo.right <= geo.left)          geo.right = geo.left + 1;
-    if(geo.bottom <= geo.top)          geo.bottom = geo.top + 1;
-    Rect null_rect;
-       SetRect(&null_rect, 0, 0, 1, 1);
-    err = CreateNewWindow(wclass, wattr, &null_rect, &window);
-    if(err == noErr) {
-        err = SetWindowBounds(window, kWindowContentRgn, &geo);
-        if(err != noErr)
-            qWarning("QWidget: Internal error (%s:%d)", __FILE__, __LINE__);
-    }
-    return window;
-}
-
-#ifndef QT_NO_GESTURES
-#if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
-/* We build the release package against the 10.4 SDK.
-   So, to enable gestures for applications running on
-   10.6+, we define the missing constants here: */
-enum {
-    kEventClassGesture              = 'gest',
-    kEventGestureStarted            = 1,
-    kEventGestureEnded              = 2,
-    kEventGestureMagnify            = 4,
-    kEventGestureSwipe              = 5,
-    kEventGestureRotate             = 6,
-    kEventParamRotationAmount       = 'rota',
-    kEventParamSwipeDirection       = 'swip',
-    kEventParamMagnificationAmount  = 'magn'
-};
-#endif
-#endif // QT_NO_GESTURES
-
-// window events
-static EventTypeSpec window_events[] = {
-    { kEventClassWindow, kEventWindowClose },
-    { kEventClassWindow, kEventWindowExpanded },
-    { kEventClassWindow, kEventWindowHidden },
-    { kEventClassWindow, kEventWindowZoom },
-    { kEventClassWindow, kEventWindowZoomed },
-    { kEventClassWindow, kEventWindowCollapsed },
-    { kEventClassWindow, kEventWindowToolbarSwitchMode },
-    { kEventClassWindow, kEventWindowProxyBeginDrag },
-    { kEventClassWindow, kEventWindowProxyEndDrag },
-    { kEventClassWindow, kEventWindowResizeCompleted },
-    { kEventClassWindow, kEventWindowBoundsChanging },
-    { kEventClassWindow, kEventWindowGetRegion },
-    { kEventClassWindow, kEventWindowGetClickModality },
-    { kEventClassWindow, kEventWindowTransitionCompleted },
-    { kEventClassGesture, kEventGestureStarted },
-    { kEventClassGesture, kEventGestureEnded },
-    { kEventClassGesture, kEventGestureMagnify },
-    { kEventClassGesture, kEventGestureSwipe },
-    { kEventClassGesture, kEventGestureRotate },
-    { kEventClassMouse, kEventMouseDown }
-};
-static EventHandlerUPP mac_win_eventUPP = 0;
-static void cleanup_win_eventUPP()
-{
-    DisposeEventHandlerUPP(mac_win_eventUPP);
-    mac_win_eventUPP = 0;
-}
-static const EventHandlerUPP make_win_eventUPP()
-{
-    if(mac_win_eventUPP)
-        return mac_win_eventUPP;
-    qAddPostRoutine(cleanup_win_eventUPP);
-    return mac_win_eventUPP = NewEventHandlerUPP(QWidgetPrivate::qt_window_event);
-}
-OSStatus QWidgetPrivate::qt_window_event(EventHandlerCallRef er, EventRef event, void *)
-{
-    QScopedLoopLevelCounter loopLevelCounter(qApp->d_func()->threadData);
-    bool handled_event = true;
-    UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
-    switch(eclass) {
-    case kEventClassWindow: {
-        WindowRef wid = 0;
-        GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
-                          sizeof(WindowRef), 0, &wid);
-        QWidget *widget = qt_mac_find_window(wid);
-        if(!widget) {
-            handled_event = false;
-        } else if(ekind == kEventWindowGetClickModality) {
-            // Carbon will send us kEventWindowGetClickModality before every
-            // mouse press / release event. By returning 'true', we tell Carbon
-            // that we would like the event target to receive the mouse event even
-            // if the target is modally shaddowed. In Qt, this makes sense when we
-            // e.g. have a popup showing, as the popup will grab the event
-            // and perhaps use it to close itself.
-            // By also setting the current modal window back into the event, we
-            // help Carbon determining which window is supposed to be raised.
-            handled_event = qApp->activePopupWidget() ? true : false;
-        } else if(ekind == kEventWindowClose) {
-            widget->d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
-            QMenuBar::macUpdateMenuBar();
-        } else if (ekind == kEventWindowTransitionCompleted) {
-            WindowTransitionAction transitionAction;
-            GetEventParameter(event, kEventParamWindowTransitionAction, typeWindowTransitionAction,
-                              0, sizeof(transitionAction), 0, &transitionAction);
-            if (transitionAction == kWindowHideTransitionAction)
-                widget->hide();
-        } else if(ekind == kEventWindowExpanded) {
-            Qt::WindowStates currState = widget->data->window_state;
-            Qt::WindowStates newState = currState;
-            if (currState & Qt::WindowMinimized)
-                newState &= ~Qt::WindowMinimized;
-            if (!(currState & Qt::WindowActive))
-                newState |= Qt::WindowActive;
-            if (newState != currState) {
-                // newState will differ from currState if the window
-                // was expanded after clicking on the jewels (as opposed
-                // to calling QWidget::setWindowState)
-                widget->data->window_state = newState;
-                QWindowStateChangeEvent e(currState);
-                QApplication::sendSpontaneousEvent(widget, &e);
-            }
-
-            QShowEvent qse;
-            QApplication::sendSpontaneousEvent(widget, &qse);
-        } else if(ekind == kEventWindowZoom) {
-            widget->d_func()->topData()->normalGeometry = widget->geometry();
-            handled_event = false;
-        } else if(ekind == kEventWindowZoomed) {
-            WindowPartCode windowPart;
-            GetEventParameter(event, kEventParamWindowPartCode,
-                              typeWindowPartCode, 0, sizeof(windowPart), 0, &windowPart);
-            if(windowPart == inZoomIn && widget->isMaximized()) {
-
-                widget->data->window_state = widget->data->window_state & ~Qt::WindowMaximized;
-                QWindowStateChangeEvent e(widget->data->window_state | Qt::WindowMaximized);
-                QApplication::sendSpontaneousEvent(widget, &e);
-            } else if(windowPart == inZoomOut && !widget->isMaximized()) {
-                widget->data->window_state = widget->data->window_state | Qt::WindowMaximized;
-                QWindowStateChangeEvent e(widget->data->window_state & ~Qt::WindowMaximized);
-                QApplication::sendSpontaneousEvent(widget, &e);
-            }
-            qt_button_down = 0;
-        } else if(ekind == kEventWindowCollapsed) {
-            if (!widget->isMinimized()) {
-                widget->data->window_state = widget->data->window_state | Qt::WindowMinimized;
-                QWindowStateChangeEvent e(widget->data->window_state & ~Qt::WindowMinimized);
-                QApplication::sendSpontaneousEvent(widget, &e);
-            }
-
-            // Deactivate this window:
-            if (widget->isActiveWindow() && !(widget->windowType() == Qt::Popup)) {
-                QWidget *w = 0;
-                if (widget->parentWidget())
-                    w = widget->parentWidget()->window();
-                if (!w || (!w->isVisible() && !w->isMinimized())) {
-                    for (WindowPtr wp = GetFrontWindowOfClass(kDocumentWindowClass, true);
-                        wp; wp = GetNextWindowOfClass(wp, kDocumentWindowClass, true)) {
-                        if ((w = qt_mac_find_window(wp)))
-                            break;
-                    }
-                }
-                if(!(w && w->isVisible() && !w->isMinimized()))
-                    qApp->setActiveWindow(0);
-            }
-
-            //we send a hide to be like X11/Windows
-            QEvent e(QEvent::Hide);
-            QApplication::sendSpontaneousEvent(widget, &e);
-            qt_button_down = 0;
-        } else if(ekind == kEventWindowToolbarSwitchMode) {
-            macSendToolbarChangeEvent(widget);
-            HIToolbarRef toolbar;
-            if (GetWindowToolbar(wid, &toolbar) == noErr) {
-                if (toolbar) {
-                    // Let HIToolbar do its thang, but things like the OpenGL context
-                    // needs to know about it.
-                    CallNextEventHandler(er, event);
-                    qt_event_request_window_change(widget);
-                    widget->data->fstrut_dirty = true;
-                }
-            }
-        } else if(ekind == kEventWindowGetRegion) {
-            WindowRef window;
-            GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0,
-                              sizeof(window), 0, &window);
-            WindowRegionCode wcode;
-            GetEventParameter(event, kEventParamWindowRegionCode, typeWindowRegionCode, 0,
-                              sizeof(wcode), 0, &wcode);
-            if (wcode != kWindowOpaqueRgn){
-                // If the region is kWindowOpaqueRgn, don't call next
-                // event handler cause this will make the shadow of
-                // masked windows become offset. Unfortunately, we're not sure why.
-                CallNextEventHandler(er, event);
-            }
-                       RgnHandle rgn;
-            GetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, 0,
-                              sizeof(rgn), 0, &rgn);
-
-            if(QWidgetPrivate::qt_widget_rgn(qt_mac_find_window(window), wcode, rgn, false))
-                SetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, sizeof(rgn), &rgn);
-        } else if(ekind == kEventWindowProxyBeginDrag) {
-            QIconDragEvent e;
-            QApplication::sendSpontaneousEvent(widget, &e);
-        } else if(ekind == kEventWindowResizeCompleted) {
-            // Create a mouse up event, since such an event is not send by carbon to the
-            // application event handler (while a mouse down <b>is</b> on kEventWindowResizeStarted)
-            EventRef mouseUpEvent;
-            CreateEvent(0, kEventClassMouse, kEventMouseUp, 0, kEventAttributeUserEvent, &mouseUpEvent);
-            UInt16 mbutton = kEventMouseButtonPrimary;
-            SetEventParameter(mouseUpEvent, kEventParamMouseButton, typeMouseButton, sizeof(mbutton), &mbutton);
-            WindowRef window;
-            GetEventParameter(event, kEventParamDirectObject, typeWindowRef, 0, sizeof(window), 0, &window);
-            Rect dragRect;
-            GetWindowBounds(window, kWindowGrowRgn, &dragRect);
-            Point pos = {dragRect.bottom, dragRect.right};
-            SetEventParameter(mouseUpEvent, kEventParamMouseLocation, typeQDPoint, sizeof(pos), &pos);
-            SendEventToApplication(mouseUpEvent);
-            ReleaseEvent(mouseUpEvent);
-        } else if(ekind == kEventWindowBoundsChanging) {
-            UInt32 flags = 0;
-            GetEventParameter(event, kEventParamAttributes, typeUInt32, 0,
-                                  sizeof(flags), 0, &flags);
-            Rect nr;
-            GetEventParameter(event, kEventParamCurrentBounds, typeQDRectangle, 0,
-                                  sizeof(nr), 0, &nr);
-
-            QRect newRect(nr.left, nr.top, nr.right - nr.left, nr.bottom - nr.top);
-
-            QTLWExtra * const tlwExtra = widget->d_func()->maybeTopData();
-            if (tlwExtra && tlwExtra->isSetGeometry == 1) {
-                widget->d_func()->setGeometry_sys_helper(newRect.left(), newRect.top(), newRect.width(), newRect.height(), tlwExtra->isMove);
-            } else {
-                //implicitly removes the maximized bit
-                if((widget->data->window_state & Qt::WindowMaximized) &&
-                   IsWindowInStandardState(wid, 0, 0)) {
-                    widget->data->window_state &= ~Qt::WindowMaximized;
-                    QWindowStateChangeEvent e(widget->data->window_state | Qt::WindowMaximized);
-                    QApplication::sendSpontaneousEvent(widget, &e);
-
-                }
-
-                handled_event = false;
-                const QRect oldRect = widget->data->crect;
-                if((flags & kWindowBoundsChangeOriginChanged)) {
-                    if(nr.left != oldRect.x() || nr.top != oldRect.y()) {
-                        widget->data->crect.moveTo(nr.left, nr.top);
-                        QMoveEvent qme(widget->data->crect.topLeft(), oldRect.topLeft());
-                        QApplication::sendSpontaneousEvent(widget, &qme);
-                    }
-                }
-                if((flags & kWindowBoundsChangeSizeChanged)) {
-                    if (widget->isWindow()) {
-                        QSize newSize = QLayout::closestAcceptableSize(widget, newRect.size());
-                        int dh = newSize.height() - newRect.height();
-                        int dw = newSize.width() - newRect.width();
-                        if (dw != 0 || dh != 0) {
-                            handled_event = true;  // We want to change the bounds, so we handle the event
-
-                            // set the rect, so we can also do the resize down below (yes, we need to resize).
-                            newRect.setBottom(newRect.bottom() + dh);
-                            newRect.setRight(newRect.right() + dw);
-
-                            nr.left = newRect.x();
-                            nr.top = newRect.y();
-                            nr.right = nr.left + newRect.width();
-                            nr.bottom = nr.top + newRect.height();
-                            SetEventParameter(event, kEventParamCurrentBounds, typeQDRectangle, sizeof(Rect), &nr);
-                        }
-                    }
-
-                    if (oldRect.width() != newRect.width() || oldRect.height() != newRect.height()) {
-                        widget->data->crect.setSize(newRect.size());
-                        HIRect bounds = CGRectMake(0, 0, newRect.width(), newRect.height());
-
-                        // If the WA_StaticContents attribute is set we can optimize the resize
-                        // by only repainting the newly exposed area. We do this by disabling
-                        // painting when setting the size of the view. The OS will invalidate
-                        // the newly exposed area for us.
-                        const bool staticContents = widget->testAttribute(Qt::WA_StaticContents);
-                        const HIViewRef view = qt_mac_nativeview_for(widget);
-                        if (staticContents)
-                            HIViewSetDrawingEnabled(view, false);
-                        HIViewSetFrame(view, &bounds);
-                        if (staticContents)
-                            HIViewSetDrawingEnabled(view, true);
-
-                        QResizeEvent qre(newRect.size(), oldRect.size());
-                        QApplication::sendSpontaneousEvent(widget, &qre);
-                        qt_event_request_window_change(widget);
-                    }
-                }
-            }
-        } else if (ekind == kEventWindowHidden) {
-            // Make sure that we also hide any visible sheets on our window.
-            // Cocoa does the right thing for us.
-            const QObjectList children = widget->children();
-            const int childCount = children.count();
-            for (int i = 0; i < childCount; ++i) {
-                QObject *obj = children.at(i);
-                if (obj->isWidgetType()) {
-                    QWidget *widget = static_cast<QWidget *>(obj);
-                    if (qt_mac_is_macsheet(widget) && widget->isVisible())
-                        widget->hide();
-                }
-            }
-        } else {
-            handled_event = false;
-        }
-        break; }
-    case kEventClassMouse: {
-#if 0
-        return SendEventToApplication(event);
-#endif
-
-        bool send_to_app = false;
-        {
-            WindowPartCode wpc;
-            if (GetEventParameter(event, kEventParamWindowPartCode, typeWindowPartCode, 0,
-                                  sizeof(wpc), 0, &wpc) == noErr && wpc != inContent)
-                send_to_app = true;
-        }
-        if(!send_to_app) {
-            WindowRef window;
-            if(GetEventParameter(event, kEventParamWindowRef, typeWindowRef, 0,
-                                 sizeof(window), 0, &window) == noErr) {
-                HIViewRef hiview;
-                if(HIViewGetViewForMouseEvent(HIViewGetRoot(window), event, &hiview) == noErr) {
-                    if(QWidget *w = QWidget::find((WId)hiview)) {
-#if 0
-                        send_to_app = !w->isActiveWindow();
-#else
-                        Q_UNUSED(w);
-                        send_to_app = true;
-#endif
-                    }
-                }
-            }
-        }
-        if(send_to_app)
-            return SendEventToApplication(event);
-        handled_event = false;
-        break; }
-
-#ifndef QT_NO_GESTURES
-    case kEventClassGesture: {
-        // First, find the widget that was under
-        // the mouse when the gesture happened:
-        HIPoint screenLocation;
-        if (GetEventParameter(event, kEventParamMouseLocation, typeHIPoint, 0,
-                    sizeof(screenLocation), 0, &screenLocation) != noErr) {
-            handled_event = false;
-            break;
-        }
-        QWidget *widget = QApplication::widgetAt(screenLocation.x, screenLocation.y);
-        if (!widget) {
-            handled_event = false;
-            break;
-        }
-
-        QNativeGestureEvent qNGEvent;
-        qNGEvent.position = QPoint(screenLocation.x, screenLocation.y);
-
-        switch (ekind) {
-            case kEventGestureStarted:
-                qNGEvent.gestureType = QNativeGestureEvent::GestureBegin;
-                break;
-            case kEventGestureEnded:
-                qNGEvent.gestureType = QNativeGestureEvent::GestureEnd;
-                break;
-            case kEventGestureRotate: {
-                CGFloat amount;
-                if (GetEventParameter(event, kEventParamRotationAmount, 'cgfl', 0,
-                            sizeof(amount), 0, &amount) != noErr) {
-                    handled_event = false;
-                    break;
-                }
-                qNGEvent.gestureType = QNativeGestureEvent::Rotate;
-                qNGEvent.percentage = float(-amount);
-                break; }
-            case kEventGestureSwipe: {
-                HIPoint swipeDirection;
-                if (GetEventParameter(event, kEventParamSwipeDirection, typeHIPoint, 0,
-                            sizeof(swipeDirection), 0, &swipeDirection) != noErr) {
-                    handled_event = false;
-                    break;
-                }
-                qNGEvent.gestureType = QNativeGestureEvent::Swipe;
-                if (swipeDirection.x == 1)
-                    qNGEvent.angle = 180.0f;
-                else if (swipeDirection.x == -1)
-                    qNGEvent.angle = 0.0f;
-                else if (swipeDirection.y == 1)
-                    qNGEvent.angle = 90.0f;
-                else if (swipeDirection.y == -1)
-                    qNGEvent.angle = 270.0f;
-                break; }
-            case kEventGestureMagnify: {
-                CGFloat amount;
-                if (GetEventParameter(event, kEventParamMagnificationAmount, 'cgfl', 0,
-                            sizeof(amount), 0, &amount) != noErr) {
-                    handled_event = false;
-                    break;
-                }
-                qNGEvent.gestureType = QNativeGestureEvent::Zoom;
-                qNGEvent.percentage = float(amount);
-                break; }
-        }
-
-        QApplication::sendSpontaneousEvent(widget, &qNGEvent);
-    break; }
-#endif // QT_NO_GESTURES
-
-    default:
-        handled_event = false;
-    }
-    if(!handled_event) //let the event go through
-        return eventNotHandledErr;
-    return noErr; //we eat the event
-}
-
-// widget events
-static HIObjectClassRef widget_class = 0;
-static EventTypeSpec widget_events[] = {
-    { kEventClassHIObject, kEventHIObjectConstruct },
-    { kEventClassHIObject, kEventHIObjectDestruct },
-
-    { kEventClassControl, kEventControlDraw },
-    { kEventClassControl, kEventControlInitialize },
-    { kEventClassControl, kEventControlGetPartRegion },
-    { kEventClassControl, kEventControlGetClickActivation },
-    { kEventClassControl, kEventControlSetFocusPart },
-    { kEventClassControl, kEventControlDragEnter },
-    { kEventClassControl, kEventControlDragWithin },
-    { kEventClassControl, kEventControlDragLeave },
-    { kEventClassControl, kEventControlDragReceive },
-    { kEventClassControl, kEventControlOwningWindowChanged },
-    { kEventClassControl, kEventControlBoundsChanged },
-    { kEventClassControl, kEventControlGetSizeConstraints },
-    { kEventClassControl, kEventControlVisibilityChanged },
-
-    { kEventClassMouse, kEventMouseDown },
-    { kEventClassMouse, kEventMouseUp },
-    { kEventClassMouse, kEventMouseMoved },
-    { kEventClassMouse, kEventMouseDragged }
-};
-static EventHandlerUPP mac_widget_eventUPP = 0;
-static void cleanup_widget_eventUPP()
-{
-    DisposeEventHandlerUPP(mac_widget_eventUPP);
-    mac_widget_eventUPP = 0;
-}
-static const EventHandlerUPP make_widget_eventUPP()
-{
-    if(mac_widget_eventUPP)
-        return mac_widget_eventUPP;
-    qAddPostRoutine(cleanup_widget_eventUPP);
-    return mac_widget_eventUPP = NewEventHandlerUPP(QWidgetPrivate::qt_widget_event);
-}
-OSStatus QWidgetPrivate::qt_widget_event(EventHandlerCallRef er, EventRef event, void *)
-{
-    QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);
-
-    bool handled_event = true;
-    UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
-    switch(eclass) {
-    case kEventClassHIObject: {
-        HIViewRef view = 0;
-        GetEventParameter(event, kEventParamHIObjectInstance, typeHIObjectRef,
-                          0, sizeof(view), 0, &view);
-        if(ekind == kEventHIObjectConstruct) {
-            if(view) {
-                HIViewChangeFeatures(view, kHIViewAllowsSubviews, 0);
-                SetEventParameter(event, kEventParamHIObjectInstance,
-                                  typeVoidPtr, sizeof(view), &view);
-            }
-        } else if(ekind == kEventHIObjectDestruct) {
-            //nothing to really do.. or is there?
-        } else {
-            handled_event = false;
-        }
-        break; }
-    case kEventClassControl: {
-        QWidget *widget = 0;
-        HIViewRef hiview = 0;
-        if(GetEventParameter(event, kEventParamDirectObject, typeControlRef,
-                             0, sizeof(hiview), 0, &hiview) == noErr)
-            widget = QWidget::find((WId)hiview);
-        if (widget && widget->macEvent(er, event))
-            return noErr;
-        if(ekind == kEventControlDraw) {
-            if(widget && qt_isGenuineQWidget(hiview)) {
-
-                // if there is a window change event pending for any gl child wigets,
-                // send it immediately. (required for flicker-free resizing)
-                extern void qt_mac_send_posted_gl_updates(QWidget *widget);
-                qt_mac_send_posted_gl_updates(widget);
-
-                if (QApplicationPrivate::graphics_system && !widget->d_func()->paintOnScreen()) {
-                    widget->d_func()->syncBackingStore();
-                    widget->d_func()->dirtyOnWidget = QRegion();
-                    return noErr;
-                }
-
-                //requested rgn
-                RgnHandle rgn;
-                GetEventParameter(event, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof(rgn), 0, &rgn);
-                QRegion qrgn(qt_mac_convert_mac_region(rgn));
-
-                //update handles
-                GrafPtr qd = 0;
-                CGContextRef cg = 0;
-                if(GetEventParameter(event, kEventParamCGContextRef, typeCGContextRef, 0, sizeof(cg), 0, &cg) != noErr) {
-                    Q_ASSERT(false);
-                }
-                widget->d_func()->hd = cg;
-                widget->d_func()->qd_hd = qd;
-                CGContextSaveGState(cg);
-
-#ifdef DEBUG_WIDGET_PAINT
-                const bool doDebug = true;
-                if(doDebug)  {
-                    qDebug("asked to draw %p[%p] [%s::%s] %p[%p] [%d] [%dx%d]", widget, hiview, widget->metaObject()->className(),
-                           widget->objectName().local8Bit().data(), widget->parentWidget(),
-                           (HIViewRef)(widget->parentWidget() ? qt_mac_nativeview_for(widget->parentWidget()) : (HIViewRef)0),
-                           HIViewIsCompositingEnabled(hiview), qt_mac_posInWindow(widget).x(), qt_mac_posInWindow(widget).y());
-#if 0
-                    QVector<QRect> region_rects = qrgn.rects();
-                    qDebug("Region! %d", region_rects.count());
-                    for(int i = 0; i < region_rects.count(); i++)
-                        qDebug("%d %d %d %d", region_rects[i].x(), region_rects[i].y(),
-                               region_rects[i].width(), region_rects[i].height());
-                    region_rects = widget->d_func()->clp.rects();
-                    qDebug("Widget Region! %d", region_rects.count());
-                    for(int i = 0; i < region_rects.count(); i++)
-                        qDebug("%d %d %d %d", region_rects[i].x(), region_rects[i].y(),
-                               region_rects[i].width(), region_rects[i].height());
-#endif
-                }
-#endif
-                if (widget->isVisible() && widget->updatesEnabled()) { //process the actual paint event.
-                    if(widget->testAttribute(Qt::WA_WState_InPaintEvent))
-                        qWarning("QWidget::repaint: Recursive repaint detected");
-                    if (widget->isWindow() && !widget->d_func()->isOpaque
-                        && !widget->testAttribute(Qt::WA_MacBrushedMetal)) {
-                        QRect qrgnRect = qrgn.boundingRect();
-                        CGContextClearRect(cg, CGRectMake(qrgnRect.x(), qrgnRect.y(), qrgnRect.width(), qrgnRect.height()));
-                    }
-
-                    QPoint redirectionOffset(0, 0);
-                    QWidget *tl = widget->window();
-                    if (tl) {
-                        Qt::WindowFlags flags = tl->windowFlags();
-                        if (flags & Qt::FramelessWindowHint
-                            || (flags & Qt::CustomizeWindowHint && !(flags & Qt::WindowTitleHint))) {
-                            if(tl->d_func()->extra && !tl->d_func()->extra->mask.isEmpty())
-                                redirectionOffset += tl->d_func()->extra->mask.boundingRect().topLeft();
-                        }
-                    }
-
-                    //setup the context
-                    widget->setAttribute(Qt::WA_WState_InPaintEvent);
-                    QPaintEngine *engine = widget->paintEngine();
-                    if (engine)
-                        engine->setSystemClip(qrgn);
-
-                    //handle the erase
-                    if (engine && (!widget->testAttribute(Qt::WA_NoSystemBackground)
-                        && (widget->isWindow() || widget->autoFillBackground())
-                        || widget->testAttribute(Qt::WA_TintedBackground)
-                        || widget->testAttribute(Qt::WA_StyledBackground))) {
-#ifdef DEBUG_WIDGET_PAINT
-                        if(doDebug)
-                            qDebug(" Handling erase for [%s::%s]", widget->metaObject()->className(),
-                                   widget->objectName().local8Bit().data());
-#endif
-                        if (!redirectionOffset.isNull())
-                            widget->d_func()->setRedirected(widget, redirectionOffset);
-
-                        bool was_unclipped = widget->testAttribute(Qt::WA_PaintUnclipped);
-                        widget->setAttribute(Qt::WA_PaintUnclipped, false);
-                        QPainter p(widget);
-                        p.setClipping(false);
-                        if(was_unclipped)
-                            widget->setAttribute(Qt::WA_PaintUnclipped);
-                        widget->d_func()->paintBackground(&p, qrgn, widget->isWindow() ? DrawAsRoot : 0);
-                        if (widget->testAttribute(Qt::WA_TintedBackground)) {
-                            QColor tint = widget->palette().window().color();
-                            tint.setAlphaF(.6);
-                            const QVector<QRect> &rects = qrgn.rects();
-                            for (int i = 0; i < rects.size(); ++i)
-                                p.fillRect(rects.at(i), tint);
-                        }
-                        p.end();
-                        if (!redirectionOffset.isNull())
-                            widget->d_func()->restoreRedirected();
-                    }
-
-                    if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
-                        CallNextEventHandler(er, event);
-
-                    //send the paint
-                    redirectionOffset += widget->data->wrect.topLeft(); // Map from system to qt coordinates
-                    if (!redirectionOffset.isNull())
-                        widget->d_func()->setRedirected(widget, redirectionOffset);
-                    qrgn.translate(redirectionOffset);
-                    QPaintEvent e(qrgn);
-                    widget->d_func()->dirtyOnWidget = QRegion();
-                    QApplication::sendSpontaneousEvent(widget, &e);
-                    if (!redirectionOffset.isNull())
-                        widget->d_func()->restoreRedirected();
-
-                    //cleanup
-                    if (engine)
-                        engine->setSystemClip(QRegion());
-
-                    widget->setAttribute(Qt::WA_WState_InPaintEvent, false);
-                    if(!widget->testAttribute(Qt::WA_PaintOutsidePaintEvent) && widget->paintingActive())
-                        qWarning("QWidget: It is dangerous to leave painters active on a widget outside of the PaintEvent");
-                }
-
-                widget->d_func()->hd = 0;
-                widget->d_func()->qd_hd = 0;
-                CGContextRestoreGState(cg);
-            } else if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) {
-                CallNextEventHandler(er, event);
-            }
-        } else if(ekind == kEventControlInitialize) {
-            if(HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) {
-                UInt32 features = kControlSupportsDragAndDrop | kControlSupportsClickActivation | kControlSupportsFocus;
-                SetEventParameter(event, kEventParamControlFeatures, typeUInt32, sizeof(features), &features);
-            } else {
-                handled_event = false;
-            }
-        } else if(ekind == kEventControlSetFocusPart) {
-            if(widget) {
-                ControlPartCode part;
-                GetEventParameter(event, kEventParamControlPart, typeControlPartCode, 0,
-                                  sizeof(part), 0, &part);
-                if(part == kControlFocusNoPart){
-                    if (widget->hasFocus())
-                        QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
-                } else
-                    widget->setFocus();
-            }
-            if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
-                CallNextEventHandler(er, event);
-        } else if(ekind == kEventControlGetClickActivation) {
-            ClickActivationResult clickT = kActivateAndIgnoreClick;
-            SetEventParameter(event, kEventParamClickActivation, typeClickActivationResult,
-                              sizeof(clickT), &clickT);
-        } else if(ekind == kEventControlGetPartRegion) {
-            handled_event = false;
-            if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget) && CallNextEventHandler(er, event) == noErr) {
-                handled_event = true;
-                break;
-            }
-            if(widget && !widget->isWindow()) {
-                ControlPartCode part;
-                GetEventParameter(event, kEventParamControlPart, typeControlPartCode, 0,
-                                  sizeof(part), 0, &part);
-                if(part == kControlClickableMetaPart && widget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
-                    RgnHandle rgn;
-                    GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
-                                      sizeof(rgn), 0, &rgn);
-                    SetEmptyRgn(rgn);
-                    handled_event = true;
-                } else if(part == kControlStructureMetaPart || part == kControlClickableMetaPart) {
-                    RgnHandle rgn;
-                    GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
-                                      sizeof(rgn), 0, &rgn);
-                    SetRectRgn(rgn, 0, 0, widget->width(), widget->height());
-                    if(QWidgetPrivate::qt_widget_rgn(widget, kWindowStructureRgn, rgn, false))
-                        handled_event = true;
-                } else if(part == kControlOpaqueMetaPart) {
-                    if(widget->d_func()->isOpaque) {
-                        RgnHandle rgn;
-                        GetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle, 0,
-                                          sizeof(RgnHandle), 0, &rgn);
-                        SetRectRgn(rgn, 0, 0, widget->width(), widget->height());
-                        QWidgetPrivate::qt_widget_rgn(widget, kWindowStructureRgn, rgn, false);
-                        SetEventParameter(event, kEventParamControlRegion, typeQDRgnHandle,
-                                sizeof(RgnHandle), &rgn);
-                        handled_event = true;
-                    }
-                }
-            }
-        } else if(ekind == kEventControlOwningWindowChanged) {
-            if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget))
-                CallNextEventHandler(er, event);
-            if(widget && qt_mac_window_for(hiview)) {
-                WindowRef foo = 0;
-                GetEventParameter(event, kEventParamControlCurrentOwningWindow, typeWindowRef, 0,
-                                  sizeof(foo), 0, &foo);
-                widget->d_func()->initWindowPtr();
-            }
-            if (widget)
-                qt_event_request_window_change(widget);
-        } else if(ekind == kEventControlDragEnter || ekind == kEventControlDragWithin ||
-                  ekind == kEventControlDragLeave || ekind == kEventControlDragReceive) {
-            // dnd are really handled in qdnd_mac.cpp,
-            // just modularize the code a little...
-            DragRef drag;
-            GetEventParameter(event, kEventParamDragRef, typeDragRef, 0, sizeof(drag), 0, &drag);
-            handled_event = false;
-            bool drag_allowed = false;
-
-            QWidget *dropWidget = widget;
-            if (qobject_cast<QFocusFrame *>(widget)){
-                // We might shadow widgets underneath the focus
-                // frame, so stay interrested, and let the dnd through
-                drag_allowed = true;
-                handled_event = true;
-                Point where;
-                GetDragMouse(drag, &where, 0);
-                dropWidget = QApplication::widgetAt(QPoint(where.h, where.v));
-
-                if (dropWidget != QDragManager::self()->currentTarget()) {
-                    // We have to 'fake' enter and leave events for the shaddowed widgets:
-                    if (ekind == kEventControlDragEnter) {
-                        if (QDragManager::self()->currentTarget())
-                            QDragManager::self()->currentTarget()->d_func()->qt_mac_dnd_event(kEventControlDragLeave, drag);
-                        if (dropWidget) {
-                            dropWidget->d_func()->qt_mac_dnd_event(kEventControlDragEnter, drag);
-                        }
-                        // Set dropWidget to zero, so qt_mac_dnd_event
-                        // doesn't get called a second time below:
-                        dropWidget = 0;
-                    } else if (ekind == kEventControlDragLeave) {
-                        dropWidget = QDragManager::self()->currentTarget();
-                        if (dropWidget) {
-                            dropWidget->d_func()->qt_mac_dnd_event(kEventControlDragLeave, drag);
-                        }
-                        // Set dropWidget to zero, so qt_mac_dnd_event
-                        // doesn't get called a second time below:
-                        dropWidget = 0;
-                    }
-                }
-            }
-
-            // Send the dnd event to the widget:
-            if (dropWidget && dropWidget->d_func()->qt_mac_dnd_event(ekind, drag)) {
-                drag_allowed = true;
-                handled_event = true;
-            }
-
-            if (ekind == kEventControlDragEnter) {
-                // If we don't accept the enter event, we will
-                // receive no more drag events for this widget
-                const Boolean wouldAccept = drag_allowed ? true : false;
-                SetEventParameter(event, kEventParamControlWouldAcceptDrop, typeBoolean,
-                        sizeof(wouldAccept), &wouldAccept);
-            }
-        } else if (ekind == kEventControlBoundsChanged) {
-            if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_Moved) || widget->testAttribute(Qt::WA_Resized)) {
-                handled_event = false;
-            } else {
-                // Sync our view in case some other (non-Qt) view is controlling us.
-                handled_event = true;
-                Rect newBounds;
-                GetEventParameter(event, kEventParamCurrentBounds,
-                                  typeQDRectangle, 0, sizeof(Rect), 0, &newBounds);
-                QRect rect(newBounds.left, newBounds.top,
-                            newBounds.right - newBounds.left, newBounds.bottom - newBounds.top);
-
-                bool moved = widget->testAttribute(Qt::WA_Moved);
-                bool resized = widget->testAttribute(Qt::WA_Resized);
-                widget->setGeometry(rect);
-                widget->setAttribute(Qt::WA_Moved, moved);
-                widget->setAttribute(Qt::WA_Resized, resized);
-                qt_event_request_window_change(widget);
-            }
-        } else if (ekind == kEventControlGetSizeConstraints) {
-            if (!widget || !qt_isGenuineQWidget(widget)) {
-                handled_event = false;
-            } else {
-                handled_event = true;
-                QWidgetItem item(widget);
-                QSize size = item.minimumSize();
-                HISize hisize = { size.width(), size.height() };
-                SetEventParameter(event, kEventParamMinimumSize, typeHISize, sizeof(HISize), &hisize);
-                size = item.maximumSize();
-                hisize.width = size.width() + 2; // ### shouldn't have to add 2 (but it works).
-                hisize.height = size.height();
-                SetEventParameter(event, kEventParamMaximumSize, typeHISize, sizeof(HISize), &hisize);
-            }
-        } else if (ekind == kEventControlVisibilityChanged) {
-            handled_event = false;
-            if (widget) {
-                qt_event_request_window_change(widget);
-                if (!HIViewIsVisible(HIViewRef(widget->winId()))) {
-                    if (widget == qt_button_down)
-                        qt_button_down = 0;
-                }
-            }
-        }
-        break; }
-    case kEventClassMouse: {
-        bool send_to_app = false;
-        if(qt_button_down)
-            send_to_app = true;
-        if(send_to_app) {
-            OSStatus err = SendEventToApplication(event);
-            if(err != noErr)
-                handled_event = false;
-        } else {
-            CallNextEventHandler(er, event);
-        }
-        break; }
-    default:
-        handled_event = false;
-        break;
-    }
-    if(!handled_event) //let the event go through
-        return eventNotHandledErr;
-    return noErr; //we eat the event
-}
-#endif
-
-OSViewRef qt_mac_create_widget(QWidget *widget, QWidgetPrivate *widgetPrivate, OSViewRef parent)
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QCocoaView) *view = [[QT_MANGLE_NAMESPACE(QCocoaView) alloc] initWithQWidget:widget widgetPrivate:widgetPrivate];
-
-#ifdef ALIEN_DEBUG
-    qDebug() << "Creating NSView for" << widget;
-#endif
-
-    if (view && parent)
-        [parent addSubview:view];
-    return view;
-#else
-    Q_UNUSED(widget);
-    Q_UNUSED(widgetPrivate);
-    if(!widget_class) {
-        OSStatus err = HIObjectRegisterSubclass(kObjectQWidget, kHIViewClassID, 0, make_widget_eventUPP(),
-                                                GetEventTypeCount(widget_events), widget_events,
-                                                0, &widget_class);
-        if (err && err != hiObjectClassExistsErr)
-            qWarning("QWidget: Internal error (%d)", __LINE__);
-    }
-    HIViewRef ret = 0;
-    if(HIObjectCreate(kObjectQWidget, 0, (HIObjectRef*)&ret) != noErr)
-        qWarning("QWidget: Internal error (%d)", __LINE__);
-    if(ret && parent)
-        HIViewAddSubview(parent, ret);
-    return ret;
-#endif
-}
-
-void qt_mac_unregister_widget()
-{
-#ifndef QT_MAC_USE_COCOA
-    HIObjectUnregisterClass(widget_class);
-    widget_class = 0;
-#endif
-}
-
-void QWidgetPrivate::toggleDrawers(bool visible)
-{
-    for (int i = 0; i < children.size(); ++i) {
-        register QObject *object = children.at(i);
-        if (!object->isWidgetType())
-            continue;
-        QWidget *widget = static_cast<QWidget*>(object);
-        if(qt_mac_is_macdrawer(widget)) {
-            bool oldState = widget->testAttribute(Qt::WA_WState_ExplicitShowHide);
-            if(visible) {
-                if (!widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
-                    widget->show();
-            } else {
-                widget->hide();
-                if(!oldState)
-                    widget->setAttribute(Qt::WA_WState_ExplicitShowHide, false);
-            }
-        }
-    }
-}
-
-/*****************************************************************************
-  QWidgetPrivate member functions
- *****************************************************************************/
-bool QWidgetPrivate::qt_mac_update_sizer(QWidget *w, int up)
-{
-    // I'm not sure what "up" is
-    if(!w || !w->isWindow())
-        return false;
-
-    QTLWExtra *topData = w->d_func()->topData();
-    QWExtra *extraData = w->d_func()->extraData();
-    // topData->resizer is only 4 bits, so subtracting -1 from zero causes bad stuff
-    // to happen, prevent that here (you really want the thing hidden).
-    if (up >= 0 || topData->resizer != 0)
-        topData->resizer += up;
-    OSWindowRef windowRef = qt_mac_window_for(OSViewRef(w->effectiveWinId()));
-    {
-#ifndef QT_MAC_USE_COCOA
-        WindowClass wclass;
-        GetWindowClass(windowRef, &wclass);
-        if(!(GetAvailableWindowAttributes(wclass) & kWindowResizableAttribute))
-            return true;
-#endif
-    }
-    bool remove_grip = (topData->resizer || (w->windowFlags() & Qt::FramelessWindowHint)
-                        || (extraData->maxw && extraData->maxh &&
-                            extraData->maxw == extraData->minw && extraData->maxh == extraData->minh));
-#ifndef QT_MAC_USE_COCOA
-    WindowAttributes attr;
-    GetWindowAttributes(windowRef, &attr);
-    if(remove_grip) {
-        if(attr & kWindowResizableAttribute) {
-            ChangeWindowAttributes(qt_mac_window_for(w), kWindowNoAttributes,
-                                   kWindowResizableAttribute);
-            ReshapeCustomWindow(qt_mac_window_for(w));
-        }
-    } else if(!(attr & kWindowResizableAttribute)) {
-        ChangeWindowAttributes(windowRef, kWindowResizableAttribute,
-                               kWindowNoAttributes);
-        ReshapeCustomWindow(windowRef);
-    }
-#else
-    [windowRef setShowsResizeIndicator:!remove_grip];
-#endif
-    return true;
-}
-
-void QWidgetPrivate::qt_clean_root_win()
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    [qt_root_win release];
-#else
-    if(!qt_root_win)
-        return;
-    CFRelease(qt_root_win);
-#endif
-    qt_root_win = 0;
-}
-
-bool QWidgetPrivate::qt_create_root_win()
-{
-    if(qt_root_win)
-        return false;
-    const QSize desktopSize = qt_mac_desktopSize();
-    QRect desktopRect(QPoint(0, 0), desktopSize);
-#ifdef QT_MAC_USE_COCOA
-    qt_root_win = qt_mac_create_window(0, kOverlayWindowClass, NSBorderlessWindowMask, desktopRect);
-#else
-    WindowAttributes wattr = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
-    qt_root_win = qt_mac_create_window(0, kOverlayWindowClass, wattr, desktopRect);
-#endif
-    if(!qt_root_win)
-        return false;
-    qAddPostRoutine(qt_clean_root_win);
-    return true;
-}
-
-bool QWidgetPrivate::qt_widget_rgn(QWidget *widget, short wcode, RgnHandle rgn, bool force = false)
-{
-    bool ret = false;
-#ifndef QT_MAC_USE_COCOA
-    switch(wcode) {
-    case kWindowStructureRgn: {
-        if(widget) {
-            if(widget->d_func()->extra && !widget->d_func()->extra->mask.isEmpty()) {
-                QRegion rin = qt_mac_convert_mac_region(rgn);
-                if(!rin.isEmpty()) {
-                    QPoint rin_tl = rin.boundingRect().topLeft(); //in offset
-                    rin.translate(-rin_tl.x(), -rin_tl.y()); //bring into same space as below
-                    QRegion mask = widget->d_func()->extra->mask;
-                    Qt::WindowFlags flags = widget->windowFlags();
-                    if(widget->isWindow()
-                       && !(flags & Qt::FramelessWindowHint
-                            || (flags & Qt::CustomizeWindowHint && !(flags & Qt::WindowTitleHint)))) {
-                        QRegion title;
-                        {
-                            QMacSmartQuickDrawRegion rgn(qt_mac_get_rgn());
-                            GetWindowRegion(qt_mac_window_for(widget), kWindowTitleBarRgn, rgn);
-                            title = qt_mac_convert_mac_region(rgn);
-                        }
-                        QRect br = title.boundingRect();
-                        mask.translate(0, br.height()); //put the mask 'under' the title bar..
-                        title.translate(-br.x(), -br.y());
-                        mask += title;
-                    }
-
-                    QRegion cr = rin & mask;
-                    cr.translate(rin_tl.x(), rin_tl.y()); //translate back to incoming space
-                    CopyRgn(QMacSmartQuickDrawRegion(cr.toQDRgn()), rgn);
-                }
-                ret = true;
-            } else if(force) {
-                QRegion cr(widget->geometry());
-                CopyRgn(QMacSmartQuickDrawRegion(cr.toQDRgn()), rgn);
-                ret = true;
-            }
-        }
-        break; }
-    default: break;
-    }
-    //qDebug() << widget << ret << wcode << qt_mac_convert_mac_region(rgn);
-#else
-    Q_UNUSED(widget);
-    Q_UNUSED(wcode);
-    Q_UNUSED(rgn);
-    Q_UNUSED(force);
-#endif
-    return ret;
-}
-
-/*****************************************************************************
-  QWidget member functions
- *****************************************************************************/
-void QWidgetPrivate::determineWindowClass()
-{
-    Q_Q(QWidget);
-#if !defined(QT_NO_MAINWINDOW) && !defined(QT_NO_TOOLBAR)
-    // Make sure that QMainWindow has the MacWindowToolBarButtonHint when the
-    // unifiedTitleAndToolBarOnMac property is ON. This is to avoid reentry of
-    // setParent() triggered by the QToolBar::event(QEvent::ParentChange).
-    QMainWindow *mainWindow = qobject_cast<QMainWindow *>(q);
-    if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
-        data.window_flags |= Qt::MacWindowToolBarButtonHint;
-    }
-#endif
-#ifndef QT_MAC_USE_COCOA
-// ### COCOA:Interleave these better!
-
-    const Qt::WindowType type = q->windowType();
-    Qt::WindowFlags &flags = data.window_flags;
-    const bool popup = (type == Qt::Popup);
-    if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
-        flags |= Qt::FramelessWindowHint;
-
-    WindowClass wclass = kSheetWindowClass;
-    if(qt_mac_is_macdrawer(q))
-        wclass = kDrawerWindowClass;
-    else if (q->testAttribute(Qt::WA_ShowModal) && flags & Qt::CustomizeWindowHint)
-        wclass = kDocumentWindowClass;
-    else if(popup || (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 && type == Qt::SplashScreen))
-        wclass = kModalWindowClass;
-    else if(q->testAttribute(Qt::WA_ShowModal))
-        wclass = kMovableModalWindowClass;
-    else if(type == Qt::ToolTip)
-        wclass = kHelpWindowClass;
-    else if(type == Qt::Tool || (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5
-                                 && type == Qt::SplashScreen))
-        wclass = kFloatingWindowClass;
-    else
-        wclass = kDocumentWindowClass;
-
-    WindowGroupRef grp = 0;
-    WindowAttributes wattr = (kWindowCompositingAttribute | kWindowStandardHandlerAttribute);
-    if (q->testAttribute(Qt::WA_MacFrameworkScaled))
-        wattr |= kWindowFrameworkScaledAttribute;
-    if(qt_mac_is_macsheet(q)) {
-        //grp = GetWindowGroupOfClass(kMovableModalWindowClass);
-        wclass = kSheetWindowClass;
-    } else {
-        grp = GetWindowGroupOfClass(wclass);
-        // Shift things around a bit to get the correct window class based on the presence
-        // (or lack) of the border.
-       bool customize = flags & Qt::CustomizeWindowHint;
-        bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
-        if (framelessWindow) {
-            if(wclass == kDocumentWindowClass) {
-                wattr |= kWindowNoTitleBarAttribute;
-            } else if(wclass == kFloatingWindowClass) {
-                wattr |= kWindowNoTitleBarAttribute;
-            } else if (wclass  == kMovableModalWindowClass) {
-                wclass = kModalWindowClass;
-            }
-        } else {
-            if(wclass != kModalWindowClass)
-                wattr |= kWindowResizableAttribute;
-        }
-        // Only add extra decorations (well, buttons) for widgets that can have them
-        // and have an actual border we can put them on.
-        if(wclass != kModalWindowClass && wclass != kMovableModalWindowClass
-                && wclass != kSheetWindowClass && wclass != kPlainWindowClass
-                && !framelessWindow && wclass != kDrawerWindowClass
-                && wclass != kHelpWindowClass) {
-            if (flags & Qt::WindowMaximizeButtonHint)
-                wattr |= kWindowFullZoomAttribute;
-            if (flags & Qt::WindowMinimizeButtonHint)
-                wattr |= kWindowCollapseBoxAttribute;
-            if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
-                wattr |= kWindowCloseBoxAttribute;
-            if (flags & Qt::MacWindowToolBarButtonHint)
-                wattr |= kWindowToolbarButtonAttribute;
-        } else {
-            // Clear these hints so that we aren't call them on invalid windows
-            flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
-                       | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
-        }
-    }
-    if((popup || type == Qt::Tool) && !q->isModal())
-        wattr |= kWindowHideOnSuspendAttribute;
-    wattr |= kWindowLiveResizeAttribute;
-
-#ifdef DEBUG_WINDOW_CREATE
-#define ADD_DEBUG_WINDOW_NAME(x) { x, #x }
-    struct {
-        UInt32 tag;
-        const char *name;
-    } known_attribs[] = {
-        ADD_DEBUG_WINDOW_NAME(kWindowCompositingAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowMetalAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowCollapseBoxAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowHorizontalZoomAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowVerticalZoomAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowResizableAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowNoActivatesAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowNoUpdatesAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowOpaqueForEventsAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowLiveResizeAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowCloseBoxAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
-        { 0, 0 }
-    }, known_classes[] = {
-        ADD_DEBUG_WINDOW_NAME(kHelpWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kPlainWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kDrawerWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kSheetWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kFloatingWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kDocumentWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kMovableModalWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kModalWindowClass),
-        { 0, 0 }
-    };
-    qDebug("Qt: internal: ************* Creating new window %p (%s::%s)", q, q->metaObject()->className(),
-            q->objectName().toLocal8Bit().constData());
-    bool found_class = false;
-    for(int i = 0; known_classes[i].name; i++) {
-        if(wclass == known_classes[i].tag) {
-            found_class = true;
-            qDebug("Qt: internal: ** Class: %s", known_classes[i].name);
-            break;
-        }
-    }
-    if(!found_class)
-        qDebug("Qt: internal: !! Class: Unknown! (%d)", (int)wclass);
-    if(wattr) {
-        WindowAttributes tmp_wattr = wattr;
-        qDebug("Qt: internal: ** Attributes:");
-        for(int i = 0; tmp_wattr && known_attribs[i].name; i++) {
-            if((tmp_wattr & known_attribs[i].tag) == known_attribs[i].tag) {
-                tmp_wattr ^= known_attribs[i].tag;
-                qDebug("Qt: internal: * %s %s", known_attribs[i].name,
-                        (GetAvailableWindowAttributes(wclass) & known_attribs[i].tag) ? "" : "(*)");
-            }
-        }
-        if(tmp_wattr)
-            qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)tmp_wattr);
-    }
-#endif
-
-    /* Just to be extra careful we will change to the kUtilityWindowClass if the
-       requested attributes cannot be used */
-    if((GetAvailableWindowAttributes(wclass) & wattr) != wattr) {
-        WindowClass tmp_class = wclass;
-        if(wclass == kToolbarWindowClass || wclass == kUtilityWindowClass)
-            wclass = kFloatingWindowClass;
-        if(tmp_class != wclass) {
-            if(!grp)
-                grp = GetWindowGroupOfClass(wclass);
-            wclass = tmp_class;
-        }
-    }
-    topData()->wclass = wclass;
-    topData()->wattr = wattr;
-#else
-    const Qt::WindowType type = q->windowType();
-    Qt::WindowFlags &flags = data.window_flags;
-    const bool popup = (type == Qt::Popup);
-    if (type == Qt::ToolTip || type == Qt::SplashScreen || popup)
-        flags |= Qt::FramelessWindowHint;
-
-    WindowClass wclass = kSheetWindowClass;
-    if(qt_mac_is_macdrawer(q))
-        wclass = kDrawerWindowClass;
-    else if (q->testAttribute(Qt::WA_ShowModal) && flags & Qt::CustomizeWindowHint)
-        wclass = kDocumentWindowClass;
-    else if(popup || (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 && type == Qt::SplashScreen))
-        wclass = kModalWindowClass;
-    else if(type == Qt::Dialog)
-        wclass = kMovableModalWindowClass;
-    else if(type == Qt::ToolTip)
-        wclass = kHelpWindowClass;
-    else if(type == Qt::Tool || (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5
-                                 && type == Qt::SplashScreen))
-        wclass = kFloatingWindowClass;
-    else if(q->testAttribute(Qt::WA_ShowModal))
-        wclass = kMovableModalWindowClass;
-    else
-        wclass = kDocumentWindowClass;
-
-    WindowAttributes wattr = NSBorderlessWindowMask;
-    if(qt_mac_is_macsheet(q)) {
-        //grp = GetWindowGroupOfClass(kMovableModalWindowClass);
-        wclass = kSheetWindowClass;
-        wattr = NSTitledWindowMask | NSResizableWindowMask;
-    } else {
-#ifndef QT_MAC_USE_COCOA
-        grp = GetWindowGroupOfClass(wclass);
-#endif
-        // Shift things around a bit to get the correct window class based on the presence
-        // (or lack) of the border.
-       bool customize = flags & Qt::CustomizeWindowHint;
-        bool framelessWindow = (flags & Qt::FramelessWindowHint || (customize && !(flags & Qt::WindowTitleHint)));
-        if (framelessWindow) {
-            if (wclass == kDocumentWindowClass) {
-                wclass = kSimpleWindowClass;
-            } else if (wclass == kFloatingWindowClass) {
-                wclass = kToolbarWindowClass;
-            } else if (wclass  == kMovableModalWindowClass) {
-                wclass  = kModalWindowClass;
-            }
-        } else {
-            wattr |= NSTitledWindowMask;
-            if (wclass != kModalWindowClass)
-                wattr |= NSResizableWindowMask;
-        }
-        // Only add extra decorations (well, buttons) for widgets that can have them
-        // and have an actual border we can put them on.
-        if (wclass != kModalWindowClass
-                && wclass != kSheetWindowClass && wclass != kPlainWindowClass
-                && !framelessWindow && wclass != kDrawerWindowClass
-                && wclass != kHelpWindowClass) {
-            if (flags & Qt::WindowMinimizeButtonHint)
-                wattr |= NSMiniaturizableWindowMask;
-            if (flags & Qt::WindowSystemMenuHint || flags & Qt::WindowCloseButtonHint)
-                wattr |= NSClosableWindowMask;
-        } else {
-            // Clear these hints so that we aren't call them on invalid windows
-            flags &= ~(Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint
-                       | Qt::WindowCloseButtonHint | Qt::WindowSystemMenuHint);
-        }
-    }
-    if (q->testAttribute(Qt::WA_MacBrushedMetal))
-        wattr |= NSTexturedBackgroundWindowMask;
-
-#ifdef DEBUG_WINDOW_CREATE
-#define ADD_DEBUG_WINDOW_NAME(x) { x, #x }
-    struct {
-        UInt32 tag;
-        const char *name;
-    } known_attribs[] = {
-        ADD_DEBUG_WINDOW_NAME(kWindowCompositingAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowMetalAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowStandardHandlerAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowCollapseBoxAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowHorizontalZoomAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowVerticalZoomAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowResizableAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowNoActivatesAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowNoUpdatesAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowOpaqueForEventsAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowLiveResizeAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowCloseBoxAttribute),
-        ADD_DEBUG_WINDOW_NAME(kWindowHideOnSuspendAttribute),
-        { 0, 0 }
-    }, known_classes[] = {
-        ADD_DEBUG_WINDOW_NAME(kHelpWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kPlainWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kDrawerWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kSheetWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kFloatingWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kUtilityWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kDocumentWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kToolbarWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kMovableModalWindowClass),
-        ADD_DEBUG_WINDOW_NAME(kModalWindowClass),
-        { 0, 0 }
-    };
-    qDebug("Qt: internal: ************* Creating new window %p (%s::%s)", q, q->metaObject()->className(),
-            q->objectName().toLocal8Bit().constData());
-    bool found_class = false;
-    for(int i = 0; known_classes[i].name; i++) {
-        if(wclass == known_classes[i].tag) {
-            found_class = true;
-            qDebug("Qt: internal: ** Class: %s", known_classes[i].name);
-            break;
-        }
-    }
-    if(!found_class)
-        qDebug("Qt: internal: !! Class: Unknown! (%d)", (int)wclass);
-    if(wattr) {
-        WindowAttributes tmp_wattr = wattr;
-        qDebug("Qt: internal: ** Attributes:");
-        for(int i = 0; tmp_wattr && known_attribs[i].name; i++) {
-            if((tmp_wattr & known_attribs[i].tag) == known_attribs[i].tag) {
-                tmp_wattr ^= known_attribs[i].tag;
-            }
-        }
-        if(tmp_wattr)
-            qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)tmp_wattr);
-    }
-#endif
-
-#ifndef QT_MAC_USE_COCOA
-    /* Just to be extra careful we will change to the kUtilityWindowClass if the
-       requested attributes cannot be used */
-    if((GetAvailableWindowAttributes(wclass) & wattr) != wattr) {
-        WindowClass tmp_class = wclass;
-        if(wclass == kToolbarWindowClass || wclass == kUtilityWindowClass)
-            wclass = kFloatingWindowClass;
-        if(tmp_class != wclass) {
-            if(!grp)
-                grp = GetWindowGroupOfClass(wclass);
-            wclass = tmp_class;
-        }
-    }
-#endif
-#endif
-    topData()->wclass = wclass;
-    topData()->wattr = wattr;
-}
-
-#ifndef QT_MAC_USE_COCOA  // This is handled in Cocoa via our category.
-void QWidgetPrivate::initWindowPtr()
-{
-    Q_Q(QWidget);
-    OSWindowRef windowRef = qt_mac_window_for(qt_mac_nativeview_for(q)); //do not create!
-    if(!windowRef)
-        return;
-    QWidget *window = q->window(), *oldWindow = 0;
-    if(GetWindowProperty(windowRef, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(oldWindow), 0, &oldWindow) == noErr) {
-        Q_ASSERT(window == oldWindow);
-        return;
-    }
-
-    if(SetWindowProperty(windowRef, kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(window), &window) != noErr)
-        qWarning("Qt:Internal error (%s:%d)", __FILE__, __LINE__); //no real way to recover
-    if(!q->windowType() != Qt::Desktop) { //setup an event callback handler on the window
-        InstallWindowEventHandler(windowRef, make_win_eventUPP(), GetEventTypeCount(window_events),
-                window_events, static_cast<void *>(qApp), &window_event);
-    }
-}
-
-void QWidgetPrivate::finishCreateWindow_sys_Carbon(OSWindowRef windowRef)
-{
-    Q_Q(QWidget);
-    const Qt::WindowType type = q->windowType();
-    Qt::WindowFlags &flags = data.window_flags;
-    QWidget *parentWidget = q->parentWidget();
-
-    const bool desktop = (type == Qt::Desktop);
-    const bool dialog = (type == Qt::Dialog
-                         || type == Qt::Sheet
-                         || type == Qt::Drawer
-                         || (flags & Qt::MSWindowsFixedSizeDialogHint));
-    QTLWExtra *topExtra = topData();
-    quint32 wattr = topExtra->wattr;
-    if (!desktop)
-        SetAutomaticControlDragTrackingEnabledForWindow(windowRef, true);
-    HIWindowChangeFeatures(windowRef, kWindowCanCollapse, 0);
-    if (wattr & kWindowHideOnSuspendAttribute)
-        HIWindowChangeAvailability(windowRef, kHIWindowExposeHidden, 0);
-    else
-        HIWindowChangeAvailability(windowRef, 0, kHIWindowExposeHidden);
-    if ((flags & Qt::WindowStaysOnTopHint))
-        ChangeWindowAttributes(windowRef, kWindowNoAttributes, kWindowHideOnSuspendAttribute);
-    if (qt_mac_is_macdrawer(q) && parentWidget)
-        SetDrawerParent(windowRef, qt_mac_window_for (parentWidget));
-    if (topExtra->group) {
-        qt_mac_release_window_group(topExtra->group);
-        topExtra->group = 0;
-    }
-    if (type == Qt::ToolTip)
-        qt_mac_set_window_group_to_tooltip(windowRef);
-    else if (type == Qt::Popup && (flags & Qt::WindowStaysOnTopHint))
-        qt_mac_set_window_group_to_popup(windowRef);
-    else if (flags & Qt::WindowStaysOnTopHint)
-        qt_mac_set_window_group_to_stays_on_top(windowRef, type);
-    else if (dialog)
-        SetWindowGroup(windowRef, GetWindowGroupOfClass(kMovableModalWindowClass));
-
-#ifdef DEBUG_WINDOW_CREATE
-    if (WindowGroupRef grpf = GetWindowGroup(windowRef)) {
-        QCFString cfname;
-        CopyWindowGroupName(grpf, &cfname);
-        SInt32 lvl;
-        GetWindowGroupLevel(grpf, &lvl);
-        const char *from = "Default";
-        if (topExtra && grpf == topData()->group)
-            from = "Created";
-        else if (grpf == grp)
-            from = "Copied";
-        qDebug("Qt: internal: With window group '%s' [%p] @ %d: %s",
-                static_cast<QString>(cfname).toLatin1().constData(), grpf, (int)lvl, from);
-    } else {
-        qDebug("Qt: internal: No window group!!!");
-    }
-    HIWindowAvailability hi_avail = 0;
-    if (HIWindowGetAvailability(windowRef, &hi_avail) == noErr) {
-        struct {
-            UInt32 tag;
-            const char *name;
-        } known_avail[] = {
-            ADD_DEBUG_WINDOW_NAME(kHIWindowExposeHidden),
-            { 0, 0 }
-        };
-        qDebug("Qt: internal: ** HIWindowAvailibility:");
-        for (int i = 0; hi_avail && known_avail[i].name; i++) {
-            if ((hi_avail & known_avail[i].tag) == known_avail[i].tag) {
-                hi_avail ^= known_avail[i].tag;
-                qDebug("Qt: internal: * %s", known_avail[i].name);
-            }
-        }
-        if (hi_avail)
-            qDebug("Qt: internal: !! Attributes: Unknown (%d)", (int)hi_avail);
-    }
-#undef ADD_DEBUG_WINDOW_NAME
-#endif
-    if (extra && !extra->mask.isEmpty())
-        ReshapeCustomWindow(windowRef);
-    SetWindowModality(windowRef, kWindowModalityNone, 0);
-    if (qt_mac_is_macdrawer(q))
-        SetDrawerOffsets(windowRef, 0.0, 25.0);
-    data.fstrut_dirty = true; // when we create a toplevel widget, the frame strut should be dirty
-    HIViewRef hiview = (HIViewRef)data.winid;
-    HIViewRef window_hiview = qt_mac_get_contentview_for(windowRef);
-    if(!hiview) {
-        hiview = qt_mac_create_widget(q, this, window_hiview);
-        setWinId((WId)hiview);
-    } else {
-        HIViewAddSubview(window_hiview, hiview);
-    }
-    if (hiview) {
-        Rect win_rect;
-        GetWindowBounds(qt_mac_window_for (window_hiview), kWindowContentRgn, &win_rect);
-        HIRect bounds = CGRectMake(0, 0, win_rect.right-win_rect.left, win_rect.bottom-win_rect.top);
-        HIViewSetFrame(hiview, &bounds);
-        HIViewSetVisible(hiview, true);
-        if (q->testAttribute(Qt::WA_DropSiteRegistered))
-            registerDropSite(true);
-        transferChildren();
-    }
-    initWindowPtr();
-
-    if (topExtra->posFromMove) {
-        updateFrameStrut();
-        const QRect &fStrut = frameStrut();
-        Rect r;
-        SetRect(&r, data.crect.left(), data.crect.top(), data.crect.right() + 1, data.crect.bottom() + 1);
-        SetRect(&r, r.left + fStrut.left(), r.top + fStrut.top(),
-                    (r.left + fStrut.left() + data.crect.width()) - fStrut.right(),
-                    (r.top + fStrut.top() + data.crect.height()) - fStrut.bottom());
-        SetWindowBounds(windowRef, kWindowContentRgn, &r);
-        topExtra->posFromMove = false;
-    }
-
-    if (q->testAttribute(Qt::WA_WState_WindowOpacitySet)){
-        q->setWindowOpacity(topExtra->opacity / 255.0f);
-    } else if (qt_mac_is_macsheet(q)){
-        SetThemeWindowBackground(qt_mac_window_for(q), kThemeBrushSheetBackgroundTransparent, true);
-        CGFloat alpha = 0;
-        GetWindowAlpha(qt_mac_window_for(q), &alpha);
-        if (alpha == 1){
-            // For some reason the 'SetThemeWindowBackground' does not seem
-            // to work. So we do this little hack until it hopefully starts to
-            // work in newer versions of mac OS.
-            q->setWindowOpacity(0.95f);
-            q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
-        }
-    } else{
-        // If the window has been recreated after beeing e.g. a sheet,
-        // make sure that we don't report a faulty opacity:
-        q->setWindowOpacity(1.0f);
-        q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
-    }
-
-    // Since we only now have a window, sync our state.
-    macUpdateHideOnSuspend();
-    macUpdateOpaqueSizeGrip();
-    macUpdateMetalAttribute();
-    macUpdateIgnoreMouseEvents();
-    setWindowTitle_helper(extra->topextra->caption);
-    setWindowIconText_helper(extra->topextra->iconText);
-    setWindowFilePath_helper(extra->topextra->filePath);
-    setWindowModified_sys(q->isWindowModified());
-    updateFrameStrut();
-    qt_mac_update_sizer(q);
-    applyMaxAndMinSizeOnWindow();
-}
-#else  // QT_MAC_USE_COCOA
-
-void QWidgetPrivate::setWindowLevel()
-{
-    Q_Q(QWidget);
-    const QWidget * const windowParent = q->window()->parentWidget();
-    const QWidget * const primaryWindow = windowParent ? windowParent->window() : 0;
-    NSInteger winLevel = -1;
-
-    if (q->windowType() == Qt::Popup) {
-        winLevel = NSPopUpMenuWindowLevel;
-        // Popup should be in at least the same level as its parent.
-        if (primaryWindow) {
-            OSWindowRef parentRef = qt_mac_window_for(primaryWindow);
-            winLevel = qMax([parentRef level], winLevel);
-        }
-    } else if (q->windowType() == Qt::Tool) {
-        winLevel = NSFloatingWindowLevel;
-    } else if (q->windowType() == Qt::Dialog) {
-        // Correct modality level (NSModalPanelWindowLevel) will be
-        // set by cocoa when creating a modal session later.
-        winLevel = NSNormalWindowLevel;
-    }
-
-    // StayOnTop window should appear above Tool windows.
-    if (data.window_flags & Qt::WindowStaysOnTopHint)
-        winLevel = NSPopUpMenuWindowLevel;
-    // Tooltips should appear above StayOnTop windows.
-    if (q->windowType() == Qt::ToolTip)
-        winLevel = NSScreenSaverWindowLevel;
-    // All other types are Normal level.
-    if (winLevel == -1)
-        winLevel = NSNormalWindowLevel;
-    [qt_mac_window_for(q) setLevel:winLevel];
-}
-
-void QWidgetPrivate::finishCreateWindow_sys_Cocoa(void * /*NSWindow * */ voidWindowRef)
-{
-    Q_Q(QWidget);
-    QMacCocoaAutoReleasePool pool;
-    NSWindow *windowRef = static_cast<NSWindow *>(voidWindowRef);
-    const Qt::WindowType type = q->windowType();
-    Qt::WindowFlags &flags = data.window_flags;
-    QWidget *parentWidget = q->parentWidget();
-
-    const bool popup = (type == Qt::Popup);
-    const bool dialog = (type == Qt::Dialog
-                         || type == Qt::Sheet
-                         || type == Qt::Drawer
-                         || (flags & Qt::MSWindowsFixedSizeDialogHint));
-    QTLWExtra *topExtra = topData();
-
-    if ((popup || type == Qt::Tool || type == Qt::ToolTip) && !q->isModal()) {
-        [windowRef setHidesOnDeactivate:YES];
-    } else {
-        [windowRef setHidesOnDeactivate:NO];
-    }
-    if (q->testAttribute(Qt::WA_MacNoShadow))
-        [windowRef setHasShadow:NO];
-    else
-        [windowRef setHasShadow:YES];
-    Q_UNUSED(parentWidget);
-    Q_UNUSED(dialog);
-
-    data.fstrut_dirty = true; // when we create a toplevel widget, the frame strut should be dirty
-
-    OSViewRef nsview = (OSViewRef)data.winid;
-    if (!nsview) {
-        nsview = qt_mac_create_widget(q, this, 0);
-        setWinId(WId(nsview));
-    }
-    [windowRef setContentView:nsview];
-    [nsview setHidden:NO];
-    transferChildren();
-
-    // Tell Cocoa explicit that we wan't the view to receive key events
-    // (regardless of focus policy) because this is how it works on other
-    // platforms (and in the carbon port):
-    [windowRef makeFirstResponder:nsview];
-
-    if (topExtra->posFromMove) {
-        updateFrameStrut();
-
-        const QRect &fStrut = frameStrut();
-        const QRect &crect = data.crect;
-        const QRect frameRect(QPoint(crect.left(), crect.top()),
-                              QSize(fStrut.left() + fStrut.right() + crect.width(),
-                                    fStrut.top() + fStrut.bottom() + crect.height()));
-        NSRect cocoaFrameRect = NSMakeRect(frameRect.x(), flipYCoordinate(frameRect.bottom() + 1),
-                                           frameRect.width(), frameRect.height());
-        [windowRef setFrame:cocoaFrameRect display:NO];
-        topExtra->posFromMove = false;
-    }
-
-    if (q->testAttribute(Qt::WA_WState_WindowOpacitySet)){
-        q->setWindowOpacity(topExtra->opacity / 255.0f);
-    } else if (qt_mac_is_macsheet(q)){
-        CGFloat alpha = [qt_mac_window_for(q) alphaValue];
-        if (alpha >= 1.0) {
-            q->setWindowOpacity(0.95f);
-            q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
-        }
-    } else{
-        // If the window has been recreated after beeing e.g. a sheet,
-        // make sure that we don't report a faulty opacity:
-        q->setWindowOpacity(1.0f);
-        q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
-    }
-
-    // Its more performant to handle the mouse cursor
-    // ourselves, expecially when using alien widgets:
-    [windowRef disableCursorRects];
-
-    setWindowLevel();
-    macUpdateHideOnSuspend();
-    macUpdateOpaqueSizeGrip();
-    macUpdateIgnoreMouseEvents();
-    setWindowTitle_helper(extra->topextra->caption);
-    setWindowIconText_helper(extra->topextra->iconText);
-    setWindowModified_sys(q->isWindowModified());
-    updateFrameStrut();
-    syncCocoaMask();
-    macUpdateIsOpaque();
-    qt_mac_update_sizer(q);
-    applyMaxAndMinSizeOnWindow();
-}
-
-#endif // QT_MAC_USE_COCOA
-
-/*
- Recreates widget window. Useful if immutable
- properties for it has changed.
- */
-void QWidgetPrivate::recreateMacWindow()
-{
-    Q_Q(QWidget);
-    OSViewRef myView = qt_mac_nativeview_for(q);
-    OSWindowRef oldWindow = qt_mac_window_for(myView);
-#ifndef QT_MAC_USE_COCOA
-    HIViewRemoveFromSuperview(myView);
-    determineWindowClass();
-    createWindow_sys();
-
-    if (QMainWindowLayout *mwl = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q))) {
-        mwl->updateHIToolBarStatus();
-    }
-
-    if (IsWindowVisible(oldWindow))
-        show_sys();
-#else
-    QMacCocoaAutoReleasePool pool;
-    [myView removeFromSuperview];
-    determineWindowClass();
-    createWindow_sys();
-    if (NSToolbar *toolbar = [oldWindow toolbar]) {
-        OSWindowRef newWindow = qt_mac_window_for(myView);
-        [newWindow setToolbar:toolbar];
-        [toolbar setVisible:[toolbar isVisible]];
-    }
-    if ([oldWindow isVisible]){
-        if ([oldWindow isSheet])
-            [[NSApplication sharedApplication] endSheet:oldWindow];
-        [oldWindow orderOut:oldWindow];
-        show_sys();
-    }
-#endif // QT_MAC_USE_COCOA
-
-    // Release the window after creating the new window, because releasing it early
-    // may cause the app to quit ("close on last window closed attribute")
-    qt_mac_destructWindow(oldWindow);
-}
-
-void QWidgetPrivate::createWindow_sys()
-{
-    Q_Q(QWidget);
-    Qt::WindowFlags &flags = data.window_flags;
-    QWidget *parentWidget = q->parentWidget();
-
-    QTLWExtra *topExtra = topData();
-    if (topExtra->embedded)
-        return;  // Simply return because this view "is" the top window.
-    quint32 wattr = topExtra->wattr;
-
-    if(parentWidget && (parentWidget->window()->windowFlags() & Qt::WindowStaysOnTopHint)) // If our parent has Qt::WStyle_StaysOnTop, so must we
-        flags |= Qt::WindowStaysOnTopHint;
-
-    data.fstrut_dirty = true;
-
-    OSWindowRef windowRef = qt_mac_create_window(q, topExtra->wclass, wattr, data.crect);
-    if (windowRef == 0)
-        qWarning("QWidget: Internal error: %s:%d: If you reach this error please contact Qt Support and include the\n"
-                "      WidgetFlags used in creating the widget.", __FILE__, __LINE__);
-#ifndef QT_MAC_USE_COCOA
-    finishCreateWindow_sys_Carbon(windowRef);
-#else
-    finishCreateWindow_sys_Cocoa(windowRef);
-#endif
-}
-
-void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow)
-{
-    Q_Q(QWidget);
-    QMacCocoaAutoReleasePool pool;
-
-    OSViewRef destroyid = 0;
-#ifndef QT_MAC_USE_COCOA
-    window_event = 0;
-#endif
-
-    Qt::WindowType type = q->windowType();
-    Qt::WindowFlags flags = data.window_flags;
-    QWidget *parentWidget = q->parentWidget();
-
-    bool topLevel = (flags & Qt::Window);
-    bool popup = (type == Qt::Popup);
-    bool dialog = (type == Qt::Dialog
-                   || type == Qt::Sheet
-                   || type == Qt::Drawer
-                   || (flags & Qt::MSWindowsFixedSizeDialogHint));
-    bool desktop = (type == Qt::Desktop);
-
-    // Determine this early for top-levels so, we can use it later.
-    if (topLevel)
-        determineWindowClass();
-
-    if (desktop) {
-        QSize desktopSize = qt_mac_desktopSize();
-        q->setAttribute(Qt::WA_WState_Visible);
-        data.crect.setRect(0, 0, desktopSize.width(), desktopSize.height());
-        dialog = popup = false;                  // force these flags off
-    } else {
-        if (topLevel && (type != Qt::Drawer)) {
-            if (QDesktopWidget *dsk = QApplication::desktop()) { // calc pos/size from screen
-                const bool wasResized = q->testAttribute(Qt::WA_Resized);
-                const bool wasMoved = q->testAttribute(Qt::WA_Moved);
-                int deskn = dsk->primaryScreen();
-                if (parentWidget && parentWidget->windowType() != Qt::Desktop)
-                    deskn = dsk->screenNumber(parentWidget);
-                QRect screenGeo = dsk->screenGeometry(deskn);
-                if (!wasResized) {
-#ifndef QT_MAC_USE_COCOA
-                    data.crect.setSize(QSize(screenGeo.width()/2, 4*screenGeo.height()/10));
-#else
-                    NSRect newRect = [NSWindow frameRectForContentRect:NSMakeRect(0, 0,
-                                                                  screenGeo.width() / 2.,
-                                                                  4 * screenGeo.height() / 10.)
-                                        styleMask:topData()->wattr];
-                    data.crect.setSize(QSize(newRect.size.width, newRect.size.height));
-#endif
-                    // Constrain to minimums and maximums we've set
-                    if (extra->minw > 0)
-                        data.crect.setWidth(qMax(extra->minw, data.crect.width()));
-                    if (extra->minh > 0)
-                        data.crect.setHeight(qMax(extra->minh, data.crect.height()));
-                    if (extra->maxw > 0)
-                        data.crect.setWidth(qMin(extra->maxw, data.crect.width()));
-                    if (extra->maxh > 0)
-                        data.crect.setHeight(qMin(extra->maxh, data.crect.height()));
-                }
-                if (!wasMoved && !q->testAttribute(Qt::WA_DontShowOnScreen))
-                    data.crect.moveTopLeft(QPoint(screenGeo.width()/4,
-                                                  3 * screenGeo.height() / 10));
-            }
-        }
-    }
-
-
-    if(!window)                              // always initialize
-        initializeWindow=true;
-
-    hd = 0;
-    if(window) {                                // override the old window (with a new NSView)
-        OSViewRef nativeView = OSViewRef(window);
-        OSViewRef parent = 0;
-#ifndef QT_MAC_USE_COCOA
-        CFRetain(nativeView);
-#else
-        [nativeView retain];
-#endif
-        if (destroyOldWindow)
-            destroyid = qt_mac_nativeview_for(q);
-        bool transfer = false;
-        setWinId((WId)nativeView);
-#ifndef QT_MAC_USE_COCOA
-#ifndef HIViewInstallEventHandler
-        // Macro taken from the CarbonEvents Header on Tiger
-#define HIViewInstallEventHandler( target, handler, numTypes, list, userData, outHandlerRef ) \
-               InstallEventHandler( HIObjectGetEventTarget( (HIObjectRef) (target) ), (handler), (numTypes), (list), (userData), (outHandlerRef) )
-#endif
-        HIViewInstallEventHandler(nativeView, make_widget_eventUPP(), GetEventTypeCount(widget_events), widget_events, 0, 0);
-#endif
-        if(topLevel) {
-            for(int i = 0; i < 2; ++i) {
-                if(i == 1) {
-                    if(!initializeWindow)
-                        break;
-                    createWindow_sys();
-                }
-                if(OSWindowRef windowref = qt_mac_window_for(nativeView)) {
-#ifndef QT_MAC_USE_COCOA
-                    CFRetain(windowref);
-#else
-                    [windowref retain];
-#endif
-                    if (initializeWindow) {
-                        parent = qt_mac_get_contentview_for(windowref);
-                    } else {
-#ifndef QT_MAC_USE_COCOA
-                        parent = HIViewGetSuperview(nativeView);
-#else
-                        parent = [nativeView superview];
-#endif
-                    }
-                    break;
-                }
-            }
-            if(!parent)
-                transfer = true;
-        } else if (parentWidget) {
-            // I need to be added to my parent, therefore my parent needs an NSView
-            // Alien note: a 'window' was supplied as argument, meaning this widget
-            // is not alien. So therefore the parent cannot be alien either.
-            parentWidget->createWinId();
-            parent = qt_mac_nativeview_for(parentWidget);
-        }
-        if(parent != nativeView && parent) {
-#ifndef QT_MAC_USE_COCOA
-            HIViewAddSubview(parent, nativeView);
-#else
-            [parent addSubview:nativeView];
-#endif
-        }
-        if(transfer)
-            transferChildren();
-        data.fstrut_dirty = true; // we'll re calculate this later
-        q->setAttribute(Qt::WA_WState_Visible,
-#ifndef QT_MAC_USE_COCOA
-                        HIViewIsVisible(nativeView)
-#else
-                        ![nativeView isHidden]
-#endif
-                        );
-        if(initializeWindow) {
-#ifndef QT_MAC_USE_COCOA
-            HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
-            HIViewSetFrame(nativeView, &bounds);
-            q->setAttribute(Qt::WA_WState_Visible, HIViewIsVisible(nativeView));
-#else
-            NSRect bounds = NSMakeRect(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
-            [nativeView setFrame:bounds];
-            q->setAttribute(Qt::WA_WState_Visible, [nativeView isHidden]);
-#endif
-        }
-#ifndef QT_MAC_USE_COCOA
-        initWindowPtr();
-#endif
-    } else if (desktop) {                        // desktop widget
-        if (!qt_root_win)
-            QWidgetPrivate::qt_create_root_win();
-        Q_ASSERT(qt_root_win);
-        WId rootWinID = 0;
-#ifndef QT_MAC_USE_COCOA
-        CFRetain(qt_root_win);
-        if(HIViewRef rootContentView = HIViewGetRoot(qt_root_win)) {
-            rootWinID = (WId)rootContentView;
-            CFRetain(rootContentView);
-        }
-#else
-        [qt_root_win retain];
-        if (OSViewRef rootContentView = [qt_root_win contentView]) {
-            rootWinID = (WId)rootContentView;
-            [rootContentView retain];
-        }
-#endif
-        setWinId(rootWinID);
-    } else if (topLevel) {
-        determineWindowClass();
-        if(OSViewRef osview = qt_mac_create_widget(q, this, 0)) {
-#ifndef QT_MAC_USE_COCOA
-            HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(),
-                                       data.crect.width(), data.crect.height());
-            HIViewSetFrame(osview, &bounds);
-#else
-            NSRect bounds = NSMakeRect(data.crect.x(), flipYCoordinate(data.crect.y()),
-                                       data.crect.width(), data.crect.height());
-            [osview setFrame:bounds];
-#endif
-            setWinId((WId)osview);
-        }
-    } else {
-        data.fstrut_dirty = false; // non-toplevel widgets don't have a frame, so no need to update the strut
-
-#ifdef QT_MAC_USE_COCOA
-        if (q->testAttribute(Qt::WA_NativeWindow) == false || q->internalWinId() != 0) {
-            // INVARIANT: q is Alien, and we should not create an NSView to back it up.
-        } else
-#endif
-        if (OSViewRef osview = qt_mac_create_widget(q, this, qt_mac_nativeview_for(parentWidget))) {
-#ifndef QT_MAC_USE_COCOA
-            HIRect bounds = CGRectMake(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
-            HIViewSetFrame(osview, &bounds);
-            setWinId((WId)osview);
-#else
-            NSRect bounds = NSMakeRect(data.crect.x(), data.crect.y(), data.crect.width(), data.crect.height());
-            [osview setFrame:bounds];
-            setWinId((WId)osview);
-            if (q->isVisible()) {
-                // If q were Alien before, but now became native (e.g. if a call to
-                // winId was done from somewhere), we need to show the view immidiatly:
-                QMacCocoaAutoReleasePool pool;
-                [osview setHidden:NO];
-            }
-#endif
-        }
-    }
-
-    updateIsOpaque();
-
-    if (q->testAttribute(Qt::WA_DropSiteRegistered))
-        registerDropSite(true);
-    if (q->hasFocus())
-        setFocus_sys();
-    if (!topLevel && initializeWindow)
-        setWSGeometry();
-    if (destroyid)
-        qt_mac_destructView(destroyid);
-}
-
-/*!
-    Returns the QuickDraw handle of the widget. Use of this function is not
-    portable. This function will return 0 if QuickDraw is not supported, or
-    if the handle could not be created.
-
-    \warning This function is only available on Mac OS X.
-*/
-
-Qt::HANDLE
-QWidget::macQDHandle() const
-{
-#ifndef QT_MAC_USE_COCOA
-    return d_func()->qd_hd;
-#else
-    return 0;
-#endif
-}
-
-/*!
-  Returns the CoreGraphics handle of the widget. Use of this function is
-  not portable. This function will return 0 if no painter context can be
-  established, or if the handle could not be created.
-
-  \warning This function is only available on Mac OS X.
-*/
-Qt::HANDLE
-QWidget::macCGHandle() const
-{
-    return handle();
-}
-
-void qt_mac_updateParentUnderAlienWidget(QWidget *alienWidget)
-{
-    QWidget *nativeParent = alienWidget->nativeParentWidget();
-    if (!nativeParent)
-        return;
-
-    QPoint globalPos = alienWidget->mapToGlobal(QPoint(0, 0));
-    QRect dirtyRect = QRect(nativeParent->mapFromGlobal(globalPos), alienWidget->size());
-    nativeParent->update(dirtyRect);
-}
-
-void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
-{
-    Q_D(QWidget);
-    QMacCocoaAutoReleasePool pool;
-    d->aboutToDestroy();
-    if (!isWindow() && parentWidget())
-        parentWidget()->d_func()->invalidateBuffer(d->effectiveRectFor(geometry()));
-    if (!internalWinId())
-        qt_mac_updateParentUnderAlienWidget(this);
-    d->deactivateWidgetCleanup();
-    qt_mac_event_release(this);
-    if(testAttribute(Qt::WA_WState_Created)) {
-        setAttribute(Qt::WA_WState_Created, false);
-        QObjectList chldrn = children();
-        for(int i = 0; i < chldrn.size(); i++) {  // destroy all widget children
-            QObject *obj = chldrn.at(i);
-            if(obj->isWidgetType())
-                static_cast<QWidget*>(obj)->destroy(destroySubWindows, destroySubWindows);
-        }
-        if(mac_mouse_grabber == this)
-            releaseMouse();
-        if(mac_keyboard_grabber == this)
-            releaseKeyboard();
-
-        if(testAttribute(Qt::WA_ShowModal))          // just be sure we leave modal
-            QApplicationPrivate::leaveModal(this);
-        else if((windowType() == Qt::Popup))
-            qApp->d_func()->closePopup(this);
-        if (destroyWindow) {
-            if(OSViewRef hiview = qt_mac_nativeview_for(this)) {
-                OSWindowRef window = 0;
-                NSDrawer *drawer = nil;
-#ifdef QT_MAC_USE_COCOA
-                if (qt_mac_is_macdrawer(this)) {
-                    drawer = qt_mac_drawer_for(this);
-                } else
-#endif
-                if (isWindow())
-                    window = qt_mac_window_for(hiview);
-
-                // Because of how "destruct" works, we have to do just a normal release for the root_win.
-                if (window && window == qt_root_win) {
-#ifndef QT_MAC_USE_COCOA
-                    CFRelease(hiview);
-#else
-                    [hiview release];
-#endif
-                } else {
-                    qt_mac_destructView(hiview);
-                }
-                if (drawer)
-                    qt_mac_destructDrawer(drawer);
-                if (window)
-                    qt_mac_destructWindow(window);
-            }
-#ifdef QT_MAC_USE_COCOA
-            if (isWindow())
-                QCoreGraphicsPaintEngine::clearColorSpace(this);
-#endif
-        }
-        QT_TRY {
-            d->setWinId(0);
-        } QT_CATCH (const std::bad_alloc &) {
-            // swallow - destructors must not throw
-       }
-    }
-}
-
-void QWidgetPrivate::transferChildren()
-{
-    Q_Q(QWidget);
-    if (!q->internalWinId())
-        return;  // Can't add any views anyway
-
-    QObjectList chlist = q->children();
-    for (int i = 0; i < chlist.size(); ++i) {
-        QObject *obj = chlist.at(i);
-        if (obj->isWidgetType()) {
-            QWidget *w = (QWidget *)obj;
-            if (!w->isWindow()) {
-                // This seems weird, no need to call it in a loop right?
-                if (!topData()->caption.isEmpty())
-                    setWindowTitle_helper(extra->topextra->caption);
-                if (w->internalWinId()) {
-#ifndef QT_MAC_USE_COCOA
-                    HIViewAddSubview(qt_mac_nativeview_for(q), qt_mac_nativeview_for(w));
-#else
-                    // New NSWindows get an extra reference when drops are
-                    // registered (at least in 10.5) which means that we may
-                    // access the window later and get a crash (becasue our
-                    // widget is dead). Work around this be having the drop
-                    // site disabled until it is part of the new hierarchy.
-                    bool oldRegistered = w->testAttribute(Qt::WA_DropSiteRegistered);
-                    w->setAttribute(Qt::WA_DropSiteRegistered, false);
-                    [qt_mac_nativeview_for(w) retain];
-                    [qt_mac_nativeview_for(w) removeFromSuperview];
-                    [qt_mac_nativeview_for(q) addSubview:qt_mac_nativeview_for(w)];
-                    [qt_mac_nativeview_for(w) release];
-                    w->setAttribute(Qt::WA_DropSiteRegistered, oldRegistered);
-#endif
-                }
-            }
-        }
-    }
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QWidgetPrivate::setSubWindowStacking(bool set)
-{
-    // After hitting too many unforeseen bugs trying to put Qt on top of the cocoa child
-    // window API, we have decided to revert this behaviour as much as we can. We
-    // therefore now only allow child windows to exist for children of modal dialogs.
-    static bool use_behaviour_qt473 = !qgetenv("QT_MAC_USE_CHILDWINDOWS").isEmpty();
-
-    // This will set/remove a visual relationship between parent and child on screen.
-    // The reason for doing this is to ensure that a child always stacks infront of
-    // its parent. Unfortunatly is turns out that [NSWindow addChildWindow] has
-    // several unwanted side-effects, one of them being the moving of a child when
-    // moving the parent, which we choose to accept. A way tougher side-effect is
-    // that Cocoa will hide the parent if you hide the child. And in the case of
-    // a tool window, since it will normally hide when you deactivate the
-    // application, Cocoa will hide the parent upon deactivate as well. The result often
-    // being no more visible windows on screen. So, to make a long story short, we only
-    // allow parent-child relationships between windows that both are either a plain window
-    // or a dialog.
-
-    Q_Q(QWidget);
-    if (!q->isWindow())
-        return;
-    NSWindow *qwin = [qt_mac_nativeview_for(q) window];
-    if (!qwin)
-        return;
-    Qt::WindowType qtype = q->windowType();
-    if (set && !(qtype == Qt::Window || qtype == Qt::Dialog))
-        return;
-    if (set && ![qwin isVisible])
-        return;
-
-    if (QWidget *parent = q->parentWidget()) {
-        if (NSWindow *pwin = [qt_mac_nativeview_for(parent) window]) {
-            if (set) {
-                Qt::WindowType ptype = parent->window()->windowType();
-                if ([pwin isVisible]
-                    && (ptype == Qt::Window || ptype == Qt::Dialog)
-                    && ![qwin parentWindow]
-                    && (use_behaviour_qt473 || parent->windowModality() == Qt::ApplicationModal)) {
-                    NSInteger level = [qwin level];
-                    [pwin addChildWindow:qwin ordered:NSWindowAbove];
-                    if ([qwin level] < level)
-                        [qwin setLevel:level];
-                }
-            } else {
-                [pwin removeChildWindow:qwin];
-            }
-        }
-    }
-
-    // Only set-up child windows for q if q is modal:
-    if (set && !use_behaviour_qt473 && q->windowModality() != Qt::ApplicationModal)
-        return;
-
-    QObjectList widgets = q->children();
-    for (int i=0; i<widgets.size(); ++i) {
-        QWidget *child = qobject_cast<QWidget *>(widgets.at(i));
-        if (child && child->isWindow()) {
-            if (NSWindow *cwin = [qt_mac_nativeview_for(child) window]) {
-                if (set) {
-                    Qt::WindowType ctype = child->window()->windowType();
-                    if ([cwin isVisible] && (ctype == Qt::Window || ctype == Qt::Dialog) && ![cwin parentWindow]) {
-                        NSInteger level = [cwin level];
-                        [qwin addChildWindow:cwin ordered:NSWindowAbove];
-                        if ([cwin level] < level)
-                            [cwin setLevel:level];
-                    }
-                } else {
-                    [qwin removeChildWindow:qt_mac_window_for(child)];
-                }
-            }
-        }
-    }
-}
-#endif
-
-void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
-{
-    Q_Q(QWidget);
-    QMacCocoaAutoReleasePool pool;
-    QTLWExtra *topData = maybeTopData();
-    bool wasCreated = q->testAttribute(Qt::WA_WState_Created);
-#ifdef QT_MAC_USE_COCOA
-    bool wasWindow = q->isWindow();
-#endif
-    OSViewRef old_id = 0;
-
-    if (q->isVisible() && q->parentWidget() && parent != q->parentWidget())
-        q->parentWidget()->d_func()->invalidateBuffer(effectiveRectFor(q->geometry()));
-
-    // Maintain the glWidgets list on parent change: remove "our" gl widgets
-    // from the list on the old parent and grandparents.
-    if (glWidgets.isEmpty() == false) {
-        QWidget *current = q->parentWidget();
-        while (current) {
-            for (QList<QWidgetPrivate::GlWidgetInfo>::const_iterator it = glWidgets.constBegin();
-                 it != glWidgets.constEnd(); ++it)
-                current->d_func()->glWidgets.removeAll(*it);
-
-            if (current->isWindow())
-                break;
-            current = current->parentWidget();
-        }
-    }
-
-#ifndef QT_MAC_USE_COCOA
-    EventHandlerRef old_window_event = 0;
-#else
-    bool oldToolbarVisible = false;
-    NSDrawer *oldDrawer = nil;
-    NSToolbar *oldToolbar = 0;
-#endif
-    if (wasCreated && !(q->windowType() == Qt::Desktop)) {
-        old_id = qt_mac_nativeview_for(q);
-#ifndef QT_MAC_USE_COCOA
-        old_window_event = window_event;
-#else
-        if (qt_mac_is_macdrawer(q)) {
-            oldDrawer = qt_mac_drawer_for(q);
-        }
-        if (wasWindow) {
-            OSWindowRef oldWindow = qt_mac_window_for(old_id);
-            oldToolbar = [oldWindow toolbar];
-            if (oldToolbar) {
-                [oldToolbar retain];
-                oldToolbarVisible = [oldToolbar isVisible];
-                [oldWindow setToolbar:nil];
-            }
-        }
-#endif
-    }
-    QWidget* oldtlw = q->window();
-
-    if (q->testAttribute(Qt::WA_DropSiteRegistered))
-        q->setAttribute(Qt::WA_DropSiteRegistered, false);
-
-    //recreate and setup flags
-    QObjectPrivate::setParent_helper(parent);
-    bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
-    if (wasCreated && !qt_isGenuineQWidget(q))
-        return;
-
-    if (!q->testAttribute(Qt::WA_WState_WindowOpacitySet)) {
-        q->setWindowOpacity(1.0f);
-        q->setAttribute(Qt::WA_WState_WindowOpacitySet, false);
-    }
-
-    setWinId(0); //do after the above because they may want the id
-
-    data.window_flags = f;
-    q->setAttribute(Qt::WA_WState_Created, false);
-    q->setAttribute(Qt::WA_WState_Visible, false);
-    q->setAttribute(Qt::WA_WState_Hidden, false);
-    adjustFlags(data.window_flags, q);
-    // keep compatibility with previous versions, we need to preserve the created state.
-    // (but we recreate the winId for the widget being reparented, again for compatibility,
-    // unless this is an alien widget. )
-    const bool nonWindowWithCreatedParent = !q->isWindow() && parent->testAttribute(Qt::WA_WState_Created);
-    const bool nativeWidget = q->internalWinId() != 0;
-    if (wasCreated || (nativeWidget && nonWindowWithCreatedParent)) {
-        createWinId();
-        if (q->isWindow()) {
-#ifndef QT_MAC_USE_COCOA
-            // We do this down below for wasCreated, so avoid doing this twice
-            // (only for performance, it gets called a lot anyway).
-            if (!wasCreated) {
-                if (QMainWindowLayout *mwl = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q))) {
-                    mwl->updateHIToolBarStatus();
-                }
-            }
-#else
-            // Simply transfer our toolbar over. Everything should stay put, unlike in Carbon.
-            if (oldToolbar && !(f & Qt::FramelessWindowHint)) {
-                OSWindowRef newWindow = qt_mac_window_for(q);
-                [newWindow setToolbar:oldToolbar];
-                [oldToolbar release];
-                [oldToolbar setVisible:oldToolbarVisible];
-            }
-#endif
-        }
-    }
-    if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden)
-        q->setAttribute(Qt::WA_WState_Hidden);
-    q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);
-
-#ifdef QT_MAC_USE_COCOA
-    // If we add a child to the unified toolbar, we have to redirect the painting.
-    if (parent && parent->d_func() && parent->d_func()->isInUnifiedToolbar) {
-        if (parent->d_func()->unifiedSurface) {
-            QWidget *toolbar = parent->d_func()->toolbar_ancestor;
-            parent->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
-        }
-    }
-#endif // QT_MAC_USE_COCOA
-
-    if (wasCreated) {
-        transferChildren();
-#ifndef QT_MAC_USE_COCOA
-        // If we were a unified window, We just transfered our toolbars out of the unified toolbar.
-        // So redo the status one more time. It apparently is not an issue with Cocoa.
-        if (q->isWindow()) {
-            if (QMainWindowLayout *mwl = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q))) {
-                mwl->updateHIToolBarStatus();
-            }
-        }
-#endif
-
-        if (topData &&
-                (!topData->caption.isEmpty() || !topData->filePath.isEmpty()))
-            setWindowTitle_helper(q->windowTitle());
-    }
-
-    if (q->testAttribute(Qt::WA_AcceptDrops)
-        || (!q->isWindow() && q->parentWidget()
-            && q->parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
-        q->setAttribute(Qt::WA_DropSiteRegistered, true);
-
-    //cleanup
-#ifndef QT_MAC_USE_COCOA
-    if (old_window_event)
-        RemoveEventHandler(old_window_event);
-#endif
-    if (old_id) { //don't need old window anymore
-        OSWindowRef window = (oldtlw == q) ? qt_mac_window_for(old_id) : 0;
-        qt_mac_destructView(old_id);
-
-#ifdef QT_MAC_USE_COCOA
-        if (oldDrawer) {
-            qt_mac_destructDrawer(oldDrawer);
-        } else
-#endif
-        if (window)
-            qt_mac_destructWindow(window);
-    }
-
-    // Maintain the glWidgets list on parent change: add "our" gl widgets
-    // to the list on the new parent and grandparents.
-    if (glWidgets.isEmpty() == false && !q->isWindow()) {
-        QWidget *current = q->parentWidget();
-        while (current) {
-            current->d_func()->glWidgets += glWidgets;
-            if (current->isWindow())
-                break;
-            current = current->parentWidget();
-        }
-    }
-    invalidateBuffer(q->rect());
-    qt_event_request_window_change(q);
-}
-
-QPoint QWidget::mapToGlobal(const QPoint &pos) const
-{
-    Q_D(const QWidget);
-    if (!internalWinId()) {
-        QPoint p = pos + data->crect.topLeft();
-        return isWindow() ?  p : parentWidget()->mapToGlobal(p);
-    }
-#ifndef QT_MAC_USE_COCOA
-    QPoint tmp = d->mapToWS(pos);
-    HIPoint hi_pos = CGPointMake(tmp.x(), tmp.y());
-    HIViewConvertPoint(&hi_pos, qt_mac_nativeview_for(this), 0);
-    Rect win_rect;
-    GetWindowBounds(qt_mac_window_for(this), kWindowStructureRgn, &win_rect);
-    return QPoint((int)hi_pos.x+win_rect.left, (int)hi_pos.y+win_rect.top);
-#else
-    QPoint tmp = d->mapToWS(pos);
-    NSPoint hi_pos = NSMakePoint(tmp.x(), tmp.y());
-    hi_pos = [qt_mac_nativeview_for(this) convertPoint:hi_pos toView:nil];
-    NSRect win_rect = [qt_mac_window_for(this) frame];
-    hi_pos.x += win_rect.origin.x;
-    hi_pos.y += win_rect.origin.y;
-    // If we aren't the desktop we need to flip, if you flip the desktop on itself, you get the other problem.
-    return ((window()->windowFlags() & Qt::Desktop) == Qt::Desktop) ? QPointF(hi_pos.x, hi_pos.y).toPoint()
-                                                                    : flipPoint(hi_pos).toPoint();
-#endif
-}
-
-QPoint QWidget::mapFromGlobal(const QPoint &pos) const
-{
-    Q_D(const QWidget);
-    if (!internalWinId()) {
-        QPoint p = isWindow() ?  pos : parentWidget()->mapFromGlobal(pos);
-        return p - data->crect.topLeft();
-    }
-#ifndef QT_MAC_USE_COCOA
-    Rect win_rect;
-    GetWindowBounds(qt_mac_window_for(this), kWindowStructureRgn, &win_rect);
-    HIPoint hi_pos = CGPointMake(pos.x()-win_rect.left, pos.y()-win_rect.top);
-    HIViewConvertPoint(&hi_pos, 0, qt_mac_nativeview_for(this));
-    return d->mapFromWS(QPoint((int)hi_pos.x, (int)hi_pos.y));
-#else
-    NSRect win_rect = [qt_mac_window_for(this) frame];
-    // The Window point is in "Cocoa coordinates," but the view is in "Qt coordinates"
-    // so make sure to keep them in sync.
-    NSPoint hi_pos = NSMakePoint(pos.x()-win_rect.origin.x,
-                                 flipYCoordinate(pos.y())-win_rect.origin.y);
-    hi_pos = [qt_mac_nativeview_for(this) convertPoint:hi_pos fromView:0];
-    return d->mapFromWS(QPoint(qRound(hi_pos.x), qRound(hi_pos.y)));
-#endif
-}
-
-void QWidgetPrivate::updateSystemBackground()
-{
-}
-
-void QWidgetPrivate::setCursor_sys(const QCursor &)
-{
-    qt_mac_update_cursor();
-}
-
-void QWidgetPrivate::unsetCursor_sys()
-{
-    qt_mac_update_cursor();
-}
-
-void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
-{
-    Q_Q(QWidget);
-    if (q->isWindow()) {
-#ifndef QT_MAC_USE_COCOA
-        SetWindowTitleWithCFString(qt_mac_window_for(q), QCFString(caption));
-#else
-        QMacCocoaAutoReleasePool pool;
-        [qt_mac_window_for(q) setTitle:qt_mac_QStringToNSString(caption)];
-#endif
-    }
-}
-
-void QWidgetPrivate::setWindowModified_sys(bool mod)
-{
-    Q_Q(QWidget);
-    if (q->isWindow() && q->testAttribute(Qt::WA_WState_Created)) {
-#ifndef QT_MAC_USE_COCOA
-        SetWindowModified(qt_mac_window_for(q), mod);
-#else
-        [qt_mac_window_for(q) setDocumentEdited:mod];
-#endif
-    }
-}
-
-void QWidgetPrivate::setWindowFilePath_sys(const QString &filePath)
-{
-    Q_Q(QWidget);
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    QFileInfo fi(filePath);
-    [qt_mac_window_for(q) setRepresentedFilename:fi.exists() ? qt_mac_QStringToNSString(filePath) : @""];
-#else
-    bool validRef = false;
-    FSRef ref;
-    bzero(&ref, sizeof(ref));
-    OSStatus status;
-
-    if (!filePath.isEmpty()) {
-        status = FSPathMakeRef(reinterpret_cast<const UInt8 *>(filePath.toUtf8().constData()), &ref, 0);
-        validRef = (status == noErr);
-    }
-    // Set the proxy regardless, since this is our way of clearing it as well, but ignore the
-    // return value as well.
-    if (validRef) {
-        status = HIWindowSetProxyFSRef(qt_mac_window_for(q), &ref);
-    } else {
-        status = RemoveWindowProxy(qt_mac_window_for(q));
-    }
-    if (status != noErr)
-        qWarning("QWidget::setWindowFilePath: Error setting proxyicon for path (%s):%ld",
-                qPrintable(filePath), status);
-#endif
-}
-
-void QWidgetPrivate::setWindowIcon_sys(bool forceReset)
-{
-    Q_Q(QWidget);
-
-    if (!q->testAttribute(Qt::WA_WState_Created))
-        return;
-
-    QTLWExtra *topData = this->topData();
-    if (topData->iconPixmap && !forceReset) // already set
-        return;
-
-    QIcon icon = q->windowIcon();
-    QPixmap *pm = 0;
-    if (!icon.isNull()) {
-        // now create the extra
-        if (!topData->iconPixmap) {
-            pm = new QPixmap(icon.pixmap(QSize(22, 22)));
-            topData->iconPixmap = pm;
-        } else {
-            pm = topData->iconPixmap;
-        }
-    }
-    if (q->isWindow()) {
-#ifndef QT_MAC_USE_COCOA
-        IconRef previousIcon = 0;
-        if (icon.isNull()) {
-            RemoveWindowProxy(qt_mac_window_for(q));
-            previousIcon = topData->windowIcon;
-            topData->windowIcon = 0;
-        } else {
-            WindowClass wclass;
-            GetWindowClass(qt_mac_window_for(q), &wclass);
-
-            if (wclass == kDocumentWindowClass) {
-                IconRef newIcon = qt_mac_create_iconref(*pm);
-                previousIcon = topData->windowIcon;
-                topData->windowIcon = newIcon;
-                SetWindowProxyIcon(qt_mac_window_for(q), newIcon);
-            }
-        }
-
-        // Release the previous icon if it was set by this function.
-        if (previousIcon != 0)
-            ReleaseIconRef(previousIcon);
-#else
-        QMacCocoaAutoReleasePool pool;
-        if (icon.isNull())
-            return;
-        NSButton *iconButton = [qt_mac_window_for(q) standardWindowButton:NSWindowDocumentIconButton];
-        if (iconButton == nil) {
-            QCFString string(q->windowTitle());
-            const NSString *tmpString = reinterpret_cast<const NSString *>((CFStringRef)string);
-            [qt_mac_window_for(q) setRepresentedURL:[NSURL fileURLWithPath:const_cast<NSString *>(tmpString)]];
-            iconButton = [qt_mac_window_for(q) standardWindowButton:NSWindowDocumentIconButton];
-        }
-        if (icon.isNull()) {
-            [iconButton setImage:nil];
-        } else {
-            QPixmap scaled = pm->scaled(QSize(16,16), Qt::KeepAspectRatio, Qt::SmoothTransformation);
-            NSImage *image = static_cast<NSImage *>(qt_mac_create_nsimage(scaled));
-            [iconButton setImage:image];
-            [image release];
-        }
-#endif
-    }
-}
-
-void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
-{
-    Q_Q(QWidget);
-    if(q->isWindow() && !iconText.isEmpty()) {
-#ifndef QT_MAC_USE_COCOA
-        SetWindowAlternateTitle(qt_mac_window_for(q), QCFString(iconText));
-#else
-        QMacCocoaAutoReleasePool pool;
-        [qt_mac_window_for(q) setMiniwindowTitle:qt_mac_QStringToNSString(iconText)];
-#endif
-    }
-}
-
-void QWidget::grabMouse()
-{
-    if(isVisible() && !qt_nograb()) {
-        if(mac_mouse_grabber)
-            mac_mouse_grabber->releaseMouse();
-        mac_mouse_grabber=this;
-        qt_mac_setMouseGrabCursor(true);
-    }
-}
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor)
-{
-    if(isVisible() && !qt_nograb()) {
-        if(mac_mouse_grabber)
-            mac_mouse_grabber->releaseMouse();
-        mac_mouse_grabber=this;
-        qt_mac_setMouseGrabCursor(true, const_cast<QCursor *>(&cursor));
-    }
-}
-#endif
-
-void QWidget::releaseMouse()
-{
-    if(!qt_nograb() && mac_mouse_grabber == this) {
-        mac_mouse_grabber = 0;
-        qt_mac_setMouseGrabCursor(false);
-    }
-}
-
-void QWidget::grabKeyboard()
-{
-    if(!qt_nograb()) {
-        if(mac_keyboard_grabber)
-            mac_keyboard_grabber->releaseKeyboard();
-        mac_keyboard_grabber = this;
-    }
-}
-
-void QWidget::releaseKeyboard()
-{
-    if(!qt_nograb() && mac_keyboard_grabber == this)
-        mac_keyboard_grabber = 0;
-}
-
-QWidget *QWidget::mouseGrabber()
-{
-    return mac_mouse_grabber;
-}
-
-QWidget *QWidget::keyboardGrabber()
-{
-    return mac_keyboard_grabber;
-}
-
-void QWidget::activateWindow()
-{
-    QWidget *tlw = window();
-    if(!tlw->isVisible() || !tlw->isWindow() || (tlw->windowType() == Qt::Desktop))
-        return;
-    qt_event_remove_activate();
-
-    QWidget *fullScreenWidget = tlw;
-    QWidget *parentW = tlw;
-    // Find the oldest parent or the parent with fullscreen, whichever comes first.
-    while (parentW) {
-        fullScreenWidget = parentW->window();
-        if (fullScreenWidget->windowState() & Qt::WindowFullScreen)
-            break;
-        parentW = fullScreenWidget->parentWidget();
-    }
-
-    if (fullScreenWidget->windowType() != Qt::ToolTip) {
-        qt_mac_set_fullscreen_mode((fullScreenWidget->windowState() & Qt::WindowFullScreen) &&
-                                               qApp->desktop()->screenNumber(this) == 0);
-    }
-
-    bool windowActive;
-    OSWindowRef win = qt_mac_window_for(tlw);
-#ifndef QT_MAC_USE_COCOA
-    windowActive = IsWindowActive(win);
-#else
-    QMacCocoaAutoReleasePool pool;
-    windowActive = [win isKeyWindow];
-#endif
-    if ((tlw->windowType() == Qt::Popup)
-            || (tlw->windowType() == Qt::Tool)
-            || qt_mac_is_macdrawer(tlw)
-            || windowActive) {
-#ifndef QT_MAC_USE_COCOA
-        ActivateWindow(win, true);
-        qApp->setActiveWindow(tlw);
-#else
-        [win makeKeyWindow];
-#endif
-    } else if(!isMinimized()) {
-#ifndef QT_MAC_USE_COCOA
-        SelectWindow(win);
-#else
-        [win makeKeyAndOrderFront:win];
-#endif
-    }
-}
-
-QWindowSurface *QWidgetPrivate::createDefaultWindowSurface_sys()
-{
-    return new QMacWindowSurface(q_func());
-}
-
-void QWidgetPrivate::update_sys(const QRect &r)
-{
-    Q_Q(QWidget);
-    if (updateRedirectedToGraphicsProxyWidget(q, r))
-        return;
-    dirtyOnWidget += r;
-    macSetNeedsDisplay(r != q->rect() ? r : QRegion());
-}
-
-void QWidgetPrivate::update_sys(const QRegion &rgn)
-{
-    Q_Q(QWidget);
-    if (updateRedirectedToGraphicsProxyWidget(q, rgn))
-        return;
-    dirtyOnWidget += rgn;
-    macSetNeedsDisplay(rgn);
-}
-
-bool QWidgetPrivate::isRealWindow() const
-{
-    return q_func()->isWindow() && !topData()->embedded;
-}
-
-void QWidgetPrivate::show_sys()
-{
-    Q_Q(QWidget);
-    if ((q->windowType() == Qt::Desktop)) //desktop is always visible
-        return;
-
-    invalidateBuffer(q->rect());
-    if (q->testAttribute(Qt::WA_OutsideWSRange))
-        return;
-    QMacCocoaAutoReleasePool pool;
-    q->setAttribute(Qt::WA_Mapped);
-    if (q->testAttribute(Qt::WA_DontShowOnScreen))
-        return;
-
-    bool realWindow = isRealWindow();
-#ifndef QT_MAC_USE_COCOA
-    if (realWindow && !q->testAttribute(Qt::WA_Moved)) {
-        if (qt_mac_is_macsheet(q))
-            recreateMacWindow();
-        q->createWinId();
-        if (QWidget *p = q->parentWidget()) {
-            p->createWinId();
-            RepositionWindow(qt_mac_window_for(q), qt_mac_window_for(p), kWindowCenterOnParentWindow);
-        } else {
-            RepositionWindow(qt_mac_window_for(q), 0, kWindowCenterOnMainScreen);
-        }
-    }
-#endif
-
-    data.fstrut_dirty = true;
-    if (realWindow) {
-        bool isCurrentlyMinimized = (q->windowState() & Qt::WindowMinimized);
-        setModal_sys();
-        OSWindowRef window = qt_mac_window_for(q);
-#ifndef QT_MAC_USE_COCOA
-        SizeWindow(window, q->width(), q->height(), true);
-#endif
-
-#ifdef QT_MAC_USE_COCOA
-        // Make sure that we end up sending a repaint event to
-        // the widget if the window has been visible one before:
-        [qt_mac_get_contentview_for(window) setNeedsDisplay:YES];
-#endif
-        if(qt_mac_is_macsheet(q)) {
-            qt_event_request_showsheet(q);
-        } else if(qt_mac_is_macdrawer(q)) {
-#ifndef QT_MAC_USE_COCOA
-            OpenDrawer(window, kWindowEdgeDefault, false);
-#else
-            NSDrawer *drawer = qt_mac_drawer_for(q);
-            [drawer openOnEdge:[drawer preferredEdge]];
-#endif
-        } else {
-#ifndef QT_MAC_USE_COCOA
-            ShowHide(window, true);
-#else
-            // sync the opacity value back (in case of a fade).
-            [window setAlphaValue:q->windowOpacity()];
-
-            QWidget *top = 0;
-            if (QApplicationPrivate::tryModalHelper(q, &top)) {
-                if (q->testAttribute(Qt::WA_ShowWithoutActivating))
-                    [window orderFront:window];
-                else
-                    [window makeKeyAndOrderFront:window];
-                // If this window is app modal, we need to start spinning
-                // a modal session for it. Interrupting
-                // the event dispatcher will make this happend:
-                if (data.window_modality == Qt::ApplicationModal)
-                    QEventDispatcherMac::instance()->interrupt();
-            } else {
-                // The window is modally shaddowed, so we need to make
-                // sure that we don't pop in front of the modal window:
-                [window orderFront:window];
-                if (!top->testAttribute(Qt::WA_DontShowOnScreen)) {
-                    if (NSWindow *modalWin = qt_mac_window_for(top))
-                        [modalWin orderFront:window];
-                }
-            }
-            setSubWindowStacking(true);
-            qt_mac_update_cursor();
-#endif
-            if (q->windowType() == Qt::Popup) {
-                qt_button_down = 0;
-                if (q->focusWidget())
-                                   q->focusWidget()->d_func()->setFocus_sys();
-                               else
-                    setFocus_sys();
-                       }
-            toggleDrawers(true);
-        }
-        if (isCurrentlyMinimized) { //show in collapsed state
-#ifndef QT_MAC_USE_COCOA
-            CollapseWindow(window, true);
-#else
-            [window miniaturize:window];
-#endif
-        } else if (!q->testAttribute(Qt::WA_ShowWithoutActivating)) {
-#ifndef QT_MAC_USE_COCOA
-            qt_event_request_activate(q);
-#endif
-        }
-    } else if(topData()->embedded || !q->parentWidget() || q->parentWidget()->isVisible()) {
-#ifndef QT_MAC_USE_COCOA
-        HIViewSetVisible(qt_mac_nativeview_for(q), true);
-#else
-        if (NSView *view = qt_mac_nativeview_for(q)) {
-            // INVARIANT: q is native. Just show the view:
-            [view setHidden:NO];
-        } else {
-            // INVARIANT: q is alien. Update q instead:
-            q->update();
-        }
-#endif
-    }
-
-#ifdef QT_MAC_USE_COCOA
-    if ([[NSApplication sharedApplication] isActive] && !qt_button_down && !QWidget::mouseGrabber()){
-        // Update enter/leave immidiatly, don't wait for a move event. But only
-        // if no grab exists (even if the grab points to this widget, it seems, ref X11)
-        QPoint qlocal, qglobal;
-        QWidget *widgetUnderMouse = 0;
-        qt_mac_getTargetForMouseEvent(0, QEvent::Enter, qlocal, qglobal, 0, &widgetUnderMouse);
-        if (q == widgetUnderMouse) {
-            QApplicationPrivate::dispatchEnterLeave(widgetUnderMouse, qt_last_mouse_receiver);
-            qt_last_mouse_receiver = widgetUnderMouse;
-            qt_last_native_mouse_receiver = widgetUnderMouse ?
-                (widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget()) : 0;
-        }
-    }
-#endif
-
-    topLevelAt_cache = 0;
-    qt_event_request_window_change(q);
-}
-
-QPoint qt_mac_nativeMapFromParent(const QWidget *child, const QPoint &pt)
-{
-#ifndef QT_MAC_USE_COCOA
-    CGPoint nativePoint = CGPointMake(pt.x(), pt.y());
-    HIViewConvertPoint(&nativePoint, qt_mac_nativeview_for(child->parentWidget()),
-                       qt_mac_nativeview_for(child));
-#else
-    NSPoint nativePoint = [qt_mac_nativeview_for(child) convertPoint:NSMakePoint(pt.x(), pt.y()) fromView:qt_mac_nativeview_for(child->parentWidget())];
-#endif
-    return QPoint(nativePoint.x, nativePoint.y);
-}
-
-
-void QWidgetPrivate::hide_sys()
-{
-    Q_Q(QWidget);
-    if((q->windowType() == Qt::Desktop)) //you can't hide the desktop!
-        return;
-    QMacCocoaAutoReleasePool pool;
-    if(q->isWindow()) {
-#ifdef QT_MAC_USE_COCOA
-        setSubWindowStacking(false);
-#endif
-        OSWindowRef window = qt_mac_window_for(q);
-        if(qt_mac_is_macsheet(q)) {
-#ifndef QT_MAC_USE_COCOA
-            WindowRef parent = 0;
-            if(GetSheetWindowParent(window, &parent) != noErr || !parent)
-                ShowHide(window, false);
-            else
-                HideSheetWindow(window);
-#else
-            [[NSApplication sharedApplication] endSheet:window];
-            [window orderOut:window];
-#endif
-        } else if(qt_mac_is_macdrawer(q)) {
-#ifndef QT_MAC_USE_COCOA
-            CloseDrawer(window, false);
-#else
-            [qt_mac_drawer_for(q) close];
-#endif
-        } else {
-#ifndef QT_MAC_USE_COCOA
-            ShowHide(window, false);
-#else
-            // Only needed if it exists from 10.7 or later
-            if ((q->windowType() == Qt::Tool) && [window respondsToSelector: @selector(setAnimationBehavior:)])
-                [window setAnimationBehavior: 2]; // NSWindowAnimationBehaviorNone == 2
-
-            [window orderOut:window];
-            // Unfortunately it is not as easy as just hiding the window, we need
-            // to find out if we were in full screen mode. If we were and this is
-            // the last window in full screen mode then we need to unset the full screen
-            // mode. If this is not the last visible window in full screen mode then we
-            // don't change the full screen mode.
-            if(q->isFullScreen())
-            {
-                bool keepFullScreen = false;
-                QWidgetList windowList = qApp->topLevelWidgets();
-                int windowCount = windowList.count();
-                for(int i = 0; i < windowCount; i++)
-                {
-                    QWidget *w = windowList[i];
-                    // If it is the same window, we don't need to check :-)
-                    if(q == w)
-                        continue;
-                    // If they are not visible or if they are minimized then
-                    // we just ignore them.
-                    if(!w->isVisible() || w->isMinimized())
-                        continue;
-                    // Is it full screen?
-                    // Notice that if there is one window in full screen mode then we
-                    // cannot switch the full screen mode off, therefore we just abort.
-                    if(w->isFullScreen()) {
-                        keepFullScreen = true;
-                        break;
-                    }
-                }
-                // No windows in full screen mode, so let just unset that flag.
-                if(!keepFullScreen)
-                    qt_mac_set_fullscreen_mode(false);
-            }
-#endif
-            toggleDrawers(false);
-            qt_mac_update_cursor();
-#ifndef QT_MAC_USE_COCOA
-            // Clear modality (because it seems something that we've always done).
-            if (data.window_modality != Qt::NonModal) {
-                SetWindowModality(window, kWindowModalityNone,
-                          q->parentWidget() ? qt_mac_window_for(q->parentWidget()->window()) : 0);
-            }
-#endif
-        }
-#ifndef QT_MAC_USE_COCOA
-        // If the window we now hide was the active window, we need
-        // to find, and activate another window on screen. NB: Cocoa takes care of this
-        // logic for us (and distinquishes between main windows and key windows)
-        if (q->isActiveWindow() && !(q->windowType() == Qt::Popup)) {
-            QWidget *w = 0;
-            if(q->parentWidget())
-                w = q->parentWidget()->window();
-            if(!w || (!w->isVisible() && !w->isMinimized())) {
-                for (WindowPtr wp = GetFrontWindowOfClass(kMovableModalWindowClass, true);
-                    wp; wp = GetNextWindowOfClass(wp, kMovableModalWindowClass, true)) {
-                    if((w = qt_mac_find_window(wp)))
-                        break;
-                }
-                if (!w){
-                    for (WindowPtr wp = GetFrontWindowOfClass(kDocumentWindowClass, true);
-                            wp; wp = GetNextWindowOfClass(wp, kDocumentWindowClass, true)) {
-                        if((w = qt_mac_find_window(wp)))
-                            break;
-                    }
-                }
-                if (!w){
-                    for(WindowPtr wp = GetFrontWindowOfClass(kSimpleWindowClass, true);
-                        wp; wp = GetNextWindowOfClass(wp, kSimpleWindowClass, true)) {
-                        if((w = qt_mac_find_window(wp)))
-                            break;
-                    }
-                }
-            }
-            if(w && w->isVisible() && !w->isMinimized()) {
-                qt_event_request_activate(w);
-            }
-        }
-#endif
-    } else {
-         invalidateBuffer(q->rect());
-#ifndef QT_MAC_USE_COCOA
-        HIViewSetVisible(qt_mac_nativeview_for(q), false);
-#else
-        if (NSView *view = qt_mac_nativeview_for(q)) {
-            // INVARIANT: q is native. Just hide the view:
-            [view setHidden:YES];
-        } else {
-            // INVARIANT: q is alien. Repaint where q is placed instead:
-            qt_mac_updateParentUnderAlienWidget(q);
-        }
-#endif
-    }
-
-#ifdef QT_MAC_USE_COCOA
-    if ([[NSApplication sharedApplication] isActive] && !qt_button_down && !QWidget::mouseGrabber()){
-        // Update enter/leave immidiatly, don't wait for a move event. But only
-        // if no grab exists (even if the grab points to this widget, it seems, ref X11)
-        QPoint qlocal, qglobal;
-        QWidget *widgetUnderMouse = 0;
-        qt_mac_getTargetForMouseEvent(0, QEvent::Leave, qlocal, qglobal, 0, &widgetUnderMouse);
-        if (q == widgetUnderMouse) {
-            QApplicationPrivate::dispatchEnterLeave(widgetUnderMouse, qt_last_native_mouse_receiver);
-            qt_last_mouse_receiver = widgetUnderMouse;
-            qt_last_native_mouse_receiver = widgetUnderMouse ?
-                (widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget()) : 0;
-       }
-     }
-#endif
-
-    topLevelAt_cache = 0;
-    qt_event_request_window_change(q);
-    deactivateWidgetCleanup();
-    qt_mac_event_release(q);
-}
-
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
-    Q_D(QWidget);
-    bool needShow = false;
-    Qt::WindowStates oldstate = windowState();
-    if (oldstate == newstate)
-        return;
-
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-#endif
-    bool needSendStateChange = true;
-    if(isWindow()) {
-        if((oldstate & Qt::WindowFullScreen) != (newstate & Qt::WindowFullScreen)) {
-            if(newstate & Qt::WindowFullScreen) {
-                if(QTLWExtra *tlextra = d->topData()) {
-                    if(tlextra->normalGeometry.width() < 0) {
-                        if(!testAttribute(Qt::WA_Resized))
-                            adjustSize();
-                        tlextra->normalGeometry = geometry();
-                    }
-                    tlextra->savedFlags = windowFlags();
-                }
-                needShow = isVisible();
-                const QRect fullscreen(qApp->desktop()->screenGeometry(qApp->desktop()->screenNumber(this)));
-                setParent(parentWidget(), Qt::Window | Qt::FramelessWindowHint | (windowFlags() & 0xffff0000)); //save
-                setGeometry(fullscreen);
-                if(!qApp->desktop()->screenNumber(this))
-                    qt_mac_set_fullscreen_mode(true);
-            } else {
-                needShow = isVisible();
-                if(!qApp->desktop()->screenNumber(this))
-                    qt_mac_set_fullscreen_mode(false);
-                setParent(parentWidget(), d->topData()->savedFlags);
-                setGeometry(d->topData()->normalGeometry);
-                d->topData()->normalGeometry.setRect(0, 0, -1, -1);
-            }
-        }
-
-        d->createWinId();
-
-        OSWindowRef window = qt_mac_window_for(this);
-        if((oldstate & Qt::WindowMinimized) != (newstate & Qt::WindowMinimized)) {
-            if (newstate & Qt::WindowMinimized) {
-#ifndef QT_MAC_USE_COCOA
-                CollapseWindow(window, true);
-#else
-                [window miniaturize:window];
-#endif
-            } else {
-#ifndef QT_MAC_USE_COCOA
-                CollapseWindow(window, false);
-#else
-                [window deminiaturize:window];
-#endif
-            }
-            needSendStateChange = oldstate == windowState(); // Collapse didn't change our flags.
-        }
-
-        if((newstate & Qt::WindowMaximized) && !((newstate & Qt::WindowFullScreen))) {
-            if(QTLWExtra *tlextra = d->topData()) {
-                if(tlextra->normalGeometry.width() < 0) {
-                    if(!testAttribute(Qt::WA_Resized))
-                        adjustSize();
-                    tlextra->normalGeometry = geometry();
-                }
-            }
-        } else if(!(newstate & Qt::WindowFullScreen)) {
-//            d->topData()->normalGeometry = QRect(0, 0, -1, -1);
-        }
-
-#ifdef DEBUG_WINDOW_STATE
-#define WSTATE(x) qDebug("%s -- %s --> %s", #x, (oldstate & x) ? "true" : "false", (newstate & x) ? "true" : "false")
-        WSTATE(Qt::WindowMinimized);
-        WSTATE(Qt::WindowMaximized);
-        WSTATE(Qt::WindowFullScreen);
-#undef WSTATE
-#endif
-        if(!(newstate & (Qt::WindowMinimized|Qt::WindowFullScreen)) &&
-           ((oldstate & Qt::WindowFullScreen) || (oldstate & Qt::WindowMinimized) ||
-            (oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized))) {
-            if(newstate & Qt::WindowMaximized) {
-                data->fstrut_dirty = true;
-#ifndef QT_MAC_USE_COCOA
-                HIToolbarRef toolbarRef;
-                if (GetWindowToolbar(window, &toolbarRef) == noErr && toolbarRef
-                        && !isVisible() && !IsWindowToolbarVisible(window)) {
-                    // HIToolbar, needs to be shown so that it's in the structure window
-                    // Typically this is part of a main window and will get shown
-                    // during the show, but it's will make the maximize all wrong.
-                    ShowHideWindowToolbar(window, true, false);
-                    d->updateFrameStrut();  // In theory the dirty would work, but it's optimized out if the window is not visible :(
-                }
-                Rect bounds;
-                QDesktopWidget *dsk = QApplication::desktop();
-                QRect avail = dsk->availableGeometry(dsk->screenNumber(this));
-                SetRect(&bounds, avail.x(), avail.y(), avail.x() + avail.width(), avail.y() + avail.height());
-                if(QWExtra *extra = d->extraData()) {
-                    if(bounds.right - bounds.left > extra->maxw)
-                        bounds.right = bounds.left + extra->maxw;
-                    if(bounds.bottom - bounds.top > extra->maxh)
-                        bounds.bottom = bounds.top + extra->maxh;
-                }
-                if(d->topData()) {
-                    QRect fs = d->frameStrut();
-                    bounds.left += fs.left();
-                    if(bounds.right < avail.x()+avail.width())
-                        bounds.right = qMin<short>((uint)avail.x()+avail.width(), bounds.right+fs.left());
-                    if(bounds.bottom < avail.y()+avail.height())
-                        bounds.bottom = qMin<short>((uint)avail.y()+avail.height(), bounds.bottom+fs.top());
-                    bounds.top += fs.top();
-                    bounds.right -= fs.right();
-                    bounds.bottom -= fs.bottom();
-                }
-                QRect orect(geometry().x(), geometry().y(), width(), height()),
-                      nrect(bounds.left, bounds.top, bounds.right - bounds.left,
-                            bounds.bottom - bounds.top);
-                if(orect != nrect) { // the new rect differ from the old
-                    Point idealSize  = { nrect.height(), nrect.width() };
-                    ZoomWindowIdeal(window, inZoomOut, &idealSize);
-                }
-#else
-                NSToolbar *toolbarRef = [window toolbar];
-                if (toolbarRef && !isVisible() && ![toolbarRef isVisible]) {
-                    // HIToolbar, needs to be shown so that it's in the structure window
-                    // Typically this is part of a main window and will get shown
-                    // during the show, but it's will make the maximize all wrong.
-                    // ### Not sure this is right for NSToolbar...
-                    [toolbarRef setVisible:true];
-//                    ShowHideWindowToolbar(window, true, false);
-                    d->updateFrameStrut();  // In theory the dirty would work, but it's optimized out if the window is not visible :(
-                }
-                // Everything should be handled by Cocoa.
-                if (!windowFlags() & Qt::FramelessWindowHint) {
-                    [window zoom:window];
-                } else {
-                    QDesktopWidget *dsk = QApplication::desktop();
-                    QRect avail = dsk->availableGeometry(dsk->screenNumber(this));
-                    setGeometry(avail);
-                }
-
-#endif
-                needSendStateChange = oldstate == windowState(); // Zoom didn't change flags.
-            } else if(oldstate & Qt::WindowMaximized && !(oldstate & Qt::WindowFullScreen)) {
-#ifndef QT_MAC_USE_COCOA
-                Point idealSize;
-                ZoomWindowIdeal(window, inZoomIn, &idealSize);
-#else
-                [window zoom:window];
-#endif
-                if(QTLWExtra *tlextra = d->topData()) {
-                    setGeometry(tlextra->normalGeometry);
-                    tlextra->normalGeometry.setRect(0, 0, -1, -1);
-                }
-            }
-        }
-    }
-
-    data->window_state = newstate;
-
-    if(needShow)
-        show();
-
-    if(newstate & Qt::WindowActive)
-        activateWindow();
-
-    qt_event_request_window_change(this);
-    if (needSendStateChange) {
-        QWindowStateChangeEvent e(oldstate);
-        QApplication::sendEvent(this, &e);
-    }
-}
-
-void QWidgetPrivate::setFocus_sys()
-{
-    Q_Q(QWidget);
-    if (q->testAttribute(Qt::WA_WState_Created)) {
-#ifdef QT_MAC_USE_COCOA
-        QMacCocoaAutoReleasePool pool;
-        NSView *view = qt_mac_effectiveview_for(q);
-        [[view window] makeFirstResponder:view];
-#else
-        SetKeyboardFocus(qt_mac_window_for(q), qt_mac_nativeview_for(q), 1);
-#endif
-    }
-}
-
-NSComparisonResult compareViews2Raise(id view1, id view2, void *context)
-{
-    id topView = reinterpret_cast<id>(context);
-    if (view1 == topView)
-        return NSOrderedDescending;
-    if (view2 == topView)
-        return NSOrderedAscending;
-    return NSOrderedSame;
-}
-
-void QWidgetPrivate::raise_sys()
-{
-    Q_Q(QWidget);
-    if((q->windowType() == Qt::Desktop))
-        return;
-
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    if (isRealWindow()) {
-        // With the introduction of spaces it is not as simple as just raising the window.
-        // First we need to check if we are in the right space. If we are, then we just continue
-        // as usual. The problem comes when we are not in the active space. There are two main cases:
-        // 1. Our parent was moved to a new space. In this case we want the window to be raised
-        // in the same space as its parent.
-        // 2. We don't have a parent. For this case we will just raise the window and let Cocoa
-        // switch to the corresponding space.
-        // NOTICE: There are a lot of corner cases here. We are keeping this simple for now, if
-        // required we will introduce special handling for some of them.
-        if (!q->testAttribute(Qt::WA_DontShowOnScreen) && q->isVisible()) {
-            OSWindowRef window = qt_mac_window_for(q);
-            // isOnActiveSpace is available only from 10.6 onwards, so we need to check if it is
-            // available before calling it.
-            if([window respondsToSelector:@selector(isOnActiveSpace)]) {
-                if(![window performSelector:@selector(isOnActiveSpace)]) {
-                    QWidget *parentWidget = q->parentWidget();
-                    if(parentWidget) {
-                        OSWindowRef parentWindow = qt_mac_window_for(parentWidget);
-                        if(parentWindow && [parentWindow respondsToSelector:@selector(isOnActiveSpace)]) {
-                            if ([parentWindow performSelector:@selector(isOnActiveSpace)]) {
-                                // The window was created in a different space. Therefore if we want
-                                // to show it in the current space we need to recreate it in the new
-                                // space.
-                                recreateMacWindow();
-                                window = qt_mac_window_for(q);
-                            }
-                        }
-                    }
-                }
-            }
-            [window orderFront:window];
-        }
-        if (qt_mac_raise_process) { //we get to be the active process now
-            ProcessSerialNumber psn;
-            GetCurrentProcess(&psn);
-            SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
-        }
-    } else {
-        NSView *view = qt_mac_nativeview_for(q);
-        NSView *parentView = [view superview];
-        [parentView sortSubviewsUsingFunction:compareViews2Raise context:reinterpret_cast<void *>(view)];
-    }
-    topLevelAt_cache = 0;
-#else
-    if(q->isWindow()) {
-        //raise this window
-        BringToFront(qt_mac_window_for(q));
-        if(qt_mac_raise_process) { //we get to be the active process now
-            ProcessSerialNumber psn;
-            GetCurrentProcess(&psn);
-            SetFrontProcessWithOptions(&psn, kSetFrontProcessFrontWindowOnly);
-        }
-    } else if(q->parentWidget()) {
-        HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderAbove, 0);
-        qt_event_request_window_change(q);
-    }
-#endif
-}
-
-NSComparisonResult compareViews2Lower(id view1, id view2, void *context)
-{
-    id topView = reinterpret_cast<id>(context);
-    if (view1 == topView)
-        return NSOrderedAscending;
-    if (view2 == topView)
-        return NSOrderedDescending;
-    return NSOrderedSame;
-}
-
-void QWidgetPrivate::lower_sys()
-{
-    Q_Q(QWidget);
-    if((q->windowType() == Qt::Desktop))
-        return;
-#ifdef QT_MAC_USE_COCOA
-    if (isRealWindow()) {
-        OSWindowRef window = qt_mac_window_for(q);
-        [window orderBack:window];
-    } else {
-        NSView *view = qt_mac_nativeview_for(q);
-        NSView *parentView = [view superview];
-        [parentView sortSubviewsUsingFunction:compareViews2Lower context:reinterpret_cast<void *>(view)];
-    }
-    topLevelAt_cache = 0;
-#else
-    if(q->isWindow()) {
-        SendBehind(qt_mac_window_for(q), 0);
-    } else if(q->parentWidget()) {
-        invalidateBuffer(q->rect());
-        HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderBelow, 0);
-        qt_event_request_window_change(q);
-    }
-#endif
-}
-
-NSComparisonResult compareViews2StackUnder(id view1, id view2, void *context)
-{
-    const QHash<NSView *, int> &viewOrder = *reinterpret_cast<QHash<NSView *, int> *>(context);
-    if (viewOrder[view1] < viewOrder[view2])
-        return NSOrderedAscending;
-    if (viewOrder[view1] > viewOrder[view2])
-        return NSOrderedDescending;
-    return NSOrderedSame;
-}
-
-void QWidgetPrivate::stackUnder_sys(QWidget *w)
-{
-    // stackUnder
-    Q_Q(QWidget);
-    if(!w || q->isWindow() || (q->windowType() == Qt::Desktop))
-        return;
-#ifdef QT_MAC_USE_COCOA
-    // Do the same trick as lower_sys() and put this widget before the widget passed in.
-    NSView *myView = qt_mac_nativeview_for(q);
-    NSView *wView = qt_mac_nativeview_for(w);
-
-    QHash<NSView *, int> viewOrder;
-    NSView *parentView = [myView superview];
-    NSArray *subviews = [parentView subviews];
-    NSUInteger index = 1;
-    // make a hash of view->zorderindex and make sure z-value is always odd,
-    // so that when we modify the order we create a new (even) z-value which
-    // will not interfere with others.
-    for (NSView *subview in subviews) {
-        viewOrder.insert(subview, index * 2);
-        ++index;
-    }
-    viewOrder[myView] = viewOrder[wView] - 1;
-
-    [parentView sortSubviewsUsingFunction:compareViews2StackUnder context:reinterpret_cast<void *>(&viewOrder)];
-#else
-    QWidget *p = q->parentWidget();
-    if(!p || p != w->parentWidget())
-        return;
-    invalidateBuffer(q->rect());
-    HIViewSetZOrder(qt_mac_nativeview_for(q), kHIViewZOrderBelow, qt_mac_nativeview_for(w));
-    qt_event_request_window_change(q);
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-/*
-    Modifies the bounds for a widgets backing HIView during moves and resizes. Also updates the
-    widget, either by scrolling its contents or repainting, depending on the WA_StaticContents
-    flag
-*/
-static void qt_mac_update_widget_position(QWidget *q, QRect oldRect, QRect newRect)
-{
-    HIRect bounds = CGRectMake(newRect.x(), newRect.y(),
-                               newRect.width(), newRect.height());
-
-    const HIViewRef view = qt_mac_nativeview_for(q);
-    const bool isMove = (oldRect.topLeft() != newRect.topLeft());
-    const bool isResize = (oldRect.size() != newRect.size());
-
-//    qDebug() << oldRect << newRect << isMove << isResize << q->testAttribute(Qt::WA_OpaquePaintEvent) << q->testAttribute(Qt::WA_StaticContents);
-    QWidgetPrivate *qd = qt_widget_private(q);
-
-    // Perform a normal (complete repaint) update in some cases:
-    if (
-        // always repaint on move.
-        (isMove) ||
-
-        // limited update on resize requires WA_StaticContents.
-        (isResize && q->testAttribute(Qt::WA_StaticContents) == false) ||
-
-        // one of the rects are invalid
-        (oldRect.isValid() == false || newRect.isValid() == false)  ||
-
-        // the position update is a part of a drag-and-drop operation
-        QDragManager::self()->object ||
-
-        // we are on Panther (no HIViewSetNeedsDisplayInRect)
-        QSysInfo::MacintoshVersion < QSysInfo::MV_10_4
-    ){
-        HIViewSetFrame(view, &bounds);
-        return;
-    }
-
-    const int dx = newRect.x() - oldRect.x();
-    const int dy = newRect.y() - oldRect.y();
-
-    if (isMove) {
-        // HIViewScrollRect silently fails if we try to scroll anything under the grow box.
-        // Check if there's one present within the widget rect, and if there is fall back
-        // to repainting the entire widget.
-        QWidget const * const parentWidget = q->parentWidget();
-        const HIViewRef parentView = qt_mac_nativeview_for(parentWidget);
-        HIViewRef nativeSizeGrip = 0;
-        if (q->testAttribute(Qt::WA_WState_Created))
-            HIViewFindByID(HIViewGetRoot(HIViewGetWindow(HIViewRef(q->winId()))), kHIViewWindowGrowBoxID, &nativeSizeGrip);
-        if (nativeSizeGrip) {
-            QWidget * const window = q->window();
-
-            const int sizeGripSize = 20;
-            const QRect oldWidgetRect = QRect(q->mapTo(window, QPoint(0, 0)), QSize(oldRect.width(), oldRect.height()));
-            const QRect newWidgetRect = QRect(q->mapTo(window, QPoint(0, 0)), QSize(newRect.width(), newRect.height()));
-            const QRect sizeGripRect = QRect(window->rect().bottomRight() - QPoint(sizeGripSize, sizeGripSize),
-                                             window->rect().bottomRight());
-
-            if (sizeGripRect.intersects(oldWidgetRect) || sizeGripRect.intersects(newWidgetRect)) {
-                HIViewSetFrame(view, &bounds);
-                return;
-            }
-        }
-
-        // Don't scroll anything outside the parent widget rect.
-        const QRect scrollRect = (oldRect | newRect) & parentWidget->rect();
-        const HIRect scrollBounds =
-            CGRectMake(scrollRect.x(), scrollRect.y(), scrollRect.width(), scrollRect.height());
-
-        // We cannot scroll when the widget has a mask as that would
-        // scroll the masked out areas too
-        if (qd->extra && qd->extra->hasMask) {
-            HIViewMoveBy(view, dx, dy);
-            return;
-        }
-
-        OSStatus err = HIViewScrollRect(parentView, &scrollBounds, dx, dy);
-        if (err != noErr) {
-            HIViewSetNeedsDisplay(view, true);
-            qWarning("QWidget: Internal error (%s:%d)", __FILE__, __LINE__);
-        }
-    }
-    // Set the view bounds with drawing disabled to prevent repaints.
-    HIViewSetDrawingEnabled(view, false);
-    HIViewSetFrame(view, &bounds);
-    HIViewSetDrawingEnabled(view, true);
-
-    // Update any newly exposed areas due to resizing.
-    const int startx = oldRect.width();
-    const int stopx = newRect.width();
-    const int starty = oldRect.height();
-    const int stopy = newRect.height();
-
-    const HIRect verticalSlice = CGRectMake(startx, 0, stopx , stopy);
-    HIViewSetNeedsDisplayInRect(view, &verticalSlice, true);
-    const HIRect horizontalSlice = CGRectMake(0, starty, startx, stopy);
-    HIViewSetNeedsDisplayInRect(view, &horizontalSlice, true);
-}
-#endif
-
-/*
-  Helper function for non-toplevel widgets. Helps to map Qt's 32bit
-  coordinate system to OS X's 16bit coordinate system.
-
-  Sets the geometry of the widget to data.crect, but clipped to sizes
-  that OS X can handle. Unmaps widgets that are completely outside the
-  valid range.
-
-  Maintains data.wrect, which is the geometry of the OS X widget,
-  measured in this widget's coordinate system.
-
-  if the parent is not clipped, parentWRect is empty, otherwise
-  parentWRect is the geometry of the parent's OS X rect, measured in
-  parent's coord sys
-*/
-void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &oldRect)
-{
-    Q_Q(QWidget);
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
-    if (!q->internalWinId() && QApplicationPrivate::graphics_system != 0) {
-        // We have no view to move, and no paint engine that
-        // we can update dirty regions on. So just return:
-        return;
-    }
-
-    QMacCocoaAutoReleasePool pool;
-
-    /*
-      There are up to four different coordinate systems here:
-      Qt coordinate system for this widget.
-      X coordinate system for this widget (relative to wrect).
-      Qt coordinate system for parent
-      X coordinate system for parent (relative to parent's wrect).
-    */
-
-    // wrect is the same as crect, except that it is
-    // clipped to fit inside parent (and screen):
-    QRect wrect;
-
-    // wrectInParentCoordSys will be the same as wrect, except that it is
-    // originated in q's parent rather than q itself. It starts out in
-    // parent's Qt coord system, and ends up in parent's coordinate system:
-    QRect wrectInParentCoordSys = data.crect;
-
-    // If q's parent has been clipped, parentWRect will
-    // be filled with the parents clipped crect:
-    QRect parentWRect;
-
-    // Embedded have different meaning on each platform, and on
-    // Mac, it means that q is a QMacNativeWidget.
-    bool isEmbeddedWindow = (q->isWindow() && topData()->embedded);
-#ifdef QT_MAC_USE_COCOA
-    NSView *nsview = qt_mac_nativeview_for(q);
-#endif
-    if (!isEmbeddedWindow) {
-        parentWRect = q->parentWidget()->data->wrect;
-    } else {
-        // INVARIANT: q's parent view is not owned by Qt. So we need to
-        // do some extra calls to get the clipped rect of the parent view:
-#ifndef QT_MAC_USE_COCOA
-        HIViewRef parentView = HIViewGetSuperview(qt_mac_nativeview_for(q));
-#else
-        NSView *parentView = [qt_mac_nativeview_for(q) superview];
-#endif
-        if (parentView) {
-#ifndef QT_MAC_USE_COCOA
-            HIRect tmpRect;
-            HIViewGetFrame(parentView, &tmpRect);
-#else
-            NSRect tmpRect = [parentView frame];
-#endif
-            parentWRect = QRect(tmpRect.origin.x, tmpRect.origin.y,
-                                tmpRect.size.width, tmpRect.size.height);
-        } else {
-            const QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX);
-            parentWRect = wrectRange;
-        }
-    }
-
-    if (parentWRect.isValid()) {
-        // INVARIANT: q's parent has been clipped.
-        // So we fit our own wrects inside it:
-        if (!parentWRect.contains(wrectInParentCoordSys) && !isEmbeddedWindow) {
-            wrectInParentCoordSys &= parentWRect;
-            wrect = wrectInParentCoordSys;
-            // Make sure wrect is originated in q's coordinate system:
-            wrect.translate(-data.crect.topLeft());
-        }
-        // // Make sure wrectInParentCoordSys originated in q's parent coordinate system:
-        wrectInParentCoordSys.translate(-parentWRect.topLeft());
-    } else {
-        // INVARIANT: we dont know yet the clipping rect of q's parent.
-        // So we may or may not have to adjust our wrects:
-
-        if (data.wrect.isValid() && QRect(QPoint(),data.crect.size()).contains(data.wrect)) {
-            // This is where the main optimization is: we have an old wrect from an earlier
-            // setGeometry call, and the new crect is smaller than it. If the final wrect is
-            // also inside the old wrect, we can just move q and its children to the new
-            // location without any clipping:
-
-             // vrect will be the part of q that's will be visible inside
-             // q's parent. If it inside the old wrect, then we can just move:
-            QRect vrect = wrectInParentCoordSys & q->parentWidget()->rect();
-            vrect.translate(-data.crect.topLeft());
-
-            if (data.wrect.contains(vrect)) {
-                wrectInParentCoordSys = data.wrect;
-                wrectInParentCoordSys.translate(data.crect.topLeft());
-#ifndef QT_MAC_USE_COCOA
-                HIRect bounds = CGRectMake(wrectInParentCoordSys.x(), wrectInParentCoordSys.y(),
-                                           wrectInParentCoordSys.width(), wrectInParentCoordSys.height());
-                HIViewSetFrame(qt_mac_nativeview_for(q), &bounds);
-#else
-                if (nsview) {
-                    // INVARIANT: q is native. Set view frame:
-                    NSRect bounds = NSMakeRect(wrectInParentCoordSys.x(), wrectInParentCoordSys.y(),
-                        wrectInParentCoordSys.width(), wrectInParentCoordSys.height());
-                        [nsview setFrame:bounds];
-                } else {
-                    // INVARIANT: q is alien. Repaint wrect instead (includes old and new wrect):
-                    QWidget *parent = q->parentWidget();
-                    QPoint globalPosWRect = parent->mapToGlobal(data.wrect.topLeft());
-
-                    QWidget *nativeParent = q->nativeParentWidget();
-                    QRect dirtyWRect = QRect(nativeParent->mapFromGlobal(globalPosWRect), data.wrect.size());
-
-                    nativeParent->update(dirtyWRect);
-                }
-#endif
-                if (q->testAttribute(Qt::WA_OutsideWSRange)) {
-                    q->setAttribute(Qt::WA_OutsideWSRange, false);
-                    if (!dontShow) {
-                        q->setAttribute(Qt::WA_Mapped);
-#ifndef QT_MAC_USE_COCOA
-                        HIViewSetVisible(qt_mac_nativeview_for(q), true);
-#else
-                        // If q is Alien, the following call does nothing:
-                        [nsview setHidden:NO];
-#endif
-                    }
-                }
-                return;
-            }
-        }
-
-#ifndef QT_MAC_USE_COCOA
-        const QRect validRange(-XCOORD_MAX,-XCOORD_MAX, 2*XCOORD_MAX, 2*XCOORD_MAX);
-        if (!validRange.contains(wrectInParentCoordSys)) {
-            // We're too big, and must clip:
-            QPoint screenOffset(0, 0); // offset of the part being on screen
-            const QWidget *parentWidget = q->parentWidget();
-            while (parentWidget && !parentWidget->isWindow()) {
-                screenOffset -= parentWidget->data->crect.topLeft();
-                parentWidget = parentWidget->parentWidget();
-            }
-            QRect cropRect(screenOffset.x() - WRECT_MAX,
-                           screenOffset.y() - WRECT_MAX,
-                           2*WRECT_MAX,
-                           2*WRECT_MAX);
-
-            wrectInParentCoordSys &=cropRect;
-            wrect = wrectInParentCoordSys;
-            wrect.translate(-data.crect.topLeft());
-        }
-#endif //QT_MAC_USE_COCOA
-    }
-
-    // unmap if we are outside the valid window system coord system
-    bool outsideRange = !wrectInParentCoordSys.isValid();
-    bool mapWindow = false;
-    if (q->testAttribute(Qt::WA_OutsideWSRange) != outsideRange) {
-        q->setAttribute(Qt::WA_OutsideWSRange, outsideRange);
-        if (outsideRange) {
-#ifndef QT_MAC_USE_COCOA
-            HIViewSetVisible(qt_mac_nativeview_for(q), false);
-#else
-            // If q is Alien, the following call does nothing:
-            [nsview setHidden:YES];
-#endif
-            q->setAttribute(Qt::WA_Mapped, false);
-        } else if (!q->isHidden()) {
-            mapWindow = true;
-        }
-    }
-
-    if (outsideRange)
-        return;
-
-    // Store the new clipped rect:
-    bool jump = (data.wrect != wrect);
-    data.wrect = wrect;
-
-    // and now recursively for all children...
-    // ### can be optimized
-    for (int i = 0; i < children.size(); ++i) {
-        QObject *object = children.at(i);
-        if (object->isWidgetType()) {
-            QWidget *w = static_cast<QWidget *>(object);
-            if (!w->isWindow() && w->testAttribute(Qt::WA_WState_Created))
-                w->d_func()->setWSGeometry();
-        }
-    }
-
-#ifndef QT_MAC_USE_COCOA
-    // Move the actual HIView:
-    qt_mac_update_widget_position(q, oldRect, wrectInParentCoordSys);
-    if (jump)
-        q->update();
-#else
-    if (nsview) {
-        // INVARIANT: q is native. Move the actual NSView:
-        NSRect bounds = NSMakeRect(
-            wrectInParentCoordSys.x(), wrectInParentCoordSys.y(),
-            wrectInParentCoordSys.width(), wrectInParentCoordSys.height());
-        [nsview setFrame:bounds];
-        if (jump)
-            q->update();
-    } else if (QApplicationPrivate::graphics_system == 0){
-        // INVARIANT: q is alien and we use native paint engine.
-        // Schedule updates where q is moved from and to:
-        const QWidget *parent = q->parentWidget();
-        const QPoint globalPosOldWRect = parent->mapToGlobal(oldRect.topLeft());
-        const QPoint globalPosNewWRect = parent->mapToGlobal(wrectInParentCoordSys.topLeft());
-
-        QWidget *nativeParent = q->nativeParentWidget();
-        const QRegion dirtyOldWRect = QRect(nativeParent->mapFromGlobal(globalPosOldWRect), oldRect.size());
-        const QRegion dirtyNewWRect = QRect(nativeParent->mapFromGlobal(globalPosNewWRect), wrectInParentCoordSys.size());
-
-        const bool sizeUnchanged = oldRect.size() == wrectInParentCoordSys.size();
-        const bool posUnchanged = oldRect.topLeft() == wrectInParentCoordSys.topLeft();
-
-        // Resolve/minimize the region that needs to update:
-        if (sizeUnchanged && q->testAttribute(Qt::WA_OpaquePaintEvent)) {
-            // INVARIANT: q is opaque, and is only moved (not resized). So in theory we only
-            // need to blit pixels, and skip a repaint. But we can only make this work if we
-            // had access to the backbuffer, so we need to update all:
-            nativeParent->update(dirtyOldWRect | dirtyNewWRect);
-        } else if (posUnchanged && q->testAttribute(Qt::WA_StaticContents)) {
-            // We only need to redraw exposed areas:
-            nativeParent->update(dirtyNewWRect - dirtyOldWRect);
-        } else {
-            nativeParent->update(dirtyOldWRect | dirtyNewWRect);
-        }
-    }
-#endif
-
-    if (mapWindow && !dontShow) {
-        q->setAttribute(Qt::WA_Mapped);
-#ifndef QT_MAC_USE_COCOA
-        HIViewSetVisible(qt_mac_nativeview_for(q), true);
-#else
-        // If q is Alien, the following call does nothing:
-        [nsview setHidden:NO];
-#endif
-    }
-}
-
-void QWidgetPrivate::adjustWithinMaxAndMinSize(int &w, int &h)
-{
-    if (QWExtra *extra = extraData()) {
-        w = qMin(w, extra->maxw);
-        h = qMin(h, extra->maxh);
-        w = qMax(w, extra->minw);
-        h = qMax(h, extra->minh);
-
-        // Deal with size increment
-        if (QTLWExtra *top = topData()) {
-            if(top->incw) {
-                w = w/top->incw;
-                w *= top->incw;
-            }
-            if(top->inch) {
-                h = h/top->inch;
-                h *= top->inch;
-            }
-        }
-    }
-
-    if (isRealWindow()) {
-        w = qMax(0, w);
-        h = qMax(0, h);
-    }
-}
-
-void QWidgetPrivate::applyMaxAndMinSizeOnWindow()
-{
-    Q_Q(QWidget);
-    QMacCocoaAutoReleasePool pool;
-
-    const float max_f(20000);
-#ifndef QT_MAC_USE_COCOA
-#define SF(x) ((x > max_f) ? max_f : x)
-    HISize max = CGSizeMake(SF(extra->maxw), SF(extra->maxh));
-    HISize min = CGSizeMake(SF(extra->minw), SF(extra->minh));
-#undef SF
-    SetWindowResizeLimits(qt_mac_window_for(q), &min, &max);
-#else
-#define SF(x) ((x > max_f) ? max_f : x)
-    NSSize max = NSMakeSize(SF(extra->maxw), SF(extra->maxh));
-    NSSize min = NSMakeSize(SF(extra->minw), SF(extra->minh));
-#undef SF
-    [qt_mac_window_for(q) setContentMinSize:min];
-    [qt_mac_window_for(q) setContentMaxSize:max];
-#endif
-}
-
-void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
-{
-    Q_Q(QWidget);
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
-    if(q->windowType() == Qt::Desktop)
-        return;
-
-    QMacCocoaAutoReleasePool pool;
-    bool realWindow = isRealWindow();
-
-    if (realWindow && !q->testAttribute(Qt::WA_DontShowOnScreen)){
-        adjustWithinMaxAndMinSize(w, h);
-#ifndef QT_MAC_USE_COCOA
-        if (w != 0 && h != 0) {
-            topData()->isSetGeometry = 1;
-            topData()->isMove = isMove;
-            Rect r; SetRect(&r, x, y, x + w, y + h);
-            SetWindowBounds(qt_mac_window_for(q), kWindowContentRgn, &r);
-            topData()->isSetGeometry = 0;
-        } else {
-            setGeometry_sys_helper(x, y, w, h, isMove);
-        }
-#else
-        if (!isMove && !q->testAttribute(Qt::WA_Moved) && !q->isVisible()) {
-            // INVARIANT: The location of the window has not yet been set. The default will
-            // instead be to center it on the desktop, or over the parent, if any. Since we now
-            // resize the window, we need to adjust the top left position to keep the window
-            // centeralized. And we need to to this now (and before show) in case the positioning
-            // of other windows (e.g. sub-windows) depend on this position:
-            if (QWidget *p = q->parentWidget()) {
-                x = p->geometry().center().x() - (w / 2);
-                y = p->geometry().center().y() - (h / 2);
-            } else {
-                QRect availGeo = QApplication::desktop()->availableGeometry(q);
-                x = availGeo.center().x() - (w / 2);
-                y = availGeo.center().y() - (h / 2);
-            }
-        }
-
-        QSize  olds = q->size();
-        const bool isResize = (olds != QSize(w, h));
-        NSWindow *window = qt_mac_window_for(q);
-        const QRect &fStrut = frameStrut();
-        const QRect frameRect(QPoint(x - fStrut.left(), y - fStrut.top()),
-                              QSize(fStrut.left() + fStrut.right() + w,
-                                    fStrut.top() + fStrut.bottom() + h));
-        NSRect cocoaFrameRect = NSMakeRect(frameRect.x(), flipYCoordinate(frameRect.bottom() + 1),
-                                           frameRect.width(), frameRect.height());
-        // The setFrame call will trigger a 'windowDidResize' notification for the corresponding
-        // NSWindow. The pending flag is set, so that the resize event can be send as non-spontaneous.
-        if (isResize)
-            q->setAttribute(Qt::WA_PendingResizeEvent);
-        QPoint currTopLeft = data.crect.topLeft();
-        if (currTopLeft.x() == x && currTopLeft.y() == y
-                && cocoaFrameRect.size.width != 0
-                && cocoaFrameRect.size.height != 0) {
-            [window setFrame:cocoaFrameRect display:realWindow];
-        } else {
-            // The window is moved and resized (or resized to zero).
-            // Since Cocoa usually only sends us a resize callback after
-            // setting a window frame, we issue an explicit move as
-            // well. To stop Cocoa from optimize away the move (since the move
-            // would have the same origin as the setFrame call) we shift the
-            // window back and forth inbetween.
-            cocoaFrameRect.origin.y += 1;
-            [window setFrame:cocoaFrameRect display:realWindow];
-            cocoaFrameRect.origin.y -= 1;
-            [window setFrameOrigin:cocoaFrameRect.origin];
-        }
-#endif
-    } else {
-        setGeometry_sys_helper(x, y, w, h, isMove);
-    }
-
-    topLevelAt_cache = 0;
-}
-
-void QWidgetPrivate::setGeometry_sys_helper(int x, int y, int w, int h, bool isMove)
-{
-    Q_Q(QWidget);
-    bool realWindow = isRealWindow();
-
-    QPoint oldp = q->pos();
-    QSize  olds = q->size();
-    // Apply size restrictions, applicable for Windows & Widgets.
-    if (QWExtra *extra = extraData()) {
-        w = qBound(extra->minw, w, extra->maxw);
-        h = qBound(extra->minh, h, extra->maxh);
-    }
-    const bool isResize = (olds != QSize(w, h));
-
-    if (!realWindow && !isResize && QPoint(x, y) == oldp)
-        return;
-
-    if (isResize)
-        data.window_state = data.window_state & ~Qt::WindowMaximized;
-
-    const bool visible = q->isVisible();
-    data.crect = QRect(x, y, w, h);
-
-    if (realWindow) {
-        adjustWithinMaxAndMinSize(w, h);
-        qt_mac_update_sizer(q);
-
-#ifndef QT_MAC_USE_COCOA
-        if (q->windowFlags() & Qt::WindowMaximizeButtonHint) {
-            OSWindowRef window = qt_mac_window_for(q);
-            if (extra->maxw && extra->maxh && extra->maxw == extra->minw
-                    && extra->maxh == extra->minh) {
-                ChangeWindowAttributes(window, kWindowNoAttributes, kWindowFullZoomAttribute);
-            } else {
-                ChangeWindowAttributes(window, kWindowFullZoomAttribute, kWindowNoAttributes);
-            }
-        }
-        HIRect bounds = CGRectMake(0, 0, w, h);
-        HIViewSetFrame(qt_mac_nativeview_for(q), &bounds);
-#else
-        [qt_mac_nativeview_for(q) setFrame:NSMakeRect(0, 0, w, h)];
-#endif
-    } else {
-        const QRect oldRect(oldp, olds);
-        if (!isResize && QApplicationPrivate::graphics_system)
-            moveRect(oldRect, x - oldp.x(), y - oldp.y());
-
-        setWSGeometry(false, oldRect);
-
-        if (isResize && q->parentWidget() && QApplicationPrivate::graphics_system)
-            invalidateBuffer_resizeHelper(oldp, olds);
-    }
-
-    if(isMove || isResize) {
-        if(!visible) {
-            if(isMove && q->pos() != oldp)
-                q->setAttribute(Qt::WA_PendingMoveEvent, true);
-            if(isResize)
-                q->setAttribute(Qt::WA_PendingResizeEvent, true);
-        } else {
-            if(isResize) { //send the resize event..
-                QResizeEvent e(q->size(), olds);
-                QApplication::sendEvent(q, &e);
-            }
-            if(isMove && q->pos() != oldp) { //send the move event..
-                QMoveEvent e(q->pos(), oldp);
-                QApplication::sendEvent(q, &e);
-            }
-        }
-    }
-    qt_event_request_window_change(q);
-}
-
-void QWidgetPrivate::setConstraints_sys()
-{
-    updateMaximizeButton_sys();
-    applyMaxAndMinSizeOnWindow();
-}
-
-void QWidgetPrivate::updateMaximizeButton_sys()
-{
-    Q_Q(QWidget);
-    if (q->data->window_flags & Qt::CustomizeWindowHint)
-        return;
-
-    OSWindowRef window = qt_mac_window_for(q);
-    QTLWExtra * tlwExtra = topData();
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    NSButton *maximizeButton = [window standardWindowButton:NSWindowZoomButton];
-#endif
-    if (extra->maxw && extra->maxh
-        && extra->maxw == extra->minw
-        && extra->maxh == extra->minh) {
-        // The window has a fixed size, so gray out the maximize button:
-        if (!tlwExtra->savedWindowAttributesFromMaximized) {
-#ifndef QT_MAC_USE_COCOA
-            GetWindowAttributes(window,
-                                (WindowAttributes*)&extra->topextra->savedWindowAttributesFromMaximized);
-
-#else
-            tlwExtra->savedWindowAttributesFromMaximized = (![maximizeButton isHidden] && [maximizeButton isEnabled]);
-#endif
-        }
-#ifndef QT_MAC_USE_COCOA
-        ChangeWindowAttributes(window, kWindowNoAttributes, kWindowFullZoomAttribute);
-#else
-       [maximizeButton setEnabled:NO];
-#endif
-
-
-    } else {
-        if (tlwExtra->savedWindowAttributesFromMaximized) {
-#ifndef QT_MAC_USE_COCOA
-            ChangeWindowAttributes(window,
-                                   extra->topextra->savedWindowAttributesFromMaximized,
-                                   kWindowNoAttributes);
-#else
-            [maximizeButton setEnabled:YES];
-#endif
-            tlwExtra->savedWindowAttributesFromMaximized = 0;
-        }
-    }
-
-
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy)
-{
-    if (QApplicationPrivate::graphics_system && !paintOnScreen()) {
-        // INVARIANT: Alien paint engine
-        scrollChildren(dx, dy);
-        scrollRect(q_func()->rect(), dx, dy);
-    } else {
-        scroll_sys(dx, dy, QRect());
-    }
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &qscrollRect)
-{
-    if (QMacScrollOptimization::delayScroll(this, dx, dy, qscrollRect))
-        return;
-
-    Q_Q(QWidget);
-    if (QApplicationPrivate::graphics_system && !paintOnScreen()) {
-        // INVARIANT: Alien paint engine
-        scrollRect(qscrollRect, dx, dy);
-        return;
-    }
-
-    static int accelEnv = -1;
-    if (accelEnv == -1) {
-        accelEnv = qgetenv("QT_NO_FAST_SCROLL").toInt() == 0;
-    }
-
-    // Scroll the whole widget if qscrollRect is not valid:
-    QRect validScrollRect = qscrollRect.isValid() ? qscrollRect : q->rect();
-
-    // If q is overlapped by other widgets, we cannot just blit pixels since
-    // this will move overlapping widgets as well. In case we just update:
-    const bool overlapped = isOverlapped(validScrollRect.translated(data.crect.topLeft()));
-    const bool accelerateScroll = accelEnv && isOpaque && !overlapped;
-    const bool isAlien = (q->internalWinId() == 0);
-
-    // If qscrollRect is valid, we are _not_ supposed to scroll q's children (as documented).
-    // But we do scroll children (and the whole of q) if qscrollRect is invalid. This case is
-    // documented as undefined, but we exploit it to help factor our code into one function.
-    const bool scrollChildren = !qscrollRect.isValid();
-
-    if (!q->updatesEnabled()) {
-        // We are told not to update anything on q at this point. So unless
-        // we are supposed to scroll children, we bail out early:
-        if (!scrollChildren || q->children().isEmpty())
-            return;
-    }
-
-    if (!accelerateScroll) {
-        if (overlapped) {
-            QRegion region(validScrollRect);
-            subtractOpaqueSiblings(region);
-            update_sys(region);
-        }else {
-            update_sys(qscrollRect);
-        }
-    }
-
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-#else
-    Q_UNUSED(isAlien);
-    // We're not sure what the following call is supposed to achive
-    // but until we see what it breaks, we don't bring it into the
-    // Cocoa port:
-    qt_event_request_window_change(q);
-#endif
-
-    // First move all native children. Alien children will indirectly be
-    // moved when the parent is scrolled. All directly or indirectly moved
-    // children will receive a move event before the function call returns.
-    QWidgetList movedChildren;
-    const QPoint scrollDelta(dx, dy);
-    if (scrollChildren) {
-        QObjectList children = q->children();
-
-        for (int i=0; i<children.size(); i++) {
-            QObject *obj = children.at(i);
-            if (QWidget *w = qobject_cast<QWidget*>(obj)) {
-                if (!w->isWindow()) {
-                    w->data->crect = QRect(w->pos() + scrollDelta, w->size());
-#ifndef QT_MAC_USE_COCOA
-                    if (w->testAttribute(Qt::WA_WState_Created)) {
-                        HIRect bounds = CGRectMake(w->data->crect.x(), w->data->crect.y(),
-                                                   w->data->crect.width(), w->data->crect.height());
-                        HIViewRef hiview = qt_mac_nativeview_for(w);
-                        const bool opaque = q->testAttribute(Qt::WA_OpaquePaintEvent);
-
-                        if (opaque)
-                            HIViewSetDrawingEnabled(hiview,  false);
-                        HIViewSetFrame(hiview, &bounds);
-                        if (opaque)
-                            HIViewSetDrawingEnabled(hiview,  true);
-                    }
-#else
-                    if (NSView *view = qt_mac_nativeview_for(w)) {
-                        // INVARIANT: w is not alien
-                        [view setFrame:NSMakeRect(
-                            w->data->crect.x(), w->data->crect.y(),
-                            w->data->crect.width(), w->data->crect.height())];
-                    }
-#endif
-                    movedChildren.append(w);
-                }
-            }
-        }
-    }
-
-    if (q->testAttribute(Qt::WA_WState_Created) && q->isVisible()) {
-        // Scroll q itself according to the qscrollRect, and
-        // call update on any exposed areas so that they get redrawn:
-
-#ifndef QT_MAC_USE_COCOA
-        OSViewRef view = qt_mac_nativeview_for(q);
-        HIRect scrollrect = CGRectMake(qscrollRect.x(), qscrollRect.y(), qscrollRect.width(), qscrollRect.height());
-        OSStatus err = _HIViewScrollRectWithOptions(view, qscrollRect.isValid() ? &scrollrect : 0, dx, dy, kHIViewScrollRectAdjustInvalid);
-        if (err) {
-           // The only parameter that can go wrong, is the rect.
-           qWarning("QWidget::scroll: Your rectangle was too big for the widget, clipping rect");
-           scrollrect = CGRectMake(qMax(qscrollRect.x(), 0), qMax(qscrollRect.y(), 0),
-                                   qMin(qscrollRect.width(), q->width()), qMin(qscrollRect.height(), q->height()));
-           _HIViewScrollRectWithOptions(view, qscrollRect.isValid() ? &scrollrect : 0, dx, dy, kHIViewScrollRectAdjustInvalid);
-        }
-#else
-
-        QWidget *nativeWidget = isAlien ? q->nativeParentWidget() : q;
-        if (!nativeWidget)
-            return;
-        OSViewRef view = qt_mac_nativeview_for(nativeWidget);
-        if (!view)
-            return;
-
-        // Calculate the rectangles that needs to be redrawn
-        // after the scroll. This will be source rect minus destination rect:
-        QRect deltaXRect;
-        if (dx != 0) {
-            deltaXRect.setY(validScrollRect.y());
-            deltaXRect.setHeight(validScrollRect.height());
-            if (dx > 0) {
-                deltaXRect.setX(validScrollRect.x());
-                deltaXRect.setWidth(dx);
-            } else {
-                deltaXRect.setX(validScrollRect.x() + validScrollRect.width() + dx);
-                deltaXRect.setWidth(-dx);
-            }
-        }
-
-        QRect deltaYRect;
-        if (dy != 0) {
-            deltaYRect.setX(validScrollRect.x());
-            deltaYRect.setWidth(validScrollRect.width());
-            if (dy > 0) {
-                deltaYRect.setY(validScrollRect.y());
-                deltaYRect.setHeight(dy);
-           } else {
-                deltaYRect.setY(validScrollRect.y() + validScrollRect.height() + dy);
-                deltaYRect.setHeight(-dy);
-            }
-        }
-
-        if (isAlien) {
-            // Adjust the scroll rect to the location as seen from the native parent:
-            QPoint scrollTopLeftInsideNative = nativeWidget->mapFromGlobal(q->mapToGlobal(validScrollRect.topLeft()));
-            validScrollRect.moveTo(scrollTopLeftInsideNative);
-        }
-
-        // Make the pixel copy rect within the validScrollRect bounds:
-        NSRect nsscrollRect = NSMakeRect(
-            validScrollRect.x() + (dx < 0 ? -dx : 0),
-            validScrollRect.y() + (dy < 0 ? -dy : 0),
-            validScrollRect.width() + (dx > 0 ? -dx : 0),
-            validScrollRect.height() + (dy > 0 ? -dy : 0));
-
-        NSSize deltaSize = NSMakeSize(dx, dy);
-        [view scrollRect:nsscrollRect by:deltaSize];
-
-        // Some areas inside the scroll rect might have been marked as dirty from before, which
-        // means that they are scheduled to be redrawn. But as we now scroll, those dirty rects
-        // should also move along to ensure that q receives repaints on the correct places.
-        // Since some of the dirty rects might lay outside, or only intersect with, the scroll
-        // rect, the old calls to setNeedsDisplay still makes sense.
-        // NB: Using [view translateRectsNeedingDisplayInRect:nsscrollRect by:deltaSize] have
-        // so far not been proven fruitful to solve this problem.
-        const QVector<QRect> &dirtyRectsToScroll = dirtyOnWidget.rects();
-        for (int i=0; i<dirtyRectsToScroll.size(); ++i) {
-            QRect qdirtyRect = dirtyRectsToScroll[i];
-            qdirtyRect.translate(dx, dy);
-            update_sys(qdirtyRect);
-        }
-
-        // Update newly exposed areas. This will generate new dirty areas on
-        // q, and therefore, we do it after updating the old dirty rects above:
-        if (dx != 0)
-            update_sys(deltaXRect);
-        if (dy != 0)
-            update_sys(deltaYRect);
-
-#endif // QT_MAC_USE_COCOA
-    }
-
-    for (int i=0; i<movedChildren.size(); i++) {
-        QWidget *w = movedChildren.at(i);
-        QMoveEvent e(w->pos(), w->pos() - scrollDelta);
-        QApplication::sendEvent(w, &e);
-    }
-}
-
-int QWidget::metric(PaintDeviceMetric m) const
-{
-    switch(m) {
-    case PdmHeightMM:
-        return qRound(metric(PdmHeight) * 25.4 / qreal(metric(PdmDpiY)));
-    case PdmWidthMM:
-        return qRound(metric(PdmWidth) * 25.4 / qreal(metric(PdmDpiX)));
-    case PdmHeight:
-    case PdmWidth:
-#ifndef QT_MAC_USE_COCOA
-        { HIRect rect;
-        HIViewGetFrame(qt_mac_nativeview_for(this), &rect);
-        if(m == PdmWidth)
-            return (int)rect.size.width;
-        return (int)rect.size.height; }
-#else
-        if (m == PdmWidth)
-            return data->crect.width();
-        else
-            return data->crect.height();
-#endif
-    case PdmDepth:
-        return 32;
-    case PdmNumColors:
-        return INT_MAX;
-    case PdmDpiX:
-    case PdmPhysicalDpiX: {
-        Q_D(const QWidget);
-        if (d->extra && d->extra->customDpiX)
-            return d->extra->customDpiX;
-        else if (d->parent)
-            return static_cast<QWidget *>(d->parent)->metric(m);
-        extern float qt_mac_defaultDpi_x(); //qpaintdevice_mac.cpp
-        return int(qt_mac_defaultDpi_x()); }
-    case PdmDpiY:
-    case PdmPhysicalDpiY: {
-        Q_D(const QWidget);
-        if (d->extra && d->extra->customDpiY)
-            return d->extra->customDpiY;
-        else if (d->parent)
-            return static_cast<QWidget *>(d->parent)->metric(m);
-        extern float qt_mac_defaultDpi_y(); //qpaintdevice_mac.cpp
-        return int(qt_mac_defaultDpi_y()); }
-    default: //leave this so the compiler complains when new ones are added
-        qWarning("QWidget::metric: Unhandled parameter %d", m);
-        return QPaintDevice::metric(m);
-    }
-    return 0;
-}
-
-void QWidgetPrivate::createSysExtra()
-{
-#ifdef QT_MAC_USE_COCOA
-    extra->imageMask = 0;
-#endif
-}
-
-void QWidgetPrivate::deleteSysExtra()
-{
-#ifdef QT_MAC_USE_COCOA
-    if (extra->imageMask)
-        CFRelease(extra->imageMask);
-#endif
-}
-
-void QWidgetPrivate::createTLSysExtra()
-{
-    extra->topextra->resizer = 0;
-    extra->topextra->isSetGeometry = 0;
-    extra->topextra->isMove = 0;
-    extra->topextra->wattr = 0;
-    extra->topextra->wclass = 0;
-    extra->topextra->group = 0;
-    extra->topextra->windowIcon = 0;
-    extra->topextra->savedWindowAttributesFromMaximized = 0;
-}
-
-void QWidgetPrivate::deleteTLSysExtra()
-{
-#ifndef QT_MAC_USE_COCOA
-    if (extra->topextra->group) {
-        qt_mac_release_window_group(extra->topextra->group);
-        extra->topextra->group = 0;
-    }
-    if (extra->topextra->windowIcon) {
-        ReleaseIconRef(extra->topextra->windowIcon);
-        extra->topextra->windowIcon = 0;
-    }
-#endif
-}
-
-void QWidgetPrivate::updateFrameStrut()
-{
-    Q_Q(QWidget);
-
-    QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
-
-    that->data.fstrut_dirty = false;
-    QTLWExtra *top = that->topData();
-
-#ifdef QT_MAC_USE_COCOA
-    // 1 Get the window frame
-    OSWindowRef oswnd = qt_mac_window_for(q);
-    NSRect frameW = [oswnd frame];
-    // 2 Get the content frame - so now
-    NSRect frameC = [oswnd contentRectForFrameRect:frameW];
-    top->frameStrut.setCoords(frameC.origin.x - frameW.origin.x,
-                              (frameW.origin.y + frameW.size.height) - (frameC.origin.y + frameC.size.height),
-                              (frameW.origin.x + frameW.size.width) - (frameC.origin.x + frameC.size.width),
-                              frameC.origin.y - frameW.origin.y);
-#else
-    Rect window_r;
-    GetWindowStructureWidths(qt_mac_window_for(q), &window_r);
-    top->frameStrut.setCoords(window_r.left, window_r.top, window_r.right, window_r.bottom);
-#endif
-}
-
-void QWidgetPrivate::registerDropSite(bool on)
-{
-    Q_Q(QWidget);
-    if (!q->testAttribute(Qt::WA_WState_Created))
-        return;
-#ifndef QT_MAC_USE_COCOA
-    SetControlDragTrackingEnabled(qt_mac_nativeview_for(q), on);
-#else
-    NSWindow *win = qt_mac_window_for(q);
-    if (on) {
-        if ([win isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaWindow) class]])
-            [static_cast<QT_MANGLE_NAMESPACE(QCocoaWindow) *>(win) registerDragTypes];
-        else if ([win isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaPanel) class]])
-            [static_cast<QT_MANGLE_NAMESPACE(QCocoaPanel) *>(win) registerDragTypes];
-    }
-#endif
-}
-
-void QWidgetPrivate::registerTouchWindow(bool enable)
-{
-    Q_UNUSED(enable);
-#ifdef QT_MAC_USE_COCOA
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-    if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_6)
-        return;
-
-    Q_Q(QWidget);
-    if (enable == touchEventsEnabled)
-        return;
-
-    QT_MANGLE_NAMESPACE(QCocoaView) *view = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(qt_mac_effectiveview_for(q));
-    if (!view)
-        return;
-
-    if (enable) {
-        ++view->alienTouchCount;
-        if (view->alienTouchCount == 1) {
-            touchEventsEnabled = true;
-            [view setAcceptsTouchEvents:YES];
-        }
-    } else {
-        --view->alienTouchCount;
-        if (view->alienTouchCount == 0) {
-            touchEventsEnabled = false;
-            [view setAcceptsTouchEvents:NO];
-        }
-    }
-#endif
-#endif
-}
-
-void QWidgetPrivate::setMask_sys(const QRegion &region)
-{
-    Q_UNUSED(region);
-    Q_Q(QWidget);
-
-#ifndef QT_MAC_USE_COCOA
-    if (q->isWindow())
-        ReshapeCustomWindow(qt_mac_window_for(q));
-    else
-        HIViewReshapeStructure(qt_mac_nativeview_for(q));
-#else
-    if (!q->internalWinId())
-        return;
-
-    if (extra->mask.isEmpty()) {
-        extra->maskBits = QImage();
-        finishCocoaMaskSetup();
-    } else {
-        syncCocoaMask();
-    }
-
-    topLevelAt_cache = 0;
-#endif
-}
-
-void QWidgetPrivate::setWindowOpacity_sys(qreal level)
-{
-    Q_Q(QWidget);
-
-    if (!q->isWindow())
-        return;
-
-    level = qBound(0.0, level, 1.0);
-    topData()->opacity = (uchar)(level * 255);
-    if (!q->testAttribute(Qt::WA_WState_Created))
-        return;
-
-    OSWindowRef oswindow = qt_mac_window_for(q);
-#ifdef QT_MAC_USE_COCOA
-    [oswindow setAlphaValue:level];
-#else
-    SetWindowAlpha(oswindow, level);
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QWidgetPrivate::syncCocoaMask()
-{
-    Q_Q(QWidget);
-    if (!q->testAttribute(Qt::WA_WState_Created) || !extra)
-        return;
-
-    if (extra->hasMask) {
-        if(extra->maskBits.size() != q->size()) {
-            extra->maskBits = QImage(q->size(), QImage::Format_Mono);
-        }
-        extra->maskBits.fill(QColor(Qt::color1).rgba());
-        extra->maskBits.setColorCount(2);
-        extra->maskBits.setColor(0, QColor(Qt::color0).rgba());
-        extra->maskBits.setColor(1, QColor(Qt::color1).rgba());
-        QPainter painter(&extra->maskBits);
-        painter.setBrush(Qt::color1);
-        painter.setPen(Qt::NoPen);
-        painter.drawRects(extra->mask.rects());
-        painter.end();
-        finishCocoaMaskSetup();
-    }
-}
-
-void QWidgetPrivate::finishCocoaMaskSetup()
-{
-    Q_Q(QWidget);
-
-    if (!q->testAttribute(Qt::WA_WState_Created) || !extra)
-        return;
-
-    // Technically this is too late to release, because the data behind the image
-    // has already been released. But it's more tidy to do it here.
-    // If you are seeing a crash, consider doing a CFRelease before changing extra->maskBits.
-    if (extra->imageMask) {
-        CFRelease(extra->imageMask);
-        extra->imageMask = 0;
-    }
-
-    if (!extra->maskBits.isNull()) {
-        QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(0,
-                                                                       extra->maskBits.bits(),
-                                                                       extra->maskBits.byteCount(),
-                                                                       0); // shouldn't need to release.
-        CGFloat decode[2] = {1, 0};
-        extra->imageMask = CGImageMaskCreate(extra->maskBits.width(), extra->maskBits.height(),
-                                             1, 1, extra->maskBits.bytesPerLine(), dataProvider,
-                                             decode, false);
-    }
-    if (q->isWindow()) {
-        NSWindow *window = qt_mac_window_for(q);
-        [window setOpaque:(extra->imageMask == 0)];
-        [window invalidateShadow];
-    }
-    macSetNeedsDisplay(QRegion());
-}
-#endif
-
-struct QPaintEngineCleanupHandler
-{
-    inline QPaintEngineCleanupHandler() : engine(0) {}
-    inline ~QPaintEngineCleanupHandler() { delete engine; }
-    QPaintEngine *engine;
-};
-
-Q_GLOBAL_STATIC(QPaintEngineCleanupHandler, engineHandler)
-
-QPaintEngine *QWidget::paintEngine() const
-{
-    QPaintEngine *&pe = engineHandler()->engine;
-    if (!pe)
-        pe = new QCoreGraphicsPaintEngine();
-    if (pe->isActive()) {
-        return new QCoreGraphicsPaintEngine();
-    }
-    return pe;
-}
-
-void QWidgetPrivate::setModal_sys()
-{
-    Q_Q(QWidget);
-    if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow())
-        return;
-    const QWidget * const windowParent = q->window()->parentWidget();
-    const QWidget * const primaryWindow = windowParent ? windowParent->window() : 0;
-    OSWindowRef windowRef = qt_mac_window_for(q);
-
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    bool alreadySheet = [windowRef styleMask] & NSDocModalWindowMask;
-
-    if (windowParent && q->windowModality() == Qt::WindowModal){
-        // INVARIANT: Window should be window-modal (which implies a sheet).
-        if (!alreadySheet) {
-            // NB: the following call will call setModal_sys recursivly:
-            recreateMacWindow();
-            windowRef = qt_mac_window_for(q);
-        }
-        if ([windowRef isKindOfClass:[NSPanel class]]){
-            // If the primary window of the sheet parent is a child of a modal dialog,
-            // the sheet parent should not be modally shaddowed.
-            // This goes for the sheet as well:
-            OSWindowRef ref = primaryWindow ? qt_mac_window_for(primaryWindow) : 0;
-            bool isDialog = ref ? [ref isKindOfClass:[NSPanel class]] : false;
-            bool worksWhenModal = isDialog ? [static_cast<NSPanel *>(ref) worksWhenModal] : false;
-            if (worksWhenModal)
-                [static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
-        }
-    } else {
-        // INVARIANT: Window shold _not_ be window-modal (and as such, not a sheet).
-        if (alreadySheet){
-            // NB: the following call will call setModal_sys recursivly:
-            recreateMacWindow();
-            windowRef = qt_mac_window_for(q);
-        }
-        if (q->windowModality() == Qt::NonModal
-            && primaryWindow && primaryWindow->windowModality() == Qt::ApplicationModal) {
-            // INVARIANT: Our window has a parent that is application modal.
-            // This means that q is supposed to be on top of this window and
-            // not be modally shaddowed:
-            if ([windowRef isKindOfClass:[NSPanel class]])
-                [static_cast<NSPanel *>(windowRef) setWorksWhenModal:YES];
-        }
-    }
-
-#else
-    const bool primaryWindowModal = primaryWindow ? primaryWindow->testAttribute(Qt::WA_ShowModal) : false;
-    const bool modal = q->testAttribute(Qt::WA_ShowModal);
-
-    WindowClass old_wclass;
-    GetWindowClass(windowRef, &old_wclass);
-
-    if (modal || primaryWindowModal) {
-        if (q->windowModality() == Qt::WindowModal
-                || (primaryWindow && primaryWindow->windowModality() == Qt::WindowModal)){
-            // Window should be window-modal (which implies a sheet).
-            if (old_wclass != kSheetWindowClass){
-                // We cannot convert a created window to a sheet.
-                // So we recreate the window:
-                recreateMacWindow();
-                return;
-            }
-        } else {
-            // Window should be application-modal (which implies NOT using a sheet).
-            if (old_wclass == kSheetWindowClass){
-                // We cannot convert a sheet to a window.
-                // So we recreate the window:
-                recreateMacWindow();
-                return;
-            } else if (!(q->data->window_flags & Qt::CustomizeWindowHint)) {
-                if (old_wclass == kDocumentWindowClass || old_wclass == kFloatingWindowClass || old_wclass == kUtilityWindowClass){
-                    // Only change the class to kMovableModalWindowClass if the no explicit jewels
-                    // are set (kMovableModalWindowClass can't contain them), and the current window class
-                    // can be converted to modal (according to carbon doc). Mind the order of
-                    // HIWindowChangeClass and ChangeWindowAttributes.
-                    WindowGroupRef group = GetWindowGroup(windowRef);
-                    HIWindowChangeClass(windowRef, kMovableModalWindowClass);
-                    quint32 tmpWattr = kWindowCloseBoxAttribute | kWindowHorizontalZoomAttribute;
-                    ChangeWindowAttributes(windowRef, tmpWattr, kWindowNoAttributes);
-                    ChangeWindowAttributes(windowRef, kWindowNoAttributes, tmpWattr);
-                    // If the window belongs to a qt-created group, set that group once more:
-                    if (data.window_flags & Qt::WindowStaysOnTopHint
-                            || q->windowType() == Qt::Popup
-                            || q->windowType() == Qt::ToolTip)
-                        SetWindowGroup(windowRef, group);
-                }
-                // Popups are usually handled "special" and are never modal.
-                Qt::WindowType winType = q->windowType();
-                if (winType != Qt::Popup && winType != Qt::ToolTip)
-                    SetWindowModality(windowRef, kWindowModalityAppModal, 0);
-            }
-        }
-    } else if (windowRef) {
-        if (old_wclass == kSheetWindowClass){
-            // Converting a sheet to a window is complex. It's easier to recreate:
-            recreateMacWindow();
-            return;
-        }
-
-        SetWindowModality(windowRef, kWindowModalityNone, 0);
-       if (!(q->data->window_flags & Qt::CustomizeWindowHint)) {
-           if (q->window()->d_func()->topData()->wattr |= kWindowCloseBoxAttribute)
-               ChangeWindowAttributes(windowRef, kWindowCloseBoxAttribute, kWindowNoAttributes);
-           if (q->window()->d_func()->topData()->wattr |= kWindowHorizontalZoomAttribute)
-               ChangeWindowAttributes(windowRef, kWindowHorizontalZoomAttribute, kWindowNoAttributes);
-           if (q->window()->d_func()->topData()->wattr |= kWindowCollapseBoxAttribute)
-                ChangeWindowAttributes(windowRef, kWindowCollapseBoxAttribute, kWindowNoAttributes);
-       }
-
-        WindowClass newClass = q->window()->d_func()->topData()->wclass;
-        if (old_wclass != newClass && newClass != 0){
-            WindowGroupRef group = GetWindowGroup(windowRef);
-            HIWindowChangeClass(windowRef, newClass);
-            // If the window belongs to a qt-created group, set that group once more:
-            if (data.window_flags & Qt::WindowStaysOnTopHint
-                || q->windowType() == Qt::Popup
-                || q->windowType() == Qt::ToolTip)
-                SetWindowGroup(windowRef, group);
-        }
-    }
-
-    // Make sure that HIWindowChangeClass didn't remove drag support
-    // or reset the opaque size grip setting:
-    SetAutomaticControlDragTrackingEnabledForWindow(windowRef, true);
-    macUpdateOpaqueSizeGrip();
-#endif
-}
-
-void QWidgetPrivate::macUpdateHideOnSuspend()
-{
-    Q_Q(QWidget);
-    if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow() || q->windowType() != Qt::Tool)
-        return;
-#ifndef QT_MAC_USE_COCOA
-    if(q->testAttribute(Qt::WA_MacAlwaysShowToolWindow))
-        ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowHideOnSuspendAttribute);
-    else
-        ChangeWindowAttributes(qt_mac_window_for(q), kWindowHideOnSuspendAttribute, 0);
-#else
-    if(q->testAttribute(Qt::WA_MacAlwaysShowToolWindow))
-        [qt_mac_window_for(q) setHidesOnDeactivate:NO];
-    else
-        [qt_mac_window_for(q) setHidesOnDeactivate:YES];
-#endif
-}
-
-void QWidgetPrivate::macUpdateOpaqueSizeGrip()
-{
-    Q_Q(QWidget);
-
-    if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow())
-        return;
-
-#ifndef QT_MAC_USE_COCOA       // Growbox is always transparent on Cocoa. Can emulate with setting a QSizeGrip
-    HIViewRef growBox;
-    HIViewFindByID(HIViewGetRoot(qt_mac_window_for(q)), kHIViewWindowGrowBoxID, &growBox);
-    if (!growBox)
-        return;
-    HIGrowBoxViewSetTransparent(growBox, !q->testAttribute(Qt::WA_MacOpaqueSizeGrip));
-#endif
-}
-
-void QWidgetPrivate::macUpdateSizeAttribute()
-{
-    Q_Q(QWidget);
-    QEvent event(QEvent::MacSizeChange);
-    QApplication::sendEvent(q, &event);
-    for (int i = 0; i < children.size(); ++i) {
-        QWidget *w = qobject_cast<QWidget *>(children.at(i));
-        if (w && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
-              && !q->testAttribute(Qt::WA_MacMiniSize) // no attribute set? inherit from parent
-              && !w->testAttribute(Qt::WA_MacSmallSize)
-              && !w->testAttribute(Qt::WA_MacNormalSize))
-            w->d_func()->macUpdateSizeAttribute();
-    }
-    resolveFont();
-}
-
-void QWidgetPrivate::macUpdateIgnoreMouseEvents()
-{
-#ifndef QT_MAC_USE_COCOA  // This is handled inside the mouse handler on Cocoa.
-    Q_Q(QWidget);
-    if (!q->testAttribute(Qt::WA_WState_Created))
-        return;
-
-    if(q->isWindow())
-       {
-        if(q->testAttribute(Qt::WA_TransparentForMouseEvents))
-            ChangeWindowAttributes(qt_mac_window_for(q), kWindowIgnoreClicksAttribute, 0);
-        else
-            ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowIgnoreClicksAttribute);
-        ReshapeCustomWindow(qt_mac_window_for(q));
-    } else {
-#ifndef kHIViewFeatureIgnoresClicks
-#define kHIViewFeatureIgnoresClicks kHIViewIgnoresClicks
-#endif
-        if(q->testAttribute(Qt::WA_TransparentForMouseEvents))
-            HIViewChangeFeatures(qt_mac_nativeview_for(q), kHIViewFeatureIgnoresClicks, 0);
-        else
-            HIViewChangeFeatures(qt_mac_nativeview_for(q), 0, kHIViewFeatureIgnoresClicks);
-        HIViewReshapeStructure(qt_mac_nativeview_for(q));
-    }
-#endif
-}
-
-void QWidgetPrivate::macUpdateMetalAttribute()
-{
-    Q_Q(QWidget);
-    bool realWindow = isRealWindow();
-    if (!q->testAttribute(Qt::WA_WState_Created) || !realWindow)
-        return;
-
-    if (realWindow) {
-#ifdef QT_MAC_USE_COCOA
-        // Cocoa doesn't let us change the style mask once it's been changed
-        // So, that means we need to recreate the window.
-        OSWindowRef cocoaWindow = qt_mac_window_for(q);
-        if ([cocoaWindow styleMask] & NSTexturedBackgroundWindowMask)
-            return;
-        recreateMacWindow();
-#else
-        QMainWindowLayout *layout = qt_mainwindow_layout(qobject_cast<QMainWindow *>(q));
-        if (q->testAttribute(Qt::WA_MacBrushedMetal)) {
-            if (layout)
-                layout->updateHIToolBarStatus();
-            ChangeWindowAttributes(qt_mac_window_for(q), kWindowMetalAttribute, 0);
-            ChangeWindowAttributes(qt_mac_window_for(q), kWindowMetalNoContentSeparatorAttribute, 0);
-        } else {
-            ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowMetalNoContentSeparatorAttribute);
-            ChangeWindowAttributes(qt_mac_window_for(q), 0, kWindowMetalAttribute);
-            if (layout)
-                layout->updateHIToolBarStatus();
-        }
-#endif
-    }
-}
-
-void QWidgetPrivate::setEnabled_helper_sys(bool enable)
-{
-#ifdef QT_MAC_USE_COCOA
-    Q_Q(QWidget);
-    NSView *view = qt_mac_nativeview_for(q);
-    if ([view isKindOfClass:[NSControl class]])
-        [static_cast<NSControl *>(view) setEnabled:enable];
-#else
-    Q_UNUSED(enable);
-#endif
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/kernel/qwidget_win.cpp b/src/gui/kernel/qwidget_win.cpp
deleted file mode 100644 (file)
index cd608be..0000000
+++ /dev/null
@@ -1,2183 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qapplication.h"
-#include "qapplication_p.h"
-#include "qbitmap.h"
-#include "qcursor.h"
-#include "qdesktopwidget.h"
-#include "qevent.h"
-#include "qimage.h"
-#include "qlayout.h"
-#include "qpainter.h"
-#include "qstack.h"
-#include "qthread.h"
-#include "qt_windows.h"
-#include "qwidget.h"
-#include "qwidget_p.h"
-#include "qbackingstore_p.h"
-#include "qwindowsurface_raster_p.h"
-
-#include "qscrollbar.h"
-#include "qabstractscrollarea.h"
-#include <qabstractscrollarea_p.h>
-
-#include <qdebug.h>
-
-#include <qapplication_p.h>
-#include <qwininputcontext_p.h>
-#include <qpaintengine_raster_p.h>
-#include <qsystemlibrary_p.h>
-
-#if defined(Q_WS_WINCE)
-#include "qguifunctions_wince.h"
-QT_USE_NAMESPACE
-extern void qt_wince_maximize(QWidget *widget);                          //defined in qguifunctions_wince.cpp
-extern void qt_wince_unmaximize(QWidget *widget);                        //defined in qguifunctions_wince.cpp
-extern void qt_wince_minimize(HWND hwnd);                                //defined in qguifunctions_wince.cpp
-extern void qt_wince_full_screen(HWND hwnd, bool fullScreen, UINT swpf); //defined in qguifunctions_wince.cpp
-extern bool qt_wince_is_mobile();                                        //defined in qguifunctions_wince.cpp
-#endif
-
-typedef BOOL    (WINAPI *PtrSetLayeredWindowAttributes)(HWND hwnd, COLORREF crKey, BYTE bAlpha, DWORD dwFlags);
-static PtrSetLayeredWindowAttributes ptrSetLayeredWindowAttributes = 0;
-
-#ifndef QT_NO_DIRECTDRAW
-#include <ddraw.h>
-#include <qimage_p.h>
-static IDirectDraw *qt_ddraw_object;
-static IDirectDrawSurface *qt_ddraw_primary;
-#endif
-
-
-
-#if defined(QT_NON_COMMERCIAL)
-#include "qnc_win.h"
-#endif
-
-#if !defined(WS_EX_TOOLWINDOW)
-#define WS_EX_TOOLWINDOW 0x00000080
-#endif
-
-#if !defined(GWLP_WNDPROC)
-#define GWLP_WNDPROC GWL_WNDPROC
-#endif
-
-//#define TABLET_DEBUG
-#define PACKETDATA  (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE \
-                     | PK_ORIENTATION | PK_CURSOR | PK_Z)
-#define PACKETMODE  0
-#include <wintab.h>
-#include <pktdef.h>
-
-QT_BEGIN_NAMESPACE
-
-typedef HCTX        (API *PtrWTOpen)(HWND, LPLOGCONTEXT, BOOL);
-typedef BOOL        (API *PtrWTClose)(HCTX);
-typedef UINT        (API *PtrWTInfo)(UINT, UINT, LPVOID);
-typedef BOOL        (API *PtrWTEnable)(HCTX, BOOL);
-typedef BOOL        (API *PtrWTOverlap)(HCTX, BOOL);
-typedef int        (API *PtrWTPacketsGet)(HCTX, int, LPVOID);
-typedef BOOL        (API *PtrWTGet)(HCTX, LPLOGCONTEXT);
-typedef int     (API *PtrWTQueueSizeGet)(HCTX);
-typedef BOOL    (API *PtrWTQueueSizeSet)(HCTX, int);
-
-static PtrWTOpen ptrWTOpen = 0;
-static PtrWTClose ptrWTClose = 0;
-static PtrWTInfo ptrWTInfo = 0;
-static PtrWTQueueSizeGet ptrWTQueueSizeGet = 0;
-static PtrWTQueueSizeSet ptrWTQueueSizeSet = 0;
-#ifndef QT_NO_TABLETEVENT
-static void init_wintab_functions();
-static void qt_tablet_init();
-static void qt_tablet_cleanup();
-#endif // QT_NO_TABLETEVENT
-extern HCTX qt_tablet_context;
-extern bool qt_tablet_tilt_support;
-
-static QWidget *qt_tablet_widget = 0;
-QWidget* qt_get_tablet_widget()
-{
-    return qt_tablet_widget;
-}
-
-extern bool qt_is_gui_used;
-
-#ifndef QT_NO_TABLETEVENT
-static void init_wintab_functions()
-{
-#if defined(Q_OS_WINCE)
-    return;
-#else
-    if (!qt_is_gui_used)
-        return;
-    QSystemLibrary library(QLatin1String("wintab32"));
-    ptrWTOpen = (PtrWTOpen)library.resolve("WTOpenW");
-    ptrWTInfo = (PtrWTInfo)library.resolve("WTInfoW");
-    ptrWTClose = (PtrWTClose)library.resolve("WTClose");
-    ptrWTQueueSizeGet = (PtrWTQueueSizeGet)library.resolve("WTQueueSizeGet");
-    ptrWTQueueSizeSet = (PtrWTQueueSizeSet)library.resolve("WTQueueSizeSet");
-#endif // Q_OS_WINCE
-}
-
-static void qt_tablet_init()
-{
-    static bool firstTime = true;
-    if (!firstTime)
-        return;
-    firstTime = false;
-    qt_tablet_widget = new QWidget(0);
-    qt_tablet_widget->createWinId();
-    qt_tablet_widget->setObjectName(QLatin1String("Qt internal tablet widget"));
-    // We don't need this internal widget to appear in QApplication::topLevelWidgets()
-    if (QWidgetPrivate::allWidgets)
-        QWidgetPrivate::allWidgets->remove(qt_tablet_widget);
-    LOGCONTEXT lcMine;
-    qAddPostRoutine(qt_tablet_cleanup);
-    struct tagAXIS tpOri[3];
-    init_wintab_functions();
-    if (ptrWTInfo && ptrWTOpen && ptrWTQueueSizeGet && ptrWTQueueSizeSet) {
-        // make sure we have WinTab
-        if (!ptrWTInfo(0, 0, NULL)) {
-#ifdef TABLET_DEBUG
-            qWarning("QWidget: Wintab services not available");
-#endif
-            return;
-        }
-
-        // some tablets don't support tilt, check if it is possible,
-        qt_tablet_tilt_support = ptrWTInfo(WTI_DEVICES, DVC_ORIENTATION, &tpOri);
-        if (qt_tablet_tilt_support) {
-            // check for azimuth and altitude
-            qt_tablet_tilt_support = tpOri[0].axResolution && tpOri[1].axResolution;
-        }
-        // build our context from the default context
-        ptrWTInfo(WTI_DEFSYSCTX, 0, &lcMine);
-        // Go for the raw coordinates, the tablet event will return good stuff
-        lcMine.lcOptions |= CXO_MESSAGES | CXO_CSRMESSAGES;
-        lcMine.lcPktData = PACKETDATA;
-        lcMine.lcPktMode = PACKETMODE;
-        lcMine.lcMoveMask = PACKETDATA;
-        lcMine.lcOutOrgX = 0;
-        lcMine.lcOutExtX = lcMine.lcInExtX;
-        lcMine.lcOutOrgY = 0;
-        lcMine.lcOutExtY = -lcMine.lcInExtY;
-        qt_tablet_context = ptrWTOpen(qt_tablet_widget->winId(), &lcMine, true);
-#ifdef TABLET_DEBUG
-        qDebug("Tablet is %p", qt_tablet_context);
-#endif
-        if (!qt_tablet_context) {
-#ifdef TABLET_DEBUG
-            qWarning("QWidget: Failed to open the tablet");
-#endif
-            return;
-        }
-        // Set the size of the Packet Queue to the correct size...
-        int currSize = ptrWTQueueSizeGet(qt_tablet_context);
-        if (!ptrWTQueueSizeSet(qt_tablet_context, QT_TABLET_NPACKETQSIZE)) {
-            // Ideally one might want to use a smaller
-            // multiple, but for now, since we managed to destroy
-            // the existing Q with the previous call, set it back
-            // to the other size, which should work.  If not,
-            // there will be trouble.
-            if (!ptrWTQueueSizeSet(qt_tablet_context, currSize)) {
-                Q_ASSERT_X(0, "Qt::Internal", "There is no packet queue for"
-                         " the tablet. The tablet will not work");
-            }
-        }
-    }
-}
-
-static void qt_tablet_cleanup()
-{
-    if (ptrWTClose)
-        ptrWTClose(qt_tablet_context);
-    delete qt_tablet_widget;
-    qt_tablet_widget = 0;
-}
-#endif // QT_NO_TABLETEVENT
-
-const QString qt_reg_winclass(QWidget *w);                // defined in qapplication_win.cpp
-
-#ifndef QT_NO_DRAGANDDROP
-void            qt_olednd_unregister(QWidget* widget, QOleDropTarget *dst); // dnd_win
-QOleDropTarget* qt_olednd_register(QWidget* widget);
-#endif
-
-extern bool qt_nograb();
-extern HRGN qt_win_bitmapToRegion(const QBitmap& bitmap);
-
-static QWidget *mouseGrb    = 0;
-static QCursor *mouseGrbCur = 0;
-static QWidget *keyboardGrb = 0;
-static HHOOK   journalRec  = 0;
-
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
-
-#define XCOORD_MAX 16383
-#define WRECT_MAX 16383
-
-/*****************************************************************************
-  QWidget member functions
- *****************************************************************************/
-
-#ifndef Q_WS_WINCE
-void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow)
-{
-    Q_Q(QWidget);
-    static int sw = -1, sh = -1;
-
-    Qt::WindowType type = q->windowType();
-    Qt::WindowFlags flags = data.window_flags;
-
-    bool topLevel = (flags & Qt::Window);
-    bool popup = (type == Qt::Popup);
-    bool dialog = (type == Qt::Dialog
-                   || type == Qt::Sheet
-                   || (flags & Qt::MSWindowsFixedSizeDialogHint));
-    bool desktop = (type == Qt::Desktop);
-    bool tool = (type == Qt::Tool || type == Qt::Drawer);
-
-    HINSTANCE appinst  = qWinAppInst();
-    HWND parentw, destroyw = 0;
-    WId id = 0;
-
-    QString windowClassName = qt_reg_winclass(q);
-
-    if (!window)                                // always initialize
-        initializeWindow = true;
-
-    if (popup)
-        flags |= Qt::WindowStaysOnTopHint; // a popup stays on top
-
-    if (sw < 0) {                                // get the (primary) screen size
-        sw = GetSystemMetrics(SM_CXSCREEN);
-        sh = GetSystemMetrics(SM_CYSCREEN);
-    }
-
-    if (desktop && !q->testAttribute(Qt::WA_DontShowOnScreen)) {                                // desktop widget
-        popup = false;                                // force this flags off
-        data.crect.setRect(GetSystemMetrics(76 /* SM_XVIRTUALSCREEN  */), GetSystemMetrics(77 /* SM_YVIRTUALSCREEN  */),
-                           GetSystemMetrics(78 /* SM_CXVIRTUALSCREEN */), GetSystemMetrics(79 /* SM_CYVIRTUALSCREEN */));
-    }
-
-    parentw = q->parentWidget() ? q->parentWidget()->effectiveWinId() : 0;
-
-    QString title;
-    int style = WS_CHILD;
-    int exsty = 0;
-
-    if (window) {
-        style = GetWindowLong(window, GWL_STYLE);
-        if (!style)
-            qErrnoWarning("QWidget::create: GetWindowLong failed");
-        topLevel = false; // #### needed for some IE plugins??
-    } else if (popup || (type == Qt::ToolTip) || (type == Qt::SplashScreen)) {
-        style = WS_POPUP;
-    } else if (topLevel && !desktop) {
-        if (flags & Qt::FramelessWindowHint)
-            style = WS_POPUP;                // no border
-        else if (flags & Qt::WindowTitleHint)
-            style = WS_OVERLAPPED;
-        else
-            style = 0;
-    }
-    if (!desktop) {
-        // if (!testAttribute(Qt::WA_PaintUnclipped))
-        // ### Commented out for now as it causes some problems, but
-        // this should be correct anyway, so dig some more into this
-#ifndef Q_FLATTEN_EXPOSE
-        style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN ;
-#endif
-        if (topLevel) {
-            if ((type == Qt::Window || dialog || tool)) {
-                if (!(flags & Qt::FramelessWindowHint)) {
-                    style |= WS_POPUP;
-                    if (!(flags & Qt::MSWindowsFixedSizeDialogHint))
-                        style |= WS_THICKFRAME;
-                    else
-                        style |= WS_DLGFRAME;
-                }
-                if (flags & Qt::WindowTitleHint)
-                    style |= WS_CAPTION;
-                if (flags & Qt::WindowSystemMenuHint)
-                    style |= WS_SYSMENU;
-                if (flags & Qt::WindowMinimizeButtonHint)
-                    style |= WS_MINIMIZEBOX;
-                if (shouldShowMaximizeButton())
-                    style |= WS_MAXIMIZEBOX;
-                if (tool)
-                    exsty |= WS_EX_TOOLWINDOW;
-                if (flags & Qt::WindowContextHelpButtonHint)
-                    exsty |= WS_EX_CONTEXTHELP;
-            } else {
-                 exsty |= WS_EX_TOOLWINDOW;
-            }
-        }
-    }
-
-    if (flags & Qt::WindowTitleHint) {
-        title = q->isWindow() ? qAppName() : q->objectName();
-    }
-
-    // The Qt::WA_WState_Created flag is checked by translateConfigEvent() in
-    // qapplication_win.cpp. We switch it off temporarily to avoid move
-    // and resize events during creationt
-    q->setAttribute(Qt::WA_WState_Created, false);
-
-    if (window) {                                // override the old window
-        if (destroyOldWindow)
-            destroyw = data.winid;
-        id = window;
-        setWinId(window);
-        LONG res = SetWindowLong(window, GWL_STYLE, style);
-        if (!res)
-            qErrnoWarning("QWidget::create: Failed to set window style");
-#ifdef _WIN64
-        res = SetWindowLongPtr( window, GWLP_WNDPROC, (LONG_PTR)QtWndProc );
-#else
-        res = SetWindowLong( window, GWL_WNDPROC, (LONG)QtWndProc );
-#endif
-        if (!res)
-            qErrnoWarning("QWidget::create: Failed to set window procedure");
-    } else if (desktop) {                        // desktop widget
-        id = GetDesktopWindow();
-//         QWidget *otherDesktop = QWidget::find(id);        // is there another desktop?
-//         if (otherDesktop && otherDesktop->testWFlags(Qt::WPaintDesktop)) {
-//             otherDesktop->d_func()->setWinId(0);        // remove id from widget mapper
-//             d->setWinId(id);                     // make sure otherDesktop is
-//             otherDesktop->d_func()->setWinId(id);       //   found first
-//         } else {
-            setWinId(id);
-//         }
-    } else if (topLevel) {                       // create top-level widget
-        if (popup)
-            parentw = 0;
-
-        const bool wasMoved = q->testAttribute(Qt::WA_Moved);
-        int x = wasMoved ? data.crect.left() : CW_USEDEFAULT;
-        int y = wasMoved ? data.crect.top() : CW_USEDEFAULT;
-        int w = CW_USEDEFAULT;
-        int h = CW_USEDEFAULT;
-
-        // Adjust for framestrut when needed
-        RECT rect = {0,0,0,0};
-        bool isVisibleOnScreen = !q->testAttribute(Qt::WA_DontShowOnScreen);
-        if (isVisibleOnScreen && AdjustWindowRectEx(&rect, style & ~WS_OVERLAPPED, FALSE, exsty)) {
-            QTLWExtra *td = maybeTopData();
-            if (wasMoved && (td && !td->posFromMove)) {
-                x = data.crect.x() + rect.left;
-                y = data.crect.y() + rect.top;
-            }
-
-            if (q->testAttribute(Qt::WA_Resized)) {
-                w = data.crect.width() + (rect.right - rect.left);
-                h = data.crect.height() + (rect.bottom - rect.top);
-            }
-        }
-        //update position & initial size of POPUP window
-        if (isVisibleOnScreen && topLevel && initializeWindow && (style & WS_POPUP)) {
-            if (!q->testAttribute(Qt::WA_Resized)) {
-                w = sw/2;
-                h = 4*sh/10;
-                if (extra) {
-                    int dx = rect.right - rect.left;
-                    int dy = rect.bottom - rect.top;
-                    w = qMin(w, extra->maxw + dx);
-                    h = qMin(h, extra->maxh + dy);
-                    w = qMax(w, extra->minw + dx);
-                    h = qMax(h, extra->minh + dy);
-                }
-            }
-            if (!wasMoved) {
-                x = qMax(sw/2 - w/2, 0);
-                y = qMax(sh/2 - h/2, 0);
-            }
-        }
-
-        id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()),
-                            reinterpret_cast<const wchar_t *>(title.utf16()), style,
-                            x, y, w, h,
-                            parentw, NULL, appinst, NULL);
-        if (!id)
-            qErrnoWarning("QWidget::create: Failed to create window");
-        setWinId(id);
-        if ((flags & Qt::WindowStaysOnTopHint) || (type == Qt::ToolTip)) {
-            SetWindowPos(id, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-            if (flags & Qt::WindowStaysOnBottomHint)
-                qWarning() << "QWidget: Incompatible window flags: the window can't be on top and on bottom at the same time";
-        } else if (flags & Qt::WindowStaysOnBottomHint)
-            SetWindowPos(id, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-        winUpdateIsOpaque();
-    } else if (q->testAttribute(Qt::WA_NativeWindow) || paintOnScreen()) { // create child widget
-        id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()),
-                            reinterpret_cast<const wchar_t *>(title.utf16()), style,
-                            data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(),
-                            parentw, NULL, appinst, NULL);
-        if (!id)
-            qErrnoWarning("QWidget::create: Failed to create window");
-        SetWindowPos(id, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
-        setWinId(id);
-    }
-
-    if (desktop) {
-        q->setAttribute(Qt::WA_WState_Visible);
-    } else if (topLevel && !q->testAttribute(Qt::WA_DontShowOnScreen)) {
-        RECT  cr;
-        GetClientRect(id, &cr);
-        // one cannot trust cr.left and cr.top, use a correction POINT instead
-        POINT pt;
-        pt.x = 0;
-        pt.y = 0;
-        ClientToScreen(id, &pt);
-
-        if (data.crect.width() == 0 || data.crect.height() == 0) {
-            data.crect = QRect(pt.x, pt.y, data.crect.width(), data.crect.height());
-        } else {
-            data.crect = QRect(QPoint(pt.x, pt.y),
-                               QPoint(pt.x + cr.right - 1, pt.y + cr.bottom - 1));
-        }
-
-        if (data.fstrut_dirty) {
-            // be nice to activeqt
-            updateFrameStrut();
-        }
-    }
-
-    if (topLevel) {
-        if (data.window_flags & Qt::CustomizeWindowHint
-            && data.window_flags & Qt::WindowTitleHint) {
-            HMENU systemMenu = GetSystemMenu((HWND)q->internalWinId(), FALSE);
-            if (data.window_flags & Qt::WindowCloseButtonHint)
-                EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_ENABLED);
-            else
-                EnableMenuItem(systemMenu, SC_CLOSE, MF_BYCOMMAND|MF_GRAYED);
-        }
-    }
-
-    q->setAttribute(Qt::WA_WState_Created);                // accept move/resize events
-    hd = 0;                                        // no display context
-
-    if (q->testAttribute(Qt::WA_AcceptTouchEvents))
-        registerTouchWindow();
-
-    if (window) {                                // got window from outside
-        if (IsWindowVisible(window))
-            q->setAttribute(Qt::WA_WState_Visible);
-        else
-            q->setAttribute(Qt::WA_WState_Visible, false);
-    }
-
-    if (extra && !extra->mask.isEmpty())
-        setMask_sys(extra->mask);
-
-#if defined(QT_NON_COMMERCIAL)
-    QT_NC_WIDGET_CREATE
-#endif
-
-#ifndef QT_NO_IM
-    if (q->hasFocus() && q->testAttribute(Qt::WA_InputMethodEnabled))
-        q->inputContext()->setFocusWidget(q);
-#endif
-
-    if (destroyw) {
-        DestroyWindow(destroyw);
-    }
-
-#ifndef QT_NO_TABLETEVENT
-    if (q != qt_tablet_widget && QWidgetPrivate::mapper)
-        qt_tablet_init();
-#endif // QT_NO_TABLETEVENT
-
-    if (q->testAttribute(Qt::WA_DropSiteRegistered))
-        registerDropSite(true);
-
-    if (maybeTopData() && maybeTopData()->opacity != 255)
-        q->setWindowOpacity(maybeTopData()->opacity/255.);
-
-    if (topLevel && (data.crect.width() == 0 || data.crect.height() == 0)) {
-        q->setAttribute(Qt::WA_OutsideWSRange, true);
-    }
-
-    if (!topLevel && q->testAttribute(Qt::WA_NativeWindow) && q->testAttribute(Qt::WA_Mapped)) {
-        Q_ASSERT(q->internalWinId());
-        ShowWindow(q->internalWinId(), SW_SHOW);
-    }
-}
-
-#endif //Q_WS_WINCE
-
-
-void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
-{
-    Q_D(QWidget);
-    d->aboutToDestroy();
-    if (!isWindow() && parentWidget())
-        parentWidget()->d_func()->invalidateBuffer(d->effectiveRectFor(geometry()));
-    d->deactivateWidgetCleanup();
-    if (testAttribute(Qt::WA_WState_Created)) {
-        setAttribute(Qt::WA_WState_Created, false);
-        for(int i = 0; i < d->children.size(); ++i) { // destroy all widget children
-            register QObject *obj = d->children.at(i);
-            if (obj->isWidgetType())
-                ((QWidget*)obj)->destroy(destroySubWindows,
-                                         destroySubWindows);
-        }
-        if (mouseGrb == this)
-            releaseMouse();
-        if (keyboardGrb == this)
-            releaseKeyboard();
-        if (testAttribute(Qt::WA_ShowModal))                // just be sure we leave modal
-            QApplicationPrivate::leaveModal(this);
-        else if ((windowType() == Qt::Popup))
-            qApp->d_func()->closePopup(this);
-        if (destroyWindow && !(windowType() == Qt::Desktop) && internalWinId()) {
-            DestroyWindow(internalWinId());
-        }
-#ifdef Q_WS_WINCE
-        if (destroyWindow && (windowType() == Qt::Desktop) && !GetDesktopWindow()) {
-            DestroyWindow(internalWinId());
-        }
-
-#endif
-        QT_TRY {
-            d->setWinId(0);
-        } QT_CATCH (const std::bad_alloc &) {
-            // swallow - destructors must not throw
-        }
-    }
-}
-
-void QWidgetPrivate::reparentChildren()
-{
-    Q_Q(QWidget);
-    QObjectList chlist = q->children();
-    for(int i = 0; i < chlist.size(); ++i) { // reparent children
-        QObject *obj = chlist.at(i);
-        if (obj->isWidgetType()) {
-            QWidget *w = (QWidget *)obj;
-            if ((w->windowType() == Qt::Popup)) {
-                ;
-            } else if (w->isWindow()) {
-                bool showIt = w->isVisible();
-                QPoint old_pos = w->pos();
-                w->setParent(q, w->windowFlags());
-                w->move(old_pos);
-                if (showIt)
-                    w->show();
-            } else {
-                w->d_func()->invalidateBuffer(w->rect());
-                SetParent(w->effectiveWinId(), q->effectiveWinId());
-                w->d_func()->reparentChildren();
-            }
-        }
-    }
-}
-
-void QWidgetPrivate::setParent_sys(QWidget *parent, Qt::WindowFlags f)
-{
-    Q_Q(QWidget);
-    bool wasCreated = q->testAttribute(Qt::WA_WState_Created);
-    if (q->isVisible() && q->parentWidget() && parent != q->parentWidget())
-        q->parentWidget()->d_func()->invalidateBuffer(effectiveRectFor(q->geometry()));
-
-    WId old_winid = data.winid;
-    // hide and reparent our own window away. Otherwise we might get
-    // destroyed when emitting the child remove event below. See QWorkspace.
-    if (q->isVisible() && data.winid) {
-        ShowWindow(data.winid, SW_HIDE);
-        SetParent(data.winid, 0);
-    }
-    bool dropSiteWasRegistered = false;
-    if (q->testAttribute(Qt::WA_DropSiteRegistered)) {
-        dropSiteWasRegistered = true;
-        q->setAttribute(Qt::WA_DropSiteRegistered, false); // ole dnd unregister (we will register again below)
-    }
-    QList<QWidget *> registeredDropChildren;
-    if (QWidget *nativeParent = q->internalWinId() ? q : q->nativeParentWidget()) {
-        if (const QWExtra *extra = nativeParent->d_func()->extra) {
-            foreach (QWidget *w, extra->oleDropWidgets) {
-                if (w && q->isAncestorOf(w)) {
-                    registeredDropChildren.push_back(w);
-                    w->setAttribute(Qt::WA_DropSiteRegistered, false);
-                }
-            }
-        }
-    }
-    if ((q->windowType() == Qt::Desktop))
-        old_winid = 0;
-    setWinId(0);
-
-    QObjectPrivate::setParent_helper(parent);
-    bool explicitlyHidden = q->testAttribute(Qt::WA_WState_Hidden) && q->testAttribute(Qt::WA_WState_ExplicitShowHide);
-
-    data.window_flags = f;
-    data.fstrut_dirty = true;
-    q->setAttribute(Qt::WA_WState_Created, false);
-    q->setAttribute(Qt::WA_WState_Visible, false);
-    q->setAttribute(Qt::WA_WState_Hidden, false);
-    adjustFlags(data.window_flags, q);
-    // keep compatibility with previous versions, we need to preserve the created state
-    // (but we recreate the winId for the widget being reparented, again for compatibility)
-    if (wasCreated || (!q->isWindow() && parent->testAttribute(Qt::WA_WState_Created)))
-        createWinId();
-    if (q->isWindow() || (!parent || parent->isVisible()) || explicitlyHidden)
-        q->setAttribute(Qt::WA_WState_Hidden);
-    q->setAttribute(Qt::WA_WState_ExplicitShowHide, explicitlyHidden);
-
-    if (wasCreated) {
-        reparentChildren();
-    }
-
-    if (extra && !extra->mask.isEmpty()) {
-        QRegion r = extra->mask;
-        extra->mask = QRegion();
-        q->setMask(r);
-    }
-    if (extra && extra->topextra && !extra->topextra->caption.isEmpty()) {
-        setWindowIcon_sys(true);
-        setWindowTitle_helper(extra->topextra->caption);
-    }
-    if (old_winid) {
-#ifndef QT_NO_DRAGANDDROP
-        if (extra && extra->dropTarget) {
-            // NOTE: It is possible that the current widget has already registered an ole drop target
-            // without Qt::WA_DropSiteRegistered being set. In this case we have to call RevokeDragDrop()
-            // to drop the reference count of the ole drop target object held by windows to prevent leak
-            // and re-register the old drop target object to the new window handle if possible
-            RevokeDragDrop(old_winid);
-            if (q->internalWinId())
-                RegisterDragDrop(q->internalWinId(), extra->dropTarget);
-        }
-#endif // !QT_NO_DRAGANDDROP
-        DestroyWindow(old_winid);
-    }
-
-    if (q->testAttribute(Qt::WA_AcceptDrops) || dropSiteWasRegistered
-        || (!q->isWindow() && q->parentWidget() && q->parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
-        q->setAttribute(Qt::WA_DropSiteRegistered, true);
-    foreach (QWidget *w, registeredDropChildren)
-        w->setAttribute(Qt::WA_DropSiteRegistered, true);
-
-#ifdef Q_WS_WINCE
-    // Show borderless toplevel windows in tasklist & NavBar
-    if (!parent) {
-        QString txt = q->windowTitle().isEmpty()?qAppName():q->windowTitle();
-        SetWindowText(q->internalWinId(), (wchar_t*)txt.utf16());
-    }
-#endif
-    invalidateBuffer(q->rect());
-}
-
-
-QPoint QWidget::mapToGlobal(const QPoint &pos) const
-{
-    Q_D(const QWidget);
-    QWidget *parentWindow = window();
-    QWExtra *extra = parentWindow->d_func()->extra;
-    if (!isVisible() || parentWindow->isMinimized() || !testAttribute(Qt::WA_WState_Created) || !internalWinId()
-        || (extra
-#ifndef QT_NO_GRAPHICSVIEW
-            && extra->proxyWidget
-#endif //QT_NO_GRAPHICSVIEW
-            )) {
-        if (extra && extra->topextra && extra->topextra->embedded) {
-            QPoint pt = mapTo(parentWindow, pos);
-            POINT p = {pt.x(), pt.y()};
-            ClientToScreen(parentWindow->effectiveWinId(), &p);
-            return QPoint(p.x, p.y);
-        } else {
-            QPoint toGlobal = mapTo(parentWindow, pos) + parentWindow->pos();
-            // Adjust for window decorations
-            toGlobal += parentWindow->geometry().topLeft() - parentWindow->frameGeometry().topLeft();
-            return toGlobal;
-        }
-    }
-    POINT p;
-    QPoint tmp = d->mapToWS(pos);
-    p.x = tmp.x();
-    p.y = tmp.y();
-    ClientToScreen(internalWinId(), &p);
-    return QPoint(p.x, p.y);
-}
-
-QPoint QWidget::mapFromGlobal(const QPoint &pos) const
-{
-    Q_D(const QWidget);
-    QWidget *parentWindow = window();
-    QWExtra *extra = parentWindow->d_func()->extra;
-    if (!isVisible() || parentWindow->isMinimized() || !testAttribute(Qt::WA_WState_Created) || !internalWinId()
-        || (extra
-#ifndef QT_NO_GRAPHICSVIEW
-            && extra->proxyWidget
-#endif //QT_NO_GRAPHICSVIEW
-            )) {
-        if (extra && extra->topextra && extra->topextra->embedded) {
-            POINT p = {pos.x(), pos.y()};
-            ScreenToClient(parentWindow->effectiveWinId(), &p);
-            return mapFrom(parentWindow, QPoint(p.x, p.y));
-        } else {
-            QPoint fromGlobal = mapFrom(parentWindow, pos - parentWindow->pos());
-            // Adjust for window decorations
-            fromGlobal -= parentWindow->geometry().topLeft() - parentWindow->frameGeometry().topLeft();
-            return fromGlobal;
-        }
-    }
-    POINT p;
-    p.x = pos.x();
-    p.y = pos.y();
-    ScreenToClient(internalWinId(), &p);
-    return d->mapFromWS(QPoint(p.x, p.y));
-}
-
-void QWidgetPrivate::updateSystemBackground() {}
-
-#ifndef QT_NO_CURSOR
-void QWidgetPrivate::setCursor_sys(const QCursor &cursor)
-{
-    Q_UNUSED(cursor);
-    Q_Q(QWidget);
-    qt_win_set_cursor(q, false);
-}
-
-void QWidgetPrivate::unsetCursor_sys()
-{
-    Q_Q(QWidget);
-    qt_win_set_cursor(q, false);
-}
-#endif
-
-void QWidgetPrivate::setWindowTitle_sys(const QString &caption)
-{
-    Q_Q(QWidget);
-    if (!q->isWindow())
-        return;
-
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-    SetWindowText(q->internalWinId(), (wchar_t*)caption.utf16());
-}
-
-HICON qt_createIcon(QIcon icon, int xSize, int ySize, QPixmap **cache)
-{
-    HICON result = 0;
-    if (!icon.isNull()) { // valid icon
-        QSize size = icon.actualSize(QSize(xSize, ySize));
-        QPixmap pm = icon.pixmap(size);
-        if (pm.isNull())
-            return 0;
-
-        result = pm.toWinHICON();
-
-        if (cache) {
-            delete *cache;
-            *cache = new QPixmap(pm);;
-        }
-    }
-    return result;
-}
-
-void QWidgetPrivate::setWindowIcon_sys(bool forceReset)
-{
-    Q_Q(QWidget);
-    if (!q->testAttribute(Qt::WA_WState_Created) || !q->isWindow())
-        return;
-    QTLWExtra* x = topData();
-    if (x->iconPixmap && !forceReset)
-        // already been set
-        return;
-
-    if (x->winIconBig) {
-        DestroyIcon(x->winIconBig);
-        x->winIconBig = 0;
-    }
-    if (x->winIconSmall) {
-        DestroyIcon(x->winIconSmall);
-        x->winIconSmall = 0;
-    }
-
-    x->winIconSmall = qt_createIcon(q->windowIcon(),
-                                    GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
-                                    &(x->iconPixmap));
-    x->winIconBig = qt_createIcon(q->windowIcon(),
-                                  GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON),
-                                  &(x->iconPixmap));
-    if (x->winIconBig) {
-        SendMessage(q->internalWinId(), WM_SETICON, 0 /* ICON_SMALL */, (LPARAM)x->winIconSmall);
-        SendMessage(q->internalWinId(), WM_SETICON, 1 /* ICON_BIG */, (LPARAM)x->winIconBig);
-    } else {
-        SendMessage(q->internalWinId(), WM_SETICON, 0 /* ICON_SMALL */, (LPARAM)x->winIconSmall);
-        SendMessage(q->internalWinId(), WM_SETICON, 1 /* ICON_BIG */, (LPARAM)x->winIconSmall);
-    }
-}
-
-
-void QWidgetPrivate::setWindowIconText_sys(const QString &iconText)
-{
-    Q_UNUSED(iconText);
-}
-
-
-QCursor *qt_grab_cursor()
-{
-    return mouseGrbCur;
-}
-
-// The procedure does nothing, but is required for mousegrabbing to work
-#ifndef Q_WS_WINCE
-LRESULT QT_WIN_CALLBACK qJournalRecordProc(int nCode, WPARAM wParam, LPARAM lParam)
-{
-    return CallNextHookEx(journalRec, nCode, wParam, lParam);
-}
-#endif //Q_WS_WINCE
-
-/* Works only as long as pointer is inside the application's window,
-   which is good enough for QDockWidget.
-
-   Doesn't call SetWindowsHookEx() - this function causes a system-wide
-   freeze if any other app on the system installs a hook and fails to
-   process events. */
-void QWidgetPrivate::grabMouseWhileInWindow()
-{
-    Q_Q(QWidget);
-    if (!qt_nograb()) {
-        if (mouseGrb)
-            mouseGrb->releaseMouse();
-        Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-        SetCapture(q->effectiveWinId());
-        mouseGrb = q;
-#ifndef QT_NO_CURSOR
-        mouseGrbCur = new QCursor(mouseGrb->cursor());
-#endif
-    }
-}
-
-#ifndef Q_WS_WINCE
-void QWidget::grabMouse()
-{
-    if (!qt_nograb()) {
-        if (mouseGrb)
-            mouseGrb->releaseMouse();
-        journalRec = SetWindowsHookEx(WH_JOURNALRECORD, (HOOKPROC)qJournalRecordProc, GetModuleHandle(0), 0);
-        Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-        SetCapture(effectiveWinId());
-        mouseGrb = this;
-#ifndef QT_NO_CURSOR
-        mouseGrbCur = new QCursor(mouseGrb->cursor());
-#endif
-    }
-}
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor)
-{
-    if (!qt_nograb()) {
-        if (mouseGrb)
-            mouseGrb->releaseMouse();
-        journalRec = SetWindowsHookEx(WH_JOURNALRECORD, (HOOKPROC)qJournalRecordProc, GetModuleHandle(0), 0);
-        Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-        SetCapture(effectiveWinId());
-        mouseGrbCur = new QCursor(cursor);
-        SetCursor(mouseGrbCur->handle());
-        mouseGrb = this;
-    }
-}
-#endif
-
-void QWidget::releaseMouse()
-{
-    if (!qt_nograb() && mouseGrb == this) {
-        ReleaseCapture();
-        if (journalRec) {
-            UnhookWindowsHookEx(journalRec);
-            journalRec = 0;
-        }
-        if (mouseGrbCur) {
-            delete mouseGrbCur;
-            mouseGrbCur = 0;
-        }
-        mouseGrb = 0;
-    }
-}
-#endif
-
-void QWidget::grabKeyboard()
-{
-    if (!qt_nograb()) {
-        if (keyboardGrb)
-            keyboardGrb->releaseKeyboard();
-        keyboardGrb = this;
-    }
-}
-
-void QWidget::releaseKeyboard()
-{
-    if (!qt_nograb() && keyboardGrb == this)
-        keyboardGrb = 0;
-}
-
-
-QWidget *QWidget::mouseGrabber()
-{
-    return mouseGrb;
-}
-
-QWidget *QWidget::keyboardGrabber()
-{
-    return keyboardGrb;
-}
-
-void QWidget::activateWindow()
-{
-    window()->createWinId();
-    SetForegroundWindow(window()->internalWinId());
-}
-
-#ifndef Q_WS_WINCE
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
-    Q_D(QWidget);
-    Qt::WindowStates oldstate = windowState();
-    if (oldstate == newstate)
-        return;
-
-    int max = SW_MAXIMIZE;
-    int min = SW_MINIMIZE;
-
-    int normal = SW_SHOWNOACTIVATE;
-    if (newstate & Qt::WindowActive) {
-        max = SW_SHOWMAXIMIZED;
-        min = SW_SHOWMINIMIZED;
-        normal = SW_SHOWNORMAL;
-    }
-
-    if (isWindow()) {
-        createWinId();
-        Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
-        // Ensure the initial size is valid, since we store it as normalGeometry below.
-        if (!testAttribute(Qt::WA_Resized) && !isVisible())
-            adjustSize();
-
-        if ((oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized)) {
-            if (newstate & Qt::WindowMaximized && !(oldstate & Qt::WindowFullScreen))
-                d->topData()->normalGeometry = geometry();
-            if (isVisible() && !(newstate & Qt::WindowMinimized)) {
-                ShowWindow(internalWinId(), (newstate & Qt::WindowMaximized) ? max : normal);
-                if (!(newstate & Qt::WindowFullScreen)) {
-                    QRect r = d->topData()->normalGeometry;
-                    if (!(newstate & Qt::WindowMaximized) && r.width() >= 0) {
-                        if (pos() != r.topLeft() || size() !=r.size()) {
-                            d->topData()->normalGeometry = QRect(0,0,-1,-1);
-                            setGeometry(r);
-                        }
-                    }
-                } else {
-                    d->updateFrameStrut();
-                }
-            }
-        }
-
-        if ((oldstate & Qt::WindowFullScreen) != (newstate & Qt::WindowFullScreen)) {
-            if (newstate & Qt::WindowFullScreen) {
-                if (d->topData()->normalGeometry.width() < 0 && !(oldstate & Qt::WindowMaximized))
-                    d->topData()->normalGeometry = geometry();
-                d->topData()->savedFlags = Qt::WindowFlags(GetWindowLong(internalWinId(), GWL_STYLE));
-#ifndef Q_FLATTEN_EXPOSE
-                UINT style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP;
-#else
-                UINT style = WS_POPUP;
-#endif
-               if (ulong(d->topData()->savedFlags) & WS_SYSMENU)
-                   style |= WS_SYSMENU;
-                if (isVisible())
-                    style |= WS_VISIBLE;
-                SetWindowLong(internalWinId(), GWL_STYLE, style);
-                QRect r = QApplication::desktop()->screenGeometry(this);
-                UINT swpf = SWP_FRAMECHANGED;
-                if (newstate & Qt::WindowActive)
-                    swpf |= SWP_NOACTIVATE;
-
-                SetWindowPos(internalWinId(), HWND_TOP, r.left(), r.top(), r.width(), r.height(), swpf);
-                d->updateFrameStrut();
-            } else {
-                UINT style = d->topData()->savedFlags;
-                if (isVisible())
-                    style |= WS_VISIBLE;
-                SetWindowLong(internalWinId(), GWL_STYLE, style);
-
-                UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE;
-                if (newstate & Qt::WindowActive)
-                    swpf |= SWP_NOACTIVATE;
-                SetWindowPos(internalWinId(), 0, 0, 0, 0, 0, swpf);
-                d->updateFrameStrut();
-
-                // preserve maximized state
-                if (isVisible())
-                    ShowWindow(internalWinId(), (newstate & Qt::WindowMaximized) ? max : normal);
-
-                if (!(newstate & Qt::WindowMaximized)) {
-                    QRect r = d->topData()->normalGeometry;
-                    d->topData()->normalGeometry = QRect(0,0,-1,-1);
-                    if (r.isValid())
-                        setGeometry(r);
-                }
-            }
-        }
-
-        if ((oldstate & Qt::WindowMinimized) != (newstate & Qt::WindowMinimized)) {
-            if (isVisible())
-                ShowWindow(internalWinId(), (newstate & Qt::WindowMinimized) ? min :
-                                    (newstate & Qt::WindowMaximized) ? max : normal);
-        }
-    }
-    data->window_state = newstate;
-    QWindowStateChangeEvent e(oldstate);
-    QApplication::sendEvent(this, &e);
-}
-#endif //Q_WS_WINCE
-
-
-/*
-  \internal
-  Platform-specific part of QWidget::hide().
-*/
-
-void QWidgetPrivate::hide_sys()
-{
-    Q_Q(QWidget);
-    deactivateWidgetCleanup();
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-#ifdef Q_WS_WINCE
-    if (!qt_wince_is_mobile() && q->isFullScreen()) {
-        HWND handle = FindWindow(L"HHTaskBar", L"");
-        if (handle) {
-            ShowWindow(handle, 1);
-            EnableWindow(handle, true);
-        }
-    }
-#endif
-    if (q->windowFlags() != Qt::Desktop) {
-        if ((q->windowFlags() & Qt::Popup) && q->internalWinId())
-            ShowWindow(q->internalWinId(), SW_HIDE);
-        else if (q->internalWinId())
-            SetWindowPos(q->internalWinId(),0, 0,0,0,0, SWP_HIDEWINDOW|SWP_NOSIZE|SWP_NOMOVE|SWP_NOZORDER);
-    }
-    if (q->isWindow()) {
-        if (QWidgetBackingStore *bs = maybeBackingStore())
-            bs->releaseBuffer();
-    } else {
-        invalidateBuffer(q->rect());
-    }
-    q->setAttribute(Qt::WA_Mapped, false);
-}
-
-
-/*
-  \internal
-  Platform-specific part of QWidget::show().
-*/
-#ifndef Q_WS_WINCE
-void QWidgetPrivate::show_sys()
-{
-    Q_Q(QWidget);
-#if defined(QT_NON_COMMERCIAL)
-    QT_NC_SHOW_WINDOW
-#endif
-    if (q->testAttribute(Qt::WA_OutsideWSRange))
-        return;
-    q->setAttribute(Qt::WA_Mapped);
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
-    if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
-        invalidateBuffer(q->rect());
-        return;
-    }
-
-    if (data.window_flags & Qt::Window) {
-        QTLWExtra *extra = topData();
-        if (!extra->hotkeyRegistered) {
-            // Try to set the hotkey using information from STARTUPINFO
-            STARTUPINFO startupInfo;
-            GetStartupInfo(&startupInfo);
-            // If STARTF_USEHOTKEY is set, hStdInput is the virtual keycode
-            if (startupInfo.dwFlags & 0x00000200) {
-                WPARAM hotKey = (WPARAM)startupInfo.hStdInput;
-                SendMessage(data.winid, WM_SETHOTKEY, hotKey, 0);
-            }
-            extra->hotkeyRegistered = 1;
-        }
-    }
-
-    int sm = SW_SHOWNORMAL;
-    bool fakedMaximize = false;
-    if (q->isWindow()) {
-        if (q->isMinimized()) {
-            sm = SW_SHOWMINIMIZED;
-            if (!IsWindowVisible(q->internalWinId()))
-                sm = SW_SHOWMINNOACTIVE;
-        } else if (q->isMaximized()) {
-            sm = SW_SHOWMAXIMIZED;
-            // Windows will not behave correctly when we try to maximize a window which does not
-            // have minimize nor maximize buttons in the window frame. Windows would then ignore
-            // non-available geometry, and rather maximize the widget to the full screen, minus the
-            // window frame (caption). So, we do a trick here, by adding a maximize button before
-            // maximizing the widget, and then remove the maximize button afterwards.
-            Qt::WindowFlags &flags = data.window_flags;
-            if (flags & Qt::WindowTitleHint &&
-                !(flags & (Qt::WindowMinMaxButtonsHint | Qt::FramelessWindowHint))) {
-                fakedMaximize = TRUE;
-                int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
-                SetWindowLong(q->internalWinId(), GWL_STYLE, style | WS_MAXIMIZEBOX);
-            }
-        }
-    }
-    if (q->testAttribute(Qt::WA_ShowWithoutActivating)
-        || (q->windowType() == Qt::Popup)
-        || (q->windowType() == Qt::ToolTip)
-        || (q->windowType() == Qt::Tool)) {
-        sm = SW_SHOWNOACTIVATE;
-    }
-
-
-    if (q->internalWinId())
-        ShowWindow(q->internalWinId(), sm);
-
-    if (fakedMaximize) {
-        int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
-        SetWindowLong(q->internalWinId(), GWL_STYLE, style & ~WS_MAXIMIZEBOX);
-        SetWindowPos(q->internalWinId(), 0, 0, 0, 0, 0,
-                     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER
-                     | SWP_FRAMECHANGED);
-    }
-
-    if (q->internalWinId()) {
-        if (IsIconic(q->internalWinId()))
-            data.window_state |= Qt::WindowMinimized;
-        if (IsZoomed(q->internalWinId()))
-            data.window_state |= Qt::WindowMaximized;
-        // This is to resolve the problem where popups are opened from the
-        // system tray and not being implicitly activated
-        if (q->windowType() == Qt::Popup &&
-            !q->parentWidget() && !qApp->activeWindow()) 
-            q->activateWindow();
-    }
-
-    winSetupGestures();
-
-    invalidateBuffer(q->rect());
-}
-#endif //Q_WS_WINCE
-
-void QWidgetPrivate::setFocus_sys()
-{
-    Q_Q(QWidget);
-    if (q->testAttribute(Qt::WA_WState_Created) && q->window()->windowType() != Qt::Popup)
-        SetFocus(q->effectiveWinId());
-}
-
-void QWidgetPrivate::raise_sys()
-{
-    Q_Q(QWidget);
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-    if (q->internalWinId())
-        SetWindowPos(q->internalWinId(), HWND_TOP, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-}
-
-void QWidgetPrivate::lower_sys()
-{
-    Q_Q(QWidget);
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-    if (q->internalWinId())
-        SetWindowPos(q->internalWinId(), HWND_BOTTOM, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-    invalidateBuffer(q->rect());
-}
-
-void QWidgetPrivate::stackUnder_sys(QWidget* w)
-{
-    Q_Q(QWidget);
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-    if (q->internalWinId() && w->internalWinId())
-        SetWindowPos(q->internalWinId(), w->internalWinId() , 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
-    invalidateBuffer(q->rect());
-}
-
-
-/*
-  Helper function for non-toplevel widgets. Helps to map Qt's 32bit
-  coordinate system to Windpws's 16bit coordinate system.
-
-  This code is duplicated from the X11 code, so any changes there
-  should also (most likely) be reflected here.
-
-  (In all comments below: s/X/Windows/g)
- */
-
-void QWidgetPrivate::setWSGeometry(bool dontShow, const QRect &)
-{
-    Q_Q(QWidget);
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
-    /*
-      There are up to four different coordinate systems here:
-      Qt coordinate system for this widget.
-      X coordinate system for this widget (relative to wrect).
-      Qt coordinate system for parent
-      X coordinate system for parent (relative to parent's wrect).
-     */
-    QRect validRange(-XCOORD_MAX,-XCOORD_MAX, 2*XCOORD_MAX, 2*XCOORD_MAX);
-    QRect wrectRange(-WRECT_MAX,-WRECT_MAX, 2*WRECT_MAX, 2*WRECT_MAX);
-    QRect wrect;
-    //xrect is the X geometry of my X widget. (starts out in  parent's Qt coord sys, and ends up in parent's X coord sys)
-    QRect xrect = data.crect;
-
-    const QWidget *const parent = q->parentWidget();
-    QRect parentWRect = parent->data->wrect;
-
-    if (parentWRect.isValid()) {
-        // parent is clipped, and we have to clip to the same limit as parent
-        if (!parentWRect.contains(xrect)) {
-            xrect &= parentWRect;
-            wrect = xrect;
-            //translate from parent's to my Qt coord sys
-            wrect.translate(-data.crect.topLeft());
-        }
-        //translate from parent's Qt coords to parent's X coords
-        xrect.translate(-parentWRect.topLeft());
-
-    } else {
-        // parent is not clipped, we may or may not have to clip
-
-        if (data.wrect.isValid() && QRect(QPoint(),data.crect.size()).contains(data.wrect)) {
-            // This is where the main optimization is: we are already
-            // clipped, and if our clip is still valid, we can just
-            // move our window, and do not need to move or clip
-            // children
-
-            QRect vrect = xrect & parent->rect();
-            vrect.translate(-data.crect.topLeft()); //the part of me that's visible through parent, in my Qt coords
-            if (data.wrect.contains(vrect)) {
-                xrect = data.wrect;
-                xrect.translate(data.crect.topLeft());
-                if (q->internalWinId())
-                    MoveWindow(q->internalWinId(), xrect.x(), xrect.y(), xrect.width(), xrect.height(), true);
-                return;
-            }
-        }
-
-        if (!validRange.contains(xrect)) {
-            // we are too big, and must clip
-            xrect &=wrectRange;
-            wrect = xrect;
-            wrect.translate(-data.crect.topLeft());
-            //parent's X coord system is equal to parent's Qt coord
-            //sys, so we don't need to map xrect.
-        }
-
-    }
-
-
-    // unmap if we are outside the valid window system coord system
-    bool outsideRange = !xrect.isValid();
-    bool mapWindow = false;
-    if (q->testAttribute(Qt::WA_OutsideWSRange) != outsideRange) {
-        q->setAttribute(Qt::WA_OutsideWSRange, outsideRange);
-        if (outsideRange) {
-            if (q->internalWinId())
-                ShowWindow(q->internalWinId(), SW_HIDE);
-            q->setAttribute(Qt::WA_Mapped, false);
-        } else if (!q->isHidden()) {
-            mapWindow = true;
-        }
-    }
-
-    if (outsideRange)
-        return;
-
-    bool jump = (data.wrect != wrect);
-    data.wrect = wrect;
-
-    // and now recursively for all children...
-    for (int i = 0; i < children.size(); ++i) {
-        QObject *object = children.at(i);
-        if (object->isWidgetType()) {
-            QWidget *w = static_cast<QWidget *>(object);
-            if (!w->isWindow() && w->testAttribute(Qt::WA_WState_Created))
-                w->d_func()->setWSGeometry();
-        }
-    }
-
-    // move ourselves to the new position and map (if necessary) after
-    // the movement. Rationale: moving unmapped windows is much faster
-    // than moving mapped windows
-    if (q->internalWinId()) {
-        if (!parent->internalWinId())
-            xrect.translate(parent->mapTo(q->nativeParentWidget(), QPoint(0, 0)));
-        MoveWindow(q->internalWinId(), xrect.x(), xrect.y(), xrect.width(), xrect.height(), !jump);
-    }
-    if (mapWindow && !dontShow) {
-        q->setAttribute(Qt::WA_Mapped);
-        if (q->internalWinId())
-            ShowWindow(q->internalWinId(), SW_SHOWNOACTIVATE);
-    }
-
-    if (jump && q->internalWinId())
-        InvalidateRect(q->internalWinId(), 0, false);
-
-}
-
-//
-// The internal qWinRequestConfig, defined in qapplication_win.cpp, stores move,
-// resize and setGeometry requests for a widget that is already
-// processing a config event. The purpose is to avoid recursion.
-//
-void qWinRequestConfig(WId, int, int, int, int, int);
-
-void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
-{
-    Q_Q(QWidget);
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-    if (extra) {                                // any size restrictions?
-        w = qMin(w,extra->maxw);
-        h = qMin(h,extra->maxh);
-        w = qMax(w,extra->minw);
-        h = qMax(h,extra->minh);
-    }
-    if (q->isWindow())
-        topData()->normalGeometry = QRect(0, 0, -1, -1);
-
-    QSize  oldSize(q->size());
-    QPoint oldPos(q->pos());
-
-    if (!q->isWindow())
-        isMove = (data.crect.topLeft() != QPoint(x, y));
-    bool isResize = w != oldSize.width() || h != oldSize.height();
-
-    if (!isMove && !isResize)
-        return;
-
-    if (isResize && !q->testAttribute(Qt::WA_StaticContents) && q->internalWinId())
-        ValidateRgn(q->internalWinId(), 0);
-
-#ifdef Q_WS_WINCE
-    // On Windows CE we can't just fiddle around with the window state.
-    // Too much magic in setWindowState.
-    if (isResize && q->isMaximized())
-        q->setWindowState(q->windowState() & ~Qt::WindowMaximized);
-#else
-    if (isResize)
-        data.window_state &= ~Qt::WindowMaximized;
-#endif
-
-    if (data.window_state & Qt::WindowFullScreen) {
-        QTLWExtra *top = topData();
-
-        if (q->isWindow()) {
-            // We need to update these flags when we remove the full screen state
-            // or the frame will not be updated
-            UINT style = top->savedFlags;
-            if (q->isVisible())
-                style |= WS_VISIBLE;
-            SetWindowLong(q->internalWinId(), GWL_STYLE, style);
-
-            UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE;
-            if (data.window_state & Qt::WindowActive)
-                swpf |= SWP_NOACTIVATE;
-            SetWindowPos(q->internalWinId(), 0, 0, 0, 0, 0, swpf);
-            updateFrameStrut();
-        }
-        data.window_state &= ~Qt::WindowFullScreen;
-        topData()->savedFlags = 0;
-    }
-
-    QTLWExtra *tlwExtra = q->window()->d_func()->maybeTopData();
-    const bool inTopLevelResize = tlwExtra ? tlwExtra->inTopLevelResize : false;
-    const bool isTranslucentWindow = !isOpaque && ptrUpdateLayeredWindowIndirect && (data.window_flags & Qt::FramelessWindowHint)
-                                     && GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & Q_WS_EX_LAYERED;
-
-    if (q->testAttribute(Qt::WA_WState_ConfigPending)) {        // processing config event
-        if (q->internalWinId())
-            qWinRequestConfig(q->internalWinId(), isMove ? 2 : 1, x, y, w, h);
-    } else {
-        if (!q->testAttribute(Qt::WA_DontShowOnScreen))
-            q->setAttribute(Qt::WA_WState_ConfigPending);
-        if (q->windowType() == Qt::Desktop) {
-            data.crect.setRect(x, y, w, h);
-        } else if (q->isWindow()) {
-            QRect fs(frameStrut());
-            if (extra) {
-                fs.setLeft(x - fs.left());
-                fs.setTop(y - fs.top());
-                fs.setRight((x + w - 1) + fs.right());
-                fs.setBottom((y + h - 1) + fs.bottom());
-            }
-            if (w == 0 || h == 0) {
-                q->setAttribute(Qt::WA_OutsideWSRange, true);
-                if (q->isVisible() && q->testAttribute(Qt::WA_Mapped))
-                    hide_sys();
-                data.crect = QRect(x, y, w, h);
-            } else if (q->isVisible() && q->testAttribute(Qt::WA_OutsideWSRange)) {
-                q->setAttribute(Qt::WA_OutsideWSRange, false);
-
-                // put the window in its place and show it
-                MoveWindow(q->internalWinId(), fs.x(), fs.y(), fs.width(), fs.height(), true);
-                RECT rect;
-                if (!q->testAttribute(Qt::WA_DontShowOnScreen)) {
-                    GetClientRect(q->internalWinId(), &rect);
-                    data.crect.setRect(x, y, rect.right - rect.left, rect.bottom - rect.top);
-                } else {
-                    data.crect.setRect(x, y, w, h);
-                }
-
-                show_sys();
-            } else if (!q->testAttribute(Qt::WA_DontShowOnScreen)) {
-                q->setAttribute(Qt::WA_OutsideWSRange, false);
-#ifndef Q_WS_WINCE
-                // If the window is hidden and in maximized state or minimized, instead of moving the
-                // window, set the normal position of the window.
-                WINDOWPLACEMENT wndpl;
-                wndpl.length = sizeof(WINDOWPLACEMENT);
-                GetWindowPlacement(q->internalWinId(), &wndpl);
-                if ((wndpl.showCmd == SW_MAXIMIZE && !IsWindowVisible(q->internalWinId())) || wndpl.showCmd == SW_SHOWMINIMIZED) {
-                    RECT normal = {fs.x(), fs.y(), fs.x()+fs.width(), fs.y()+fs.height()};
-                    wndpl.rcNormalPosition = normal;
-                    wndpl.showCmd = wndpl.showCmd == SW_SHOWMINIMIZED ? SW_SHOWMINIMIZED : SW_HIDE;
-                    SetWindowPlacement(q->internalWinId(), &wndpl);
-                } else {
-#else
-                if (data.window_state & Qt::WindowMaximized) {
-                    qt_wince_maximize(q);
-                } else {
-#endif
-                    MoveWindow(q->internalWinId(), fs.x(), fs.y(), fs.width(), fs.height(), true);
-                }
-                if (!q->isVisible())
-                    InvalidateRect(q->internalWinId(), 0, FALSE);
-                RECT rect;
-                // If the layout has heightForWidth, the MoveWindow() above can
-                // change the size/position, so refresh them.
-
-                if (isTranslucentWindow) {
-                    data.crect.setRect(x, y, w, h);
-                } else {
-                    GetClientRect(q->internalWinId(), &rect);
-                    RECT rcNormalPosition ={0, 0, 0, 0};
-                    // Use (0,0) as window position for embedded ActiveQt controls.
-                    if (!tlwExtra || !tlwExtra->embedded)
-                        GetWindowRect(q->internalWinId(), &rcNormalPosition);
-                    QRect fStrut(frameStrut());
-                    data.crect.setRect(rcNormalPosition.left + fStrut.left(),
-                                       rcNormalPosition.top + fStrut.top(),
-                                       rect.right - rect.left,
-                                       rect.bottom - rect.top);
-                    isResize = data.crect.size() != oldSize;
-                }
-            } else {
-                q->setAttribute(Qt::WA_OutsideWSRange, false);
-                data.crect.setRect(x, y, w, h);
-            }
-        } else {
-            QRect oldGeom(data.crect);
-            data.crect.setRect(x, y, w, h);
-            if (q->isVisible() && (!inTopLevelResize || q->internalWinId())) {
-                // Top-level resize optimization does not work for native child widgets;
-                // disable it for this particular widget.
-                if (inTopLevelResize)
-                    tlwExtra->inTopLevelResize = false;
-
-                if (!isResize)
-                    moveRect(QRect(oldPos, oldSize), x - oldPos.x(), y - oldPos.y());
-                else
-                    invalidateBuffer_resizeHelper(oldPos, oldSize);
-
-                if (inTopLevelResize)
-                    tlwExtra->inTopLevelResize = true;
-            }
-            if (q->testAttribute(Qt::WA_WState_Created))
-                setWSGeometry();
-        }
-        q->setAttribute(Qt::WA_WState_ConfigPending, false);
-    }
-
-    if (q->isWindow() && q->isVisible() && isResize && !inTopLevelResize) {
-        invalidateBuffer(q->rect()); //after the resize
-    }
-
-    // Process events immediately rather than in translateConfigEvent to
-    // avoid windows message process delay.
-    if (q->isVisible()) {
-        if (isMove && q->pos() != oldPos) {
-            QMoveEvent e(q->pos(), oldPos);
-            QApplication::sendEvent(q, &e);
-        }
-        if (isResize) {
-            static bool slowResize = qgetenv("QT_SLOW_TOPLEVEL_RESIZE").toInt();
-            // If we have a backing store with static contents, we have to disable the top-level
-            // resize optimization in order to get invalidated regions for resized widgets.
-            // The optimization discards all invalidateBuffer() calls since we're going to
-            // repaint everything anyways, but that's not the case with static contents.
-            const bool setTopLevelResize = !slowResize && q->isWindow() && extra && extra->topextra
-                                           && !extra->topextra->inTopLevelResize
-                                           && (!extra->topextra->backingStore
-                                               || !extra->topextra->backingStore->hasStaticContents());
-            if (setTopLevelResize)
-                extra->topextra->inTopLevelResize = true;
-            QResizeEvent e(q->size(), oldSize);
-            QApplication::sendEvent(q, &e);
-            if (setTopLevelResize)
-                extra->topextra->inTopLevelResize = false;
-        }
-    } else {
-        if (isMove && q->pos() != oldPos)
-            q->setAttribute(Qt::WA_PendingMoveEvent, true);
-        if (isResize)
-            q->setAttribute(Qt::WA_PendingResizeEvent, true);
-    }
-}
-
-bool QWidgetPrivate::shouldShowMaximizeButton()
-{
-    if (data.window_flags & Qt::MSWindowsFixedSizeDialogHint)
-        return false;
-    // if the user explicitly asked for the maximize button, we try to add
-    // it even if the window has fixed size.
-    if (data.window_flags & Qt::CustomizeWindowHint &&
-        data.window_flags & Qt::WindowMaximizeButtonHint)
-        return true;
-    if (extra) {
-        if ((extra->maxw && extra->maxw != QWIDGETSIZE_MAX && extra->maxw != QLAYOUTSIZE_MAX)
-            || (extra->maxh && extra->maxh != QWIDGETSIZE_MAX && extra->maxh != QLAYOUTSIZE_MAX))
-            return false;
-    }
-    return data.window_flags & Qt::WindowMaximizeButtonHint;
-}
-
-void QWidgetPrivate::winUpdateIsOpaque()
-{
-#ifndef Q_WS_WINCE
-    Q_Q(QWidget);
-
-    if (!q->isWindow() || !q->testAttribute(Qt::WA_TranslucentBackground))
-        return;
-
-    if ((data.window_flags & Qt::FramelessWindowHint) == 0)
-        return;
-
-    if (!isOpaque && ptrUpdateLayeredWindowIndirect) {
-        SetWindowLong(q->internalWinId(), GWL_EXSTYLE,
-            GetWindowLong(q->internalWinId(), GWL_EXSTYLE) | Q_WS_EX_LAYERED);
-    } else {
-        SetWindowLong(q->internalWinId(), GWL_EXSTYLE,
-            GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & ~Q_WS_EX_LAYERED);
-    }
-#endif
-}
-
-void QWidgetPrivate::setConstraints_sys()
-{
-#ifndef Q_WS_WINCE_WM
-    Q_Q(QWidget);
-    if (q->isWindow() && q->testAttribute(Qt::WA_WState_Created)) {
-        int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
-        if (shouldShowMaximizeButton())
-            style |= WS_MAXIMIZEBOX;
-        else
-            style &= ~WS_MAXIMIZEBOX;
-        SetWindowLong(q->internalWinId(), GWL_STYLE, style);
-    }
-#endif
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy)
-{
-    Q_Q(QWidget);
-    scrollChildren(dx, dy);
-
-    if (!paintOnScreen()) {
-        scrollRect(q->rect(), dx, dy);
-    } else {
-        UINT flags = SW_INVALIDATE;
-        if (!q->testAttribute(Qt::WA_OpaquePaintEvent))
-            flags |= SW_ERASE;
-        Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-        ScrollWindowEx(q->internalWinId(), dx, dy, 0, 0, 0, 0, flags);
-        UpdateWindow(q->internalWinId());
-    }
-}
-
-void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r)
-{
-    Q_Q(QWidget);
-
-    if (!paintOnScreen()) {
-        scrollRect(r, dx, dy);
-    } else {
-        RECT wr;
-        wr.top = r.top();
-        wr.left = r.left();
-        wr.bottom = r.bottom()+1;
-        wr.right = r.right()+1;
-
-        UINT flags = SW_INVALIDATE;
-        if (!q->testAttribute(Qt::WA_OpaquePaintEvent))
-            flags |= SW_ERASE;
-        Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-        ScrollWindowEx(q->internalWinId(), dx, dy, &wr, &wr, 0, 0, flags);
-        UpdateWindow(q->internalWinId());
-    }
-}
-
-extern Q_GUI_EXPORT HDC qt_win_display_dc();
-
-int QWidget::metric(PaintDeviceMetric m) const
-{
-    Q_D(const QWidget);
-    int val;
-    if (m == PdmWidth) {
-        val = data->crect.width();
-    } else if (m == PdmHeight) {
-        val = data->crect.height();
-    } else {
-        bool ownDC = QThread::currentThread() != qApp->thread();
-        HDC gdc = ownDC ? GetDC(0) : qt_win_display_dc();
-        switch (m) {
-        case PdmDpiX:
-        case PdmPhysicalDpiX:
-                if (d->extra && d->extra->customDpiX)
-                    val = d->extra->customDpiX;
-                else if (d->parent)
-                    val = static_cast<QWidget *>(d->parent)->metric(m);
-                else
-                    val = GetDeviceCaps(gdc, LOGPIXELSX);
-            break;
-        case PdmDpiY:
-        case PdmPhysicalDpiY:
-                if (d->extra && d->extra->customDpiY)
-                    val = d->extra->customDpiY;
-                else if (d->parent)
-                    val = static_cast<QWidget *>(d->parent)->metric(m);
-                else
-                    val = GetDeviceCaps(gdc, LOGPIXELSY);
-            break;
-        case PdmWidthMM:
-            val = data->crect.width()
-                    * GetDeviceCaps(gdc, HORZSIZE)
-                    / GetDeviceCaps(gdc, HORZRES);
-            break;
-        case PdmHeightMM:
-            val = data->crect.height()
-                    * GetDeviceCaps(gdc, VERTSIZE)
-                    / GetDeviceCaps(gdc, VERTRES);
-            break;
-        case PdmNumColors:
-            if (GetDeviceCaps(gdc, RASTERCAPS) & RC_PALETTE)
-                val = GetDeviceCaps(gdc, SIZEPALETTE);
-            else {
-                HDC hd = d->hd ? HDC(d->hd) : gdc;
-                int bpp = GetDeviceCaps(hd, BITSPIXEL);
-                if (bpp == 32)
-                    val = INT_MAX; // ### this is bogus, it should be 2^24 colors for 32 bit as well
-                else if(bpp<=8)
-                    val = GetDeviceCaps(hd, NUMCOLORS);
-                else
-                    val = 1 << (bpp * GetDeviceCaps(hd, PLANES));
-            }
-            break;
-        case PdmDepth:
-            val = GetDeviceCaps(gdc, BITSPIXEL);
-            break;
-        default:
-            val = 0;
-            qWarning("QWidget::metric: Invalid metric command");
-        }
-        if (ownDC)
-            ReleaseDC(0, gdc);
-    }
-    return val;
-}
-
-void QWidgetPrivate::createSysExtra()
-{
-#ifndef QT_NO_DRAGANDDROP
-    extra->dropTarget = 0;
-#endif
-}
-
-#ifndef Q_WS_WINCE
-void QWidgetPrivate::deleteSysExtra()
-{
-}
-#endif //Q_WS_WINCE
-
-void QWidgetPrivate::createTLSysExtra()
-{
-    extra->topextra->hotkeyRegistered = 0;
-    extra->topextra->savedFlags = 0;
-    extra->topextra->winIconBig = 0;
-    extra->topextra->winIconSmall = 0;
-}
-
-void QWidgetPrivate::deleteTLSysExtra()
-{
-    if (extra->topextra->winIconSmall)
-        DestroyIcon(extra->topextra->winIconSmall);
-    if (extra->topextra->winIconBig)
-        DestroyIcon(extra->topextra->winIconBig);
-}
-
-void QWidgetPrivate::registerDropSite(bool on)
-{
-    Q_Q(QWidget);
-    if (!q->testAttribute(Qt::WA_WState_Created))
-        return;
-    // Enablement is defined by d->extra->dropTarget != 0.
-    if (on) {
-        // Turn on.
-        createExtra();
-#ifndef QT_NO_DRAGANDDROP
-        if (!q->internalWinId())
-            q->nativeParentWidget()->d_func()->createExtra();
-        QWExtra *extra = extraData();
-        if (!extra->dropTarget)
-            extra->dropTarget = registerOleDnd(q);
-#endif
-    } else {
-        // Turn off.
-        QWExtra *extra = extraData();
-#ifndef QT_NO_DRAGANDDROP
-        if (extra && extra->dropTarget) {
-            unregisterOleDnd(q, extra->dropTarget);
-            extra->dropTarget = 0;
-        }
-#endif
-    }
-}
-
-#ifndef QT_NO_DRAGANDDROP
-QOleDropTarget* QWidgetPrivate::registerOleDnd(QWidget *widget)
-{
-    QOleDropTarget *dropTarget = new QOleDropTarget(widget);
-    Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
-    if (!widget->internalWinId()) {
-        QWidget *nativeParent = widget->nativeParentWidget();
-        Q_ASSERT(nativeParent);
-        QWExtra *nativeExtra = nativeParent->d_func()->extra;
-        Q_ASSERT(nativeExtra);
-        if (!nativeExtra->oleDropWidgets.contains(widget))
-            nativeExtra->oleDropWidgets.append(widget);
-        if (!nativeExtra->dropTarget) {
-            nativeExtra->dropTarget = registerOleDnd(nativeParent);
-            Q_ASSERT(nativeExtra->dropTarget);
-#ifndef Q_OS_WINCE
-            CoLockObjectExternal(nativeExtra->dropTarget, false, true);
-#endif
-            RegisterDragDrop(nativeParent->internalWinId(), nativeExtra->dropTarget);
-        }
-    } else {
-        RegisterDragDrop(widget->internalWinId(), dropTarget);
-#ifndef Q_OS_WINCE
-        CoLockObjectExternal(dropTarget, true, true);
-#endif
-    }
-    return dropTarget;
-}
-
-void QWidgetPrivate::unregisterOleDnd(QWidget *widget, QOleDropTarget *dropTarget)
-{
-    Q_ASSERT(widget->testAttribute(Qt::WA_WState_Created));
-    if (!widget->internalWinId()) {
-        dropTarget->releaseQt();
-        dropTarget->Release();
-        QWidget *nativeParent = widget->nativeParentWidget();
-        while (nativeParent) {
-            QWExtra *nativeExtra = nativeParent->d_func()->extra;
-            if (!nativeExtra) {
-                nativeParent = nativeParent->nativeParentWidget();
-                continue;
-            }
-
-            const int removeCounter = nativeExtra->oleDropWidgets.removeAll(widget);
-            nativeExtra->oleDropWidgets.removeAll(static_cast<QWidget *>(0));
-            if (nativeExtra->oleDropWidgets.isEmpty() && nativeExtra->dropTarget
-                && !nativeParent->testAttribute(Qt::WA_DropSiteRegistered)) {
-#ifndef Q_OS_WINCE
-                    CoLockObjectExternal(nativeExtra->dropTarget, false, true);
-#endif
-                    nativeExtra->dropTarget->releaseQt();
-                    nativeExtra->dropTarget->Release();
-                    RevokeDragDrop(nativeParent->internalWinId());
-                    nativeExtra->dropTarget = 0;
-            }
-
-            if (removeCounter)
-                break;
-
-            nativeParent = nativeParent->nativeParentWidget();
-        }
-    } else {
-#ifndef Q_OS_WINCE
-        CoLockObjectExternal(dropTarget, false, true);
-#endif
-        dropTarget->releaseQt();
-        dropTarget->Release();
-        RevokeDragDrop(widget->internalWinId());
-    }
-}
-
-#endif //QT_NO_DRAGANDDROP
-
-// from qregion_win.cpp
-extern HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom);
-void QWidgetPrivate::setMask_sys(const QRegion &region)
-{
-    Q_Q(QWidget);
-    if (!q->internalWinId())
-        return;
-
-    if (region.isEmpty()) {
-        SetWindowRgn(q->internalWinId(), 0, true);
-        return;
-    }
-
-    // Since SetWindowRegion takes ownership, and we need to translate,
-    // we take a copy.
-    HRGN wr = qt_tryCreateRegion(QRegion::Rectangle, 0,0,0,0);
-    CombineRgn(wr, region.handle(), 0, RGN_COPY);
-
-    QPoint offset = (q->isWindow()
-                     ? frameStrut().topLeft()
-                     : QPoint(0, 0));
-    OffsetRgn(wr, offset.x(), offset.y());
-
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-    if (!SetWindowRgn(data.winid, wr, true))
-        DeleteObject(wr);
-}
-
-void QWidgetPrivate::updateFrameStrut()
-{
-    Q_Q(QWidget);
-
-    if (!q->testAttribute(Qt::WA_WState_Created))
-        return;
-
-    if (!q->internalWinId()) {
-        data.fstrut_dirty = false;
-        return;
-    }
-
-    RECT rect = {0,0,0,0};
-
-    QTLWExtra *top = topData();
-    uint exstyle = GetWindowLong(q->internalWinId(), GWL_EXSTYLE);
-    uint style = GetWindowLong(q->internalWinId(), GWL_STYLE);
-#ifndef Q_WS_WINCE
-    if (AdjustWindowRectEx(&rect, style & ~(WS_OVERLAPPED), FALSE, exstyle)) {
-#else
-    if (AdjustWindowRectEx(&rect, style, FALSE, exstyle)) {
-#endif
-        top->frameStrut.setCoords(-rect.left, -rect.top, rect.right, rect.bottom);
-        data.fstrut_dirty = false;
-    }
-}
-
-#ifndef Q_WS_WINCE
-void QWidgetPrivate::setWindowOpacity_sys(qreal level)
-{
-    Q_Q(QWidget);
-
-    if (!isOpaque && ptrUpdateLayeredWindow && (data.window_flags & Qt::FramelessWindowHint)) {
-        if (GetWindowLong(q->internalWinId(), GWL_EXSTYLE) & Q_WS_EX_LAYERED) {
-            BLENDFUNCTION blend = {AC_SRC_OVER, 0, (BYTE)(255.0 * level), AC_SRC_ALPHA};
-            ptrUpdateLayeredWindow(q->internalWinId(), NULL, NULL, NULL, NULL, NULL, 0, &blend, Q_ULW_ALPHA);
-        }
-        return;
-    }
-
-    static bool function_resolved = false;
-    if (!function_resolved) {
-        ptrSetLayeredWindowAttributes =
-            (PtrSetLayeredWindowAttributes) QSystemLibrary::resolve(QLatin1String("user32"),
-                                                              "SetLayeredWindowAttributes");
-        function_resolved = true;
-    }
-
-    if (!ptrSetLayeredWindowAttributes)
-        return;
-
-    int wl = GetWindowLong(q->internalWinId(), GWL_EXSTYLE);
-
-    if (level != 1.0) {
-        if ((wl&Q_WS_EX_LAYERED) == 0)
-            SetWindowLong(q->internalWinId(), GWL_EXSTYLE, wl | Q_WS_EX_LAYERED);
-    } else if (wl&Q_WS_EX_LAYERED) {
-        SetWindowLong(q->internalWinId(), GWL_EXSTYLE, wl & ~Q_WS_EX_LAYERED);
-    }
-    ptrSetLayeredWindowAttributes(q->internalWinId(), 0, (int)(level * 255), Q_LWA_ALPHA);
-}
-#endif //Q_WS_WINCE
-
-// class QGlobalRasterPaintEngine: public QRasterPaintEngine
-// {
-// public:
-//     inline QGlobalRasterPaintEngine() : QRasterPaintEngine() { setFlushOnEnd(false); }
-// };
-// Q_GLOBAL_STATIC(QGlobalRasterPaintEngine, globalRasterPaintEngine)
-
-
-#ifndef QT_NO_DIRECTDRAW
-static uchar *qt_primary_surface_bits;
-static int qt_primary_surface_stride;
-static QImage::Format qt_primary_surface_format;
-
-void qt_win_initialize_directdraw()
-{
-    HRESULT res;
-
-    // Some initialization...
-    if (!qt_ddraw_object) {
-        res = DirectDrawCreate(0, &qt_ddraw_object, 0);
-
-        if (res != DD_OK)
-            qWarning("DirectDrawCreate failed: %d", res);
-
-        qt_ddraw_object->SetCooperativeLevel(0, DDSCL_NORMAL);
-
-        DDSURFACEDESC surfaceDesc;
-        memset(&surfaceDesc, 0, sizeof(DDSURFACEDESC));
-
-        surfaceDesc.dwSize = sizeof(DDSURFACEDESC);
-        surfaceDesc.dwFlags = DDSD_CAPS;
-        surfaceDesc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
-
-        res = qt_ddraw_object->CreateSurface(&surfaceDesc, &qt_ddraw_primary, 0);
-        if (res != DD_OK)
-            qWarning("CreateSurface failed: %d", res);
-
-        memset(&surfaceDesc, 0, sizeof(DDSURFACEDESC));
-        surfaceDesc.dwSize = sizeof(DDSURFACEDESC);
-        res = qt_ddraw_primary->Lock(0, &surfaceDesc, DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR, 0);
-        if (res != DD_OK)
-            qWarning("Locking surface failed: %d", res);
-
-        if (surfaceDesc.ddpfPixelFormat.dwFlags == DDPF_RGB) {
-            qt_primary_surface_bits = (uchar *) surfaceDesc.lpSurface;
-            qt_primary_surface_stride = surfaceDesc.lPitch;
-            qt_primary_surface_format = QImage::Format_RGB32;
-        } else {
-            qWarning("QWidget painting: unsupported device depth for onscreen painting...\n");
-        }
-
-        qt_ddraw_primary->Unlock(0);
-    }
-}
-
-class QOnScreenRasterPaintEngine : public QRasterPaintEngine
-{
-public:
-    // The image allocated here leaks... Fix if this code is ifdef'ed
-    // in
-    QOnScreenRasterPaintEngine()
-        : QRasterPaintEngine(new QImage(qt_primary_surface_bits,
-                                        QApplication::desktop()->width(),
-                                        QApplication::desktop()->height(),
-                                        qt_primary_surface_stride,
-                                        qt_primary_surface_format))
-    {
-        device = static_cast<QImage *>(d_func()->device);
-    }
-
-    bool begin(QPaintDevice *)
-    {
-        QRegion clip = systemClip();
-        originalSystemClip = clip;
-        clip.translate(widget->mapToGlobal(QPoint(0, 0)));
-        setSystemClip(clip);
-
-        QRect bounds = clip.boundingRect();
-        DDSURFACEDESC surface;
-        surface.dwSize = sizeof(DDSURFACEDESC);
-        HRESULT res = qt_ddraw_primary->Lock((RECT *) &bounds, &surface, DDLOCK_WAIT, 0);
-        if (res != DD_OK) {
-            qWarning("QWidget painting: locking onscreen bits failed: %d\n", res);
-            return false;
-        }
-
-        if (surface.lpSurface == qt_primary_surface_bits) {
-            qt_primary_surface_bits = (uchar *) surface.lpSurface;
-            device->data_ptr()->data = qt_primary_surface_bits;
-        }
-
-        return QRasterPaintEngine::begin(device);
-    }
-
-    bool end()
-    {
-        HRESULT res = qt_ddraw_primary->Unlock(0);
-        if (res != DD_OK)
-            qWarning("QWidget::paint, failed to unlock DirectDraw surface: %d", res);
-        bool ok = QRasterPaintEngine::end();
-        setSystemClip(originalSystemClip);
-        return ok;
-    }
-
-    QPoint coordinateOffset() const {
-        return -widget->mapToGlobal(QPoint(0, 0));
-    }
-
-    const QWidget *widget;
-    QImage *device;
-    QRegion originalSystemClip;
-};
-Q_GLOBAL_STATIC(QOnScreenRasterPaintEngine, onScreenPaintEngine)
-#else
-void qt_win_initialize_directdraw() { }
-#endif
-
-QPaintEngine *QWidget::paintEngine() const
-{
-#ifndef QT_NO_DIRECTDRAW
-    QOnScreenRasterPaintEngine *pe = onScreenPaintEngine();
-    pe->widget = this;
-    return pe;
-#endif
-
-    // We set this bit which is checked in setAttribute for
-    // Qt::WA_PaintOnScreen. We do this to allow these two scenarios:
-    //
-    // 1. Users accidentally set Qt::WA_PaintOnScreen on X and port to
-    // windows which would mean suddenly their widgets stop working.
-    //
-    // 2. Users set paint on screen and subclass paintEngine() to
-    // return 0, in which case we have a "hole" in the backingstore
-    // allowing use of GDI or DirectX directly.
-    //
-    // 1 is WRONG, but to minimize silent failures, we have set this
-    // bit to ignore the setAttribute call. 2. needs to be
-    // supported because its our only means of embeddeding native
-    // graphics stuff.
-    const_cast<QWidgetPrivate *>(d_func())->noPaintOnScreen = 1;
-
-    return 0;
-}
-
-QWindowSurface *QWidgetPrivate::createDefaultWindowSurface_sys()
-{
-    Q_Q(QWidget);
-    return new QRasterWindowSurface(q);
-}
-
-void QWidgetPrivate::setModal_sys()
-{
-}
-
-void QWidgetPrivate::registerTouchWindow()
-{
-    Q_Q(QWidget);
-
-    // enable WM_TOUCH* messages on our window
-    if (q->testAttribute(Qt::WA_WState_Created)
-        && QApplicationPrivate::RegisterTouchWindow
-        && q->windowType() != Qt::Desktop)
-        QApplicationPrivate::RegisterTouchWindow(q->effectiveWinId(), 0);
-}
-
-void QWidgetPrivate::winSetupGestures()
-{
-#if !defined(QT_NO_GESTURES) && !defined(QT_NO_NATIVE_GESTURES)
-    Q_Q(QWidget);
-    if (!q || !q->isVisible() || !nativeGesturePanEnabled)
-        return;
-
-    if (!QApplicationPrivate::HasTouchSupport)
-        return;
-    QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
-    if (!qAppPriv->SetGestureConfig)
-        return;
-    WId winid = q->internalWinId();
-
-    bool needh = false;
-    bool needv = false;
-    bool singleFingerPanEnabled = false;
-
-#ifndef QT_NO_SCROLLAREA
-    if (QAbstractScrollArea *asa = qobject_cast<QAbstractScrollArea*>(q->parent())) {
-        QScrollBar *hbar = asa->horizontalScrollBar();
-        QScrollBar *vbar = asa->verticalScrollBar();
-        Qt::ScrollBarPolicy hbarpolicy = asa->horizontalScrollBarPolicy();
-        Qt::ScrollBarPolicy vbarpolicy = asa->verticalScrollBarPolicy();
-        needh = (hbarpolicy == Qt::ScrollBarAlwaysOn ||
-                 (hbarpolicy == Qt::ScrollBarAsNeeded && hbar->minimum() < hbar->maximum()));
-        needv = (vbarpolicy == Qt::ScrollBarAlwaysOn ||
-                 (vbarpolicy == Qt::ScrollBarAsNeeded && vbar->minimum() < vbar->maximum()));
-        singleFingerPanEnabled = asa->d_func()->singleFingerPanEnabled;
-        if (!winid) {
-            winid = q->winId(); // enforces the native winid on the viewport
-        }
-    }
-#endif //QT_NO_SCROLLAREA
-    if (winid) {
-        GESTURECONFIG gc[1];
-        memset(gc, 0, sizeof(gc));
-        gc[0].dwID = GID_PAN;
-        if (nativeGesturePanEnabled) {
-            gc[0].dwWant = GC_PAN;
-            if (needv && singleFingerPanEnabled)
-                gc[0].dwWant |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
-            else
-                gc[0].dwBlock |= GC_PAN_WITH_SINGLE_FINGER_VERTICALLY;
-            if (needh && singleFingerPanEnabled)
-                gc[0].dwWant |= GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
-            else
-                gc[0].dwBlock |= GC_PAN_WITH_SINGLE_FINGER_HORIZONTALLY;
-        } else {
-            gc[0].dwBlock = GC_PAN;
-        }
-
-        qAppPriv->SetGestureConfig(winid, 0, sizeof(gc)/sizeof(gc[0]), gc, sizeof(gc[0]));
-    }
-#endif
-}
-
-QT_END_NAMESPACE
-
-#ifdef Q_WS_WINCE
-#       include "qwidget_wince.cpp"
-#endif
diff --git a/src/gui/kernel/qwidget_wince.cpp b/src/gui/kernel/qwidget_wince.cpp
deleted file mode 100644 (file)
index 7736092..0000000
+++ /dev/null
@@ -1,675 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifdef Q_WS_WINCE
-
-#include "qguifunctions_wince.h"
-
-QT_BEGIN_NAMESPACE
-
-const QString qt_reg_winclass(QWidget *w);                // defined in qapplication_win.cpp
-extern "C" LRESULT QT_WIN_CALLBACK QtWndProc(HWND, UINT, WPARAM, LPARAM);
-
-//#define TABLET_DEBUG
-#define PACKETDATA  (PK_X | PK_Y | PK_BUTTONS | PK_NORMAL_PRESSURE | PK_TANGENT_PRESSURE \
-                     | PK_ORIENTATION | PK_CURSOR | PK_Z)
-#define PACKETMODE  0
-
-typedef HCTX        (API *PtrWTOpen)(HWND, LPLOGCONTEXT, BOOL);
-typedef BOOL        (API *PtrWTClose)(HCTX);
-typedef UINT        (API *PtrWTInfo)(UINT, UINT, LPVOID);
-typedef BOOL        (API *PtrWTEnable)(HCTX, BOOL);
-typedef BOOL        (API *PtrWTOverlap)(HCTX, BOOL);
-typedef int        (API *PtrWTPacketsGet)(HCTX, int, LPVOID);
-typedef BOOL        (API *PtrWTGet)(HCTX, LPLOGCONTEXT);
-typedef int     (API *PtrWTQueueSizeGet)(HCTX);
-typedef BOOL    (API *PtrWTQueueSizeSet)(HCTX, int);
-
-#ifndef QT_NO_TABLETEVENT
-static void qt_tablet_init_wce();
-static void qt_tablet_cleanup_wce();
-
-static void qt_tablet_init_wce() {
-    static bool firstTime = true;
-    if (!firstTime)
-        return;
-    firstTime = false;
-    qt_tablet_widget = new QWidget(0);
-    qt_tablet_widget->createWinId();
-    qt_tablet_widget->setObjectName(QLatin1String("Qt internal tablet widget"));
-    LOGCONTEXT lcMine;
-    qAddPostRoutine(qt_tablet_cleanup_wce);
-    struct tagAXIS tpOri[3];
-    if (ptrWTInfo && ptrWTOpen && ptrWTQueueSizeGet && ptrWTQueueSizeSet) {
-        // make sure we have WinTab
-        if (!ptrWTInfo(0, 0, NULL)) {
-#ifdef TABLET_DEBUG
-            qWarning("QWidget: Wintab services not available");
-#endif
-            return;
-        }
-
-        // some tablets don't support tilt, check if it is possible,
-        qt_tablet_tilt_support = ptrWTInfo(WTI_DEVICES, DVC_ORIENTATION, &tpOri);
-        if (qt_tablet_tilt_support) {
-            // check for azimuth and altitude
-            qt_tablet_tilt_support = tpOri[0].axResolution && tpOri[1].axResolution;
-        }
-        // build our context from the default context
-        ptrWTInfo(WTI_DEFSYSCTX, 0, &lcMine);
-        // Go for the raw coordinates, the tablet event will return good stuff
-        lcMine.lcOptions |= CXO_MESSAGES | CXO_CSRMESSAGES;
-        lcMine.lcPktData = PACKETDATA;
-        lcMine.lcPktMode = PACKETMODE;
-        lcMine.lcMoveMask = PACKETDATA;
-        lcMine.lcOutOrgX = 0;
-        lcMine.lcOutExtX = lcMine.lcInExtX;
-        lcMine.lcOutOrgY = 0;
-        lcMine.lcOutExtY = -lcMine.lcInExtY;
-        qt_tablet_context = ptrWTOpen(qt_tablet_widget->winId(), &lcMine, true);
-#ifdef TABLET_DEBUG
-        qDebug("Tablet is %p", qt_tablet_context);
-#endif
-        if (!qt_tablet_context) {
-#ifdef TABLET_DEBUG
-            qWarning("QWidget: Failed to open the tablet");
-#endif
-            return;
-        }
-        // Set the size of the Packet Queue to the correct size...
-        int currSize = ptrWTQueueSizeGet(qt_tablet_context);
-        if (!ptrWTQueueSizeSet(qt_tablet_context, QT_TABLET_NPACKETQSIZE)) {
-            // Ideally one might want to use a smaller
-            // multiple, but for now, since we managed to destroy
-            // the existing Q with the previous call, set it back
-            // to the other size, which should work.  If not,
-            // there will be trouble.
-            if (!ptrWTQueueSizeSet(qt_tablet_context, currSize)) {
-                Q_ASSERT_X(0, "Qt::Internal", "There is no packet queue for"
-                         " the tablet. The tablet will not work");
-            }
-        }
-    }
-}
-
-static void qt_tablet_cleanup_wce() {
-    if (ptrWTClose)
-        ptrWTClose(qt_tablet_context);
-    delete qt_tablet_widget;
-    qt_tablet_widget = 0;
-}
-#endif // QT_NO_TABLETEVENT
-
-
-// The internal qWinRequestConfig, defined in qapplication_win.cpp, stores move,
-// resize and setGeometry requests for a widget that is already
-// processing a config event. The purpose is to avoid recursion.
-//
-void qWinRequestConfig(WId, int, int, int, int, int);
-
-void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyOldWindow) {
-    Q_Q(QWidget);
-    static int sw = -1, sh = -1;
-
-    Qt::WindowType type = q->windowType();
-    Qt::WindowFlags flags = data.window_flags;
-
-    bool topLevel = (flags & Qt::Window);
-    bool popup = (type == Qt::Popup);
-    bool dialog = (type == Qt::Dialog
-                   || type == Qt::Sheet
-                   || (flags & Qt::MSWindowsFixedSizeDialogHint));
-    bool desktop = (type == Qt::Desktop);
-    bool tool = (type == Qt::Tool || type == Qt::Drawer);
-
-    HINSTANCE appinst  = qWinAppInst();
-    HWND parentw, destroyw = 0;
-    WId id;
-
-    QString windowClassName = qt_reg_winclass(q);
-
-    if (!window)                                // always initialize
-        initializeWindow = true;
-
-    if (popup)
-        flags |= Qt::WindowStaysOnTopHint; // a popup stays on top
-
-    if (flags & (Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowContextHelpButtonHint)) {
-        flags |= Qt::WindowSystemMenuHint;
-        flags |= Qt::WindowTitleHint;
-        flags &= ~Qt::FramelessWindowHint;
-    }
-
-    if (sw < 0) {                                // get the (primary) screen size
-        sw = GetSystemMetrics(SM_CXSCREEN);
-        sh = GetSystemMetrics(SM_CYSCREEN);
-    }
-
-    if (desktop) {                                // desktop widget
-        popup = false;                                // force this flags off
-        data.crect.setRect(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
-    }
-
-    parentw = q->parentWidget() ? q->parentWidget()->effectiveWinId() : 0;
-
-    QString title;
-    int style = WS_CHILD;
-    int exsty = WS_EX_NOPARENTNOTIFY;
-
-    if (topLevel) {
-        if (!(flags & Qt::FramelessWindowHint) && !tool && !q->testAttribute(Qt::WA_DontShowOnScreen))
-          style = (WS_OVERLAPPED) | WS_SYSMENU;
-        else
-          style = WS_POPUP;
-        if ((type == Qt::ToolTip) || (type == Qt::SplashScreen)) {
-            style = WS_POPUP;
-            exsty |= WS_EX_NOANIMATION;
-        } else {
-            if (flags & Qt::WindowTitleHint)
-                style |= WS_CAPTION;
-            if (flags & Qt::WindowSystemMenuHint)
-                style |= WS_SYSMENU;
-            if (flags & Qt::WindowContextHelpButtonHint)
-                exsty |= WS_EX_CONTEXTHELP;
-#ifndef Q_WS_WINCE_WM
-            if (flags & Qt::WindowMinimizeButtonHint)
-                style |= WS_MINIMIZEBOX;
-            if (shouldShowMaximizeButton())
-                style |= WS_MAXIMIZEBOX;
-#endif
-            if (tool)
-                exsty |= WS_EX_TOOLWINDOW;
-        }
-    }
-    if (dialog) {
-        style = WS_BORDER | WS_CAPTION;
-        if (flags & Qt::WindowOkButtonHint)
-            exsty |= WS_EX_CAPTIONOKBTN;
-        if (flags & Qt::WindowCancelButtonHint || flags & Qt::WA_DeleteOnClose)
-            style |= WS_SYSMENU;
-        if (flags & Qt::WindowContextHelpButtonHint)
-            exsty |= WS_EX_CONTEXTHELP;
-    }
-    if (popup) {
-        style = WS_POPUP;
-        exsty |= WS_EX_NOANIMATION;
-    }
-
-    if (flags & Qt::WindowTitleHint) {
-        title = q->isWindow() ? qAppName() : q->objectName();
-    }
-
-    // The Qt::WA_WState_Created flag is checked by translateConfigEvent() in
-    // qapplication_win.cpp. We switch it off temporarily to avoid move
-    // and resize events during creationt
-    q->setAttribute(Qt::WA_WState_Created, false);
-
-    if (window) {                                // override the old window
-        if (destroyOldWindow)
-            destroyw = data.winid;
-        id = window;
-        setWinId(window);
-        LONG res = SetWindowLong(window, GWL_STYLE, style);
-        if (!res)
-            qErrnoWarning("QWidget::create: Failed to set window style");
-
-        res = SetWindowLong( window, GWL_WNDPROC, (LONG)QtWndProc );
-
-        if (!res)
-            qErrnoWarning("QWidget::create: Failed to set window procedure");
-    } else if (desktop) {                        // desktop widget
-        id = GetDesktopWindow();
-        if (!id) { //Create a dummy desktop
-            RECT r;
-            SystemParametersInfo(SPI_GETWORKAREA, 0, &r, 0);
-            id = CreateWindow(reinterpret_cast<const wchar_t *>(windowClassName.utf16()),
-                              reinterpret_cast<const wchar_t *>(title.utf16()), style,
-                              r.left, r.top, r.right - r.left, r.bottom - r.top,
-                              0, 0, appinst, 0);
-        }
-        setWinId(id);
-    } else if (topLevel) {                       // create top-level widget
-        const bool wasMoved = q->testAttribute(Qt::WA_Moved);
-        
-        int x, y;
-        if (qt_wince_is_mobile()) {
-            x = wasMoved ? data.crect.left() : CW_USEDEFAULT;
-            y = wasMoved ? data.crect.top() : CW_USEDEFAULT;
-        } else {
-            x = wasMoved ? data.crect.left() : 100;
-            y = wasMoved ? data.crect.top() : 100;
-        }
-        
-        int w = CW_USEDEFAULT;
-        int h = CW_USEDEFAULT;
-
-        // Adjust for framestrut when needed
-        RECT rect = {0,0,0,0};
-        if (AdjustWindowRectEx(&rect, style, FALSE, exsty)) {
-            QTLWExtra *td = maybeTopData();
-            if (wasMoved && (td && !td->posFromMove)) {
-                x = data.crect.x() + rect.left;
-                y = data.crect.y() + rect.top;
-            }
-
-            if (q->testAttribute(Qt::WA_Resized)) {
-                w = data.crect.width() + (rect.right - rect.left);
-                h = data.crect.height() + (rect.bottom - rect.top);
-            }
-        }
-
-        id = CreateWindowEx(exsty, reinterpret_cast<const wchar_t *>(windowClassName.utf16()),
-                            reinterpret_cast<const wchar_t *>(title.utf16()), style,
-                            x, y, w, h,
-                            0, 0, appinst, 0);
-
-        if (!id)
-            qErrnoWarning("QWidget::create: Failed to create window");
-        setWinId(id);
-        if ((flags & Qt::WindowStaysOnTopHint) || (type == Qt::ToolTip))
-            SetWindowPos(id, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
-    } else if (q->testAttribute(Qt::WA_NativeWindow) || paintOnScreen()) { // create child widget
-        id = CreateWindowEx(exsty, (wchar_t*)windowClassName.utf16(), (wchar_t*)title.utf16(), style,
-                            data.crect.left(), data.crect.top(), data.crect.width(), data.crect.height(),
-                            parentw, NULL, appinst, NULL);
-        if (!id)
-            qErrnoWarning("QWidget::create: Failed to create window");
-        SetWindowPos(id, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
-        setWinId(id);
-    }
-
-    if (desktop) {
-        q->setAttribute(Qt::WA_WState_Visible);
-    } else if (topLevel && !q->testAttribute(Qt::WA_DontShowOnScreen)) {
-        RECT  cr;
-        GetClientRect(id, &cr);
-        // one cannot trust cr.left and cr.top, use a correction POINT instead
-        POINT pt;
-        pt.x = 0;
-        pt.y = 0;
-        if (!q->testAttribute(Qt::WA_DontShowOnScreen) || q->testAttribute(Qt::WA_Moved))
-            ClientToScreen(id, &pt);
-        data.crect = QRect(QPoint(pt.x, pt.y),
-                            QPoint(pt.x + cr.right - 1, pt.y + cr.bottom - 1));
-
-        if (data.fstrut_dirty) {
-            // be nice to activeqt
-            updateFrameStrut();
-        }
-    }
-
-    q->setAttribute(Qt::WA_WState_Created);                // accept move/resize events
-    hd = 0;                                        // no display context
-
-    if (window) {                                // got window from outside
-        if (IsWindowVisible(window))
-            q->setAttribute(Qt::WA_WState_Visible);
-        else
-            q->setAttribute(Qt::WA_WState_Visible, false);
-    }
-
-    if (extra && !extra->mask.isEmpty())
-        setMask_sys(extra->mask);
-
-#if defined(QT_NON_COMMERCIAL)
-    QT_NC_WIDGET_CREATE
-#endif
-
-    if (q->hasFocus() && q->testAttribute(Qt::WA_InputMethodEnabled))
-        q->inputContext()->setFocusWidget(q);
-
-    if (destroyw) {
-        DestroyWindow(destroyw);
-    }
-
-#ifndef QT_NO_TABLETEVENT
-    if (q != qt_tablet_widget && QWidgetPrivate::mapper)
-        qt_tablet_init_wce();
-#endif // QT_NO_TABLETEVENT
-
-    if (q->testAttribute(Qt::WA_DropSiteRegistered))
-        registerDropSite(true);
-
-    if (maybeTopData() && maybeTopData()->opacity != 255)
-        q->setWindowOpacity(maybeTopData()->opacity/255.);
-
-    if (!topLevel && q->testAttribute(Qt::WA_NativeWindow) && q->testAttribute(Qt::WA_Mapped)) {
-        Q_ASSERT(q->internalWinId());
-        ShowWindow(q->internalWinId(), SW_SHOW);
-    }
-}
-
-/*
-  \internal
-  Platform-specific part of QWidget::show().
-*/
-void QWidgetPrivate::show_sys() {
-    Q_Q(QWidget);
-#if defined(QT_NON_COMMERCIAL)
-    QT_NC_SHOW_WINDOW
-#endif
-    if (q->testAttribute(Qt::WA_OutsideWSRange))
-        return;
-
-    q->setAttribute(Qt::WA_Mapped);
-
-    Q_ASSERT(q->testAttribute(Qt::WA_WState_Created));
-
-    if (q->testAttribute(Qt::WA_DontShowOnScreen)) {
-        invalidateBuffer(q->rect());
-        return;
-    }
-
-
-    int sm = SW_SHOW;
-    bool fakedMaximize = false;
-    if (q->isWindow()) {
-#ifndef Q_WS_WINCE_WM
-        if (q->isMinimized()) {
-            sm = SW_SHOWMINIMIZED;
-        } else if (q->isMaximized()) {
-            sm = SW_SHOWMAXIMIZED;
-            // Windows will not behave correctly when we try to maximize a window which does not
-            // have minimize nor maximize buttons in the window frame. Windows would then ignore
-            // non-available geometry, and rather maximize the widget to the full screen, minus the
-            // window frame (caption). So, we do a trick here, by adding a maximize button before
-            // maximizing the widget, and then remove the maximize button afterwards.
-            Qt::WindowFlags &flags = data.window_flags;
-            if (flags & Qt::WindowTitleHint &&
-                !(flags & (Qt::WindowMinMaxButtonsHint | Qt::FramelessWindowHint))) {
-                fakedMaximize = TRUE;
-                int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
-                SetWindowLong(q->internalWinId(), GWL_STYLE, style | WS_MAXIMIZEBOX);
-            }
-        } else
-#else
-        // Imitate minimizing on Windows mobile by hiding the widget.
-        if (q->isMinimized())
-            sm = SW_HIDE;
-#endif
-        if (q->isHidden()) {
-            sm = SW_HIDE;
-        }
-    }
-    if (q->testAttribute(Qt::WA_ShowWithoutActivating)
-        || (q->windowType() == Qt::Popup)
-        || (q->windowType() == Qt::ToolTip)
-        || (q->windowType() == Qt::Tool)) {
-        sm = SW_SHOWNOACTIVATE;
-    }
-
-    ShowWindow(q->internalWinId(), sm);
-
-    if (q->isMaximized() && q->isWindow())
-        qt_wince_maximize(q);
-
-#ifndef Q_WS_WINCE_WM
-    if (!qt_wince_is_mobile() && q->isFullScreen()) {
-        HWND handle = FindWindow(L"HHTaskBar", L"");
-        if (handle) {
-            ShowWindow(handle, SW_HIDE);
-            EnableWindow(handle, false);
-        }
-    }
-
-    if (fakedMaximize) {
-        int style = GetWindowLong(q->internalWinId(), GWL_STYLE);
-        SetWindowLong(q->internalWinId(), GWL_STYLE, style & ~WS_MAXIMIZEBOX);
-        SetWindowPos(q->internalWinId(), 0, 0, 0, 0, 0,
-                     SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER
-                     | SWP_FRAMECHANGED);
-    }
-#else
-    Q_UNUSED(fakedMaximize);
-#endif
-
-    if (q->isWindow() && sm == SW_SHOW)
-        SetForegroundWindow(q->internalWinId());
-
-    invalidateBuffer(q->rect());
-}
-
-void QWidget::setWindowState(Qt::WindowStates newstate)
-{
-    Q_D(QWidget);
-    Qt::WindowStates oldstate = windowState();
-    if (oldstate == newstate)
-        return;
-
-    int max = SW_SHOWNORMAL;
-    int normal = SW_SHOWNOACTIVATE;
-
-    if ((oldstate & Qt::WindowMinimized) && !(newstate & Qt::WindowMinimized))
-        newstate |= Qt::WindowActive;
-    if (newstate & Qt::WindowActive)
-        normal = SW_SHOWNORMAL;
-    if (isWindow()) {
-        createWinId();
-        Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-        // Ensure the initial size is valid, since we store it as normalGeometry below.
-        if ((!testAttribute(Qt::WA_Resized) && !isVisible()))
-            adjustSize();
-        if (!d->topData()->normalGeometry.isValid()) {
-            if (newstate & Qt::WindowMaximized && !(oldstate & Qt::WindowFullScreen))
-                d->topData()->normalGeometry = geometry();
-            if (newstate & Qt::WindowMinimized && !(oldstate & Qt::WindowFullScreen))
-                d->topData()->normalGeometry = geometry();
-        }
-        if ((oldstate & Qt::WindowMaximized) != (newstate & Qt::WindowMaximized)) {
-            if (!(newstate & Qt::WindowMaximized)) {
-                int style = GetWindowLong(internalWinId(), GWL_STYLE) | WS_BORDER | WS_POPUP | WS_CAPTION;
-                SetWindowLong(internalWinId(), GWL_STYLE, style);
-                SetWindowLong(internalWinId(), GWL_EXSTYLE, GetWindowLong (internalWinId(), GWL_EXSTYLE) & ~ WS_EX_NODRAG);
-                qt_wince_unmaximize(this);
-            }
-            if (isVisible() && newstate & Qt::WindowMaximized)
-                qt_wince_maximize(this);
-            if (isVisible() && !(newstate & Qt::WindowMinimized)) {
-                ShowWindow(internalWinId(), (newstate & Qt::WindowMaximized) ? max : normal);
-                if (!(newstate & Qt::WindowFullScreen)) {
-                    QRect r = d->topData()->normalGeometry;
-                    if (!(newstate & Qt::WindowMaximized) && r.width() >= 0) {
-                        if (pos() != r.topLeft() || size() !=r.size()) {
-                            d->topData()->normalGeometry = QRect(0,0,-1,-1);
-                            setGeometry(r);
-                        }
-                    }
-                } else {
-                    d->updateFrameStrut();
-                }
-            }
-        }
-        if ((oldstate & Qt::WindowFullScreen) != (newstate & Qt::WindowFullScreen)) {
-            if (newstate & Qt::WindowFullScreen) {
-                if (d->topData()->normalGeometry.width() < 0 && !(oldstate & Qt::WindowMaximized))
-                    d->topData()->normalGeometry = geometry();
-                d->topData()->savedFlags = (Qt::WindowFlags)GetWindowLong(internalWinId(), GWL_STYLE);
-                UINT style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_POPUP;
-                if (isVisible())
-                    style |= WS_VISIBLE;
-                SetWindowLong(internalWinId(), GWL_STYLE, style);
-                QRect r = qApp->desktop()->screenGeometry(this);
-                UINT swpf = SWP_FRAMECHANGED;
-                if (newstate & Qt::WindowActive)
-                    swpf |= SWP_NOACTIVATE;
-                qt_wince_full_screen(internalWinId(), true, swpf);
-                d->updateFrameStrut();
-            } else {
-                UINT style = d->topData()->savedFlags;
-                if (isVisible())
-                    style |= WS_VISIBLE;
-                SetWindowLong(internalWinId(), GWL_STYLE, style);
-                UINT swpf = SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE;
-                if (newstate & Qt::WindowActive)
-                    swpf |= SWP_NOACTIVATE;
-                qt_wince_full_screen(internalWinId(), false, swpf);
-                d->updateFrameStrut();
-
-                // preserve maximized state
-                if (isVisible()) {
-                    ShowWindow(internalWinId(), (newstate & Qt::WindowMaximized) ? max : normal);
-                    if (newstate & Qt::WindowMaximized)
-                        qt_wince_maximize(this);
-                }
-                if (!(newstate & Qt::WindowMaximized)) {
-                    QRect r = d->topData()->normalGeometry;
-                    d->topData()->normalGeometry = QRect(0,0,-1,-1);
-                    if (r.isValid())
-                        setGeometry(r);
-                }
-            }
-        }
-        if ((oldstate & Qt::WindowMinimized) != (newstate & Qt::WindowMinimized)) {
-            if (newstate & Qt::WindowMinimized)
-                qt_wince_minimize(internalWinId());
-            else if (newstate & Qt::WindowMaximized) {
-                ShowWindow(internalWinId(), max);
-                qt_wince_maximize(this);
-            } else {
-                ShowWindow(internalWinId(), normal);
-            }
-        }
-    }
-    data->window_state = newstate;
-    QWindowStateChangeEvent e(oldstate);
-    QApplication::sendEvent(this, &e);
-}
-
-void QWidgetPrivate::deleteSysExtra()
-{
-    Q_Q(QWidget);
-    if (!qt_wince_is_mobile() && q->isFullScreen()) {
-        HWND handle = FindWindow(L"HHTaskBar", L"");
-        if (handle) {
-            ShowWindow(handle, SW_SHOWNORMAL);
-            EnableWindow(handle, true);
-        }
-    }
-}
-
-void QWidgetPrivate::setWindowOpacity_sys(qreal level) {
-    Q_UNUSED(level);
-    return;
-}
-
-// The procedure does nothing, but is required for mousegrabbing to work
-LRESULT QT_WIN_CALLBACK qJournalRecordProc(int nCode, WPARAM wParam, LPARAM lParam) {
-    Q_UNUSED(nCode);
-    Q_UNUSED(wParam);
-    Q_UNUSED(lParam);
-    return 0;
-}
-
-void QWidget::grabMouse() {
-    if (!qt_nograb()) {
-        if (mouseGrb)
-            mouseGrb->releaseMouse();
-        Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-        SetCapture(internalWinId());
-        mouseGrb = this;
-    }
-}
-
-#ifndef QT_NO_CURSOR
-void QWidget::grabMouse(const QCursor &cursor) {
-    if (!qt_nograb()) {
-        if (mouseGrb)
-            mouseGrb->releaseMouse();
-        Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-        SetCapture(internalWinId());
-        mouseGrbCur = new QCursor(cursor);
-        SetCursor(mouseGrbCur->handle());
-        mouseGrb = this;
-    }
-}
-#endif
-
-void QWidget::releaseMouse() {
-    if (!qt_nograb() && mouseGrb == this) {
-        ReleaseCapture();
-        if (journalRec) {
-            journalRec = 0;
-        }
-        if (mouseGrbCur) {
-            delete mouseGrbCur;
-            mouseGrbCur = 0;
-        }
-        mouseGrb = 0;
-    }
-}
-
-void QWidget::show()
-{
-    Qt::WindowFlags flags = windowFlags() & 0xff;
-    int threshold = qApp->autoMaximizeThreshold();
-    if ((threshold < 0) || (windowState() & Qt::WindowFullScreen) || (windowState() & Qt::WindowMaximized)) {
-        setVisible(true);
-        return;
-    }
-    int height = sizeHint().height();
-    int screenHeight = (qreal(threshold) / 100.0f * qApp->desktop()->screenGeometry(this).height());
-    bool maximize  = height > screenHeight;
-    if (!maximize) {
-        // If we do not maximize yet we check the widget and its child widgets whether they are
-        //vertically expanding. If one of the widgets is expanding we maximize.
-        QList<QWidget *> list = findChildren<QWidget *>();
-        bool expandingChild = sizePolicy().verticalPolicy () == QSizePolicy::Expanding;
-        for (int i = 0; (i < list.size()) && !expandingChild; ++i) {
-            expandingChild = list.at(i)->sizePolicy().verticalPolicy () == QSizePolicy::Expanding;
-        }
-        maximize = expandingChild;
-    }
-    if ((minimumSizeHint().height() > qApp->desktop()->screenGeometry(this).height()) || (minimumSizeHint().width() > qApp->desktop()->screenGeometry(this).width()))
-        maximize = false;
-
-    if ((flags == Qt::Window || flags == Qt::Dialog) && maximize) {
-        setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
-            | Qt::WindowMaximized);
-        setVisible(true);
-    }
-    else {
-        setVisible(true);
-    }
-}
-
-QT_END_NAMESPACE
-
-#endif // Q_WS_WINCE
diff --git a/src/gui/kernel/qwindowdefs_win.h b/src/gui/kernel/qwindowdefs_win.h
deleted file mode 100644 (file)
index ec07df0..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWINDOWDEFS_WIN_H
-#define QWINDOWDEFS_WIN_H
-
-#include <QtCore/qglobal.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-
-QT_END_NAMESPACE
-
-#if !defined(Q_NOWINSTRICT)
-#define Q_WINSTRICT
-#endif
-
-#if defined(Q_WINSTRICT)
-
-#if !defined(STRICT)
-#define STRICT
-#endif
-#undef NO_STRICT
-#define Q_DECLARE_HANDLE(name) struct name##__; typedef struct name##__ *name
-
-#else
-
-#if !defined(NO_STRICT)
-#define NO_STRICT
-#endif
-#undef  STRICT
-#define Q_DECLARE_HANDLE(name) typedef HANDLE name
-
-#endif
-
-#ifndef HINSTANCE
-Q_DECLARE_HANDLE(HINSTANCE);
-#endif
-#ifndef HDC
-Q_DECLARE_HANDLE(HDC);
-#endif
-#ifndef HWND
-Q_DECLARE_HANDLE(HWND);
-#endif
-#ifndef HFONT
-Q_DECLARE_HANDLE(HFONT);
-#endif
-#ifndef HPEN
-Q_DECLARE_HANDLE(HPEN);
-#endif
-#ifndef HBRUSH
-Q_DECLARE_HANDLE(HBRUSH);
-#endif
-#ifndef HBITMAP
-Q_DECLARE_HANDLE(HBITMAP);
-#endif
-#ifndef HICON
-Q_DECLARE_HANDLE(HICON);
-#endif
-#ifndef HCURSOR
-typedef HICON HCURSOR;
-#endif
-#ifndef HPALETTE
-Q_DECLARE_HANDLE(HPALETTE);
-#endif
-#ifndef HRGN
-Q_DECLARE_HANDLE(HRGN);
-#endif
-#ifndef HMONITOR
-Q_DECLARE_HANDLE(HMONITOR);
-#endif
-#ifndef HRESULT
-typedef long HRESULT;
-#endif
-
-typedef struct tagMSG MSG;
-typedef HWND WId;
-
-
-QT_BEGIN_NAMESPACE
-
-Q_CORE_EXPORT HINSTANCE qWinAppInst();
-Q_CORE_EXPORT HINSTANCE qWinAppPrevInst();
-Q_CORE_EXPORT int       qWinAppCmdShow();
-Q_GUI_EXPORT HDC           qt_win_display_dc();
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QWINDOWDEFS_WIN_H
diff --git a/src/gui/kernel/qwinnativepangesturerecognizer_win.cpp b/src/gui/kernel/qwinnativepangesturerecognizer_win.cpp
deleted file mode 100644 (file)
index e6a934d..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwinnativepangesturerecognizer_win_p.h"
-
-#include "qevent.h"
-#include "qgraphicsitem.h"
-#include "qgesture.h"
-
-#include "qgesture_p.h"
-#include "qevent_p.h"
-#include "qapplication_p.h"
-#include "qwidget_p.h"
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(QT_NO_NATIVE_GESTURES)
-
-QWinNativePanGestureRecognizer::QWinNativePanGestureRecognizer()
-{
-}
-
-QGesture *QWinNativePanGestureRecognizer::create(QObject *target)
-{
-    if (!target)
-        return new QPanGesture; // a special case
-    if (!target->isWidgetType())
-        return 0;
-    if (qobject_cast<QGraphicsObject *>(target))
-        return 0;
-
-    QWidget *q = static_cast<QWidget *>(target);
-    QWidgetPrivate *d = q->d_func();
-    d->nativeGesturePanEnabled = true;
-    d->winSetupGestures();
-
-    return new QPanGesture;
-}
-
-QGestureRecognizer::Result QWinNativePanGestureRecognizer::recognize(QGesture *state,
-                                                                     QObject *,
-                                                                     QEvent *event)
-{
-    QPanGesture *q = static_cast<QPanGesture*>(state);
-    QPanGesturePrivate *d = q->d_func();
-
-    QGestureRecognizer::Result result = QGestureRecognizer::Ignore;
-    if (event->type() == QEvent::NativeGesture) {
-        QNativeGestureEvent *ev = static_cast<QNativeGestureEvent*>(event);
-        switch(ev->gestureType) {
-        case QNativeGestureEvent::GestureBegin:
-            break;
-        case QNativeGestureEvent::Pan:
-            result = QGestureRecognizer::TriggerGesture;
-            event->accept();
-            break;
-        case QNativeGestureEvent::GestureEnd:
-            if (q->state() == Qt::NoGesture)
-                return QGestureRecognizer::Ignore; // some other gesture has ended
-            result = QGestureRecognizer::FinishGesture;
-            break;
-        default:
-            return QGestureRecognizer::Ignore;
-        }
-        if (q->state() == Qt::NoGesture) {
-            d->lastOffset = d->offset = QPointF();
-            d->startPosition = ev->position;
-        } else {
-            d->lastOffset = d->offset;
-            d->offset = QPointF(ev->position.x() - d->startPosition.x(),
-                                ev->position.y() - d->startPosition.y());
-        }
-    }
-    return result;
-}
-
-void QWinNativePanGestureRecognizer::reset(QGesture *state)
-{
-    QPanGesture *pan = static_cast<QPanGesture*>(state);
-    QPanGesturePrivate *d = pan->d_func();
-
-    d->lastOffset = d->offset = QPointF();
-    d->startPosition = QPoint();
-    d->acceleration = 0;
-
-    QGestureRecognizer::reset(state);
-}
-
-#endif // QT_NO_NATIVE_GESTURES
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
diff --git a/src/gui/kernel/qwinnativepangesturerecognizer_win_p.h b/src/gui/kernel/qwinnativepangesturerecognizer_win_p.h
deleted file mode 100644 (file)
index 49a66d6..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWINNATIVEPANGESTURERECOGNIZER_WIN_P_H
-#define QWINNATIVEPANGESTURERECOGNIZER_WIN_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 <QGestureRecognizer>
-
-#ifndef QT_NO_GESTURES
-
-QT_BEGIN_NAMESPACE
-
-#if !defined(QT_NO_NATIVE_GESTURES)
-
-class QWinNativePanGestureRecognizer : public QGestureRecognizer
-{
-public:
-    QWinNativePanGestureRecognizer();
-
-    QGesture *create(QObject *target);
-    QGestureRecognizer::Result recognize(QGesture *state, QObject *watched, QEvent *event);
-    void reset(QGesture *state);
-};
-
-#endif // QT_NO_NATIVE_GESTURES
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_GESTURES
-
-#endif // QWINNATIVEPANGESTURERECOGNIZER_WIN_P_H
diff --git a/src/gui/painting/qcolormap_mac.cpp b/src/gui/painting/qcolormap_mac.cpp
deleted file mode 100644 (file)
index 1e10c1e..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qcolormap.h"
-#include "qcolor.h"
-
-QT_BEGIN_NAMESPACE
-
-class QColormapPrivate
-{
-public:
-    inline QColormapPrivate()
-        : ref(1)
-    { }
-
-    QAtomicInt ref;
-};
-static QColormap *qt_mac_global_map = 0;
-
-void QColormap::initialize()
-{
-    qt_mac_global_map = new QColormap;
-}
-
-void QColormap::cleanup()
-{
-    delete qt_mac_global_map;
-    qt_mac_global_map = 0;
-}
-
-QColormap QColormap::instance(int)
-{
-    return *qt_mac_global_map;
-}
-
-QColormap::QColormap() : d(new QColormapPrivate)
-{}
-
-QColormap::QColormap(const QColormap &colormap) :d (colormap.d)
-{ d->ref.ref(); }
-
-QColormap::~QColormap()
-{
-    if (!d->ref.deref())
-        delete d;
-}
-
-QColormap::Mode QColormap::mode() const
-{ return QColormap::Direct; }
-
-int QColormap::depth() const
-{
-    return 32;
-}
-
-int QColormap::size() const
-{
-    return -1;
-}
-
-uint QColormap::pixel(const QColor &color) const
-{ return color.rgba(); }
-
-const QColor QColormap::colorAt(uint pixel) const
-{ return QColor(pixel); }
-
-const QVector<QColor> QColormap::colormap() const
-{ return QVector<QColor>(); }
-
-QColormap &QColormap::operator=(const QColormap &colormap)
-{ qAtomicAssign(d, colormap.d); return *this; }
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qcolormap_win.cpp b/src/gui/painting/qcolormap_win.cpp
deleted file mode 100644 (file)
index 3bc0e53..0000000
+++ /dev/null
@@ -1,201 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qcolor.h"
-#include "qcolormap.h"
-#include "qvector.h"
-#include "qt_windows.h"
-
-#if defined(Q_WS_WINCE)
-#include "qguifunctions_wince.h"
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QColormapPrivate
-{
-public:
-    inline QColormapPrivate()
-        : ref(1), mode(QColormap::Direct), depth(0), hpal(0)
-    { }
-
-    QAtomicInt ref;
-
-    QColormap::Mode mode;
-    int depth;
-    int numcolors;
-
-    HPALETTE hpal;
-    QVector<QColor> palette;
-};
-
-static QColormapPrivate *screenMap = 0;
-
-void QColormap::initialize()
-{
-    HDC dc = qt_win_display_dc();
-
-    screenMap = new QColormapPrivate;
-    screenMap->depth = GetDeviceCaps(dc, BITSPIXEL);
-
-    screenMap->numcolors = -1;
-    if (GetDeviceCaps(dc, RASTERCAPS) & RC_PALETTE)
-        screenMap->numcolors = GetDeviceCaps(dc, SIZEPALETTE);
-
-    if (screenMap->numcolors <= 16 || screenMap->numcolors > 256)        // no need to create palette
-        return;
-
-    LOGPALETTE* pal = 0;
-    int numPalEntries = 6*6*6; // color cube
-
-    pal = (LOGPALETTE*)malloc(sizeof(LOGPALETTE) + numPalEntries * sizeof(PALETTEENTRY));
-    // Make 6x6x6 color cube
-    int idx = 0;
-    for(int ir = 0x0; ir <= 0xff; ir+=0x33) {
-        for(int ig = 0x0; ig <= 0xff; ig+=0x33) {
-            for(int ib = 0x0; ib <= 0xff; ib+=0x33) {
-                pal->palPalEntry[idx].peRed = ir;
-                pal->palPalEntry[idx].peGreen = ig;
-                pal->palPalEntry[idx].peBlue = ib;
-                pal->palPalEntry[idx].peFlags = 0;
-                idx++;
-            }
-        }
-    }
-
-    pal->palVersion = 0x300;
-    pal->palNumEntries = numPalEntries;
-
-    screenMap->hpal = CreatePalette(pal);
-    if (!screenMap->hpal)
-        qErrnoWarning("QColor::initialize: Failed to create logical palette");
-    free (pal);
-
-    SelectPalette(dc, screenMap->hpal, FALSE);
-    RealizePalette(dc);
-
-    PALETTEENTRY paletteEntries[256];
-    screenMap->numcolors = GetPaletteEntries(screenMap->hpal, 0, 255, paletteEntries);
-
-    screenMap->palette.resize(screenMap->numcolors);
-    for (int i = 0; i < screenMap->numcolors; i++) {
-        screenMap->palette[i] = qRgb(paletteEntries[i].peRed,
-                                     paletteEntries[i].peGreen,
-                                     paletteEntries[i].peBlue);
-    }
-}
-
-void QColormap::cleanup()
-{
-    if (!screenMap)
-        return;
-
-    if (screenMap->hpal) {                                // delete application global
-        DeleteObject(screenMap->hpal);                        // palette
-        screenMap->hpal = 0;
-    }
-
-    delete screenMap;
-    screenMap = 0;
-}
-
-QColormap QColormap::instance(int)
-{
-    Q_ASSERT_X(screenMap, "QColormap",
-               "A QApplication object needs to be constructed before QColormap is used.");
-    return QColormap();
-}
-
-QColormap::QColormap()
-    : d(screenMap)
-{ d->ref.ref(); }
-
-QColormap::QColormap(const QColormap &colormap)
-    :d (colormap.d)
-{ d->ref.ref(); }
-
-QColormap::~QColormap()
-{
-    if (!d->ref.deref())
-        delete d;
-}
-
-QColormap::Mode QColormap::mode() const
-{ return d->mode; }
-
-int QColormap::depth() const
-{ return d->depth; }
-
-int QColormap::size() const
-{ return d->numcolors; }
-
-uint QColormap::pixel(const QColor &color) const
-{
-    const QColor c = color.toRgb();
-    COLORREF rgb = RGB(c.red(), c.green(), c.blue());
-    if (d->hpal)
-        return PALETTEINDEX(GetNearestPaletteIndex(d->hpal, rgb));
-    return rgb;
-}
-
-const QColor QColormap::colorAt(uint pixel) const
-{
-    if (d->hpal) {
-        if (pixel < uint(d->numcolors))
-            return d->palette.at(pixel);
-        return QColor();
-    }
-    return QColor(GetRValue(pixel), GetGValue(pixel), GetBValue(pixel));
-}
-
-
-HPALETTE QColormap::hPal()
-{ return screenMap ? screenMap->hpal : 0; }
-
-
-const QVector<QColor> QColormap::colormap() const
-{ return d->palette; }
-
-QColormap &QColormap::operator=(const QColormap &colormap)
-{ qAtomicAssign(d, colormap.d); return *this; }
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qpaintdevice_mac.cpp b/src/gui/painting/qpaintdevice_mac.cpp
deleted file mode 100644 (file)
index a71274f..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qpaintdevice.h"
-#include "qpainter.h"
-#include "qwidget.h"
-#include "qbitmap.h"
-#include "qapplication.h"
-#include "qprinter.h"
-#include <qdebug.h>
-#include <qt_mac_p.h>
-#include <qprintengine_mac_p.h>
-#include <qpixmap_raster_p.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
-  Internal variables and functions
- *****************************************************************************/
-
-/*! \internal */
-float qt_mac_defaultDpi_x()
-{
-    // Mac OS X currently assumes things to be 72 dpi.
-    // (see http://developer.apple.com/releasenotes/GraphicsImaging/RN-ResolutionIndependentUI/)
-    // This may need to be re-worked as we go further in the resolution-independence stuff.
-    return 72;
-}
-
-/*! \internal */
-float qt_mac_defaultDpi_y()
-{
-    // Mac OS X currently assumes things to be 72 dpi.
-    // (see http://developer.apple.com/releasenotes/GraphicsImaging/RN-ResolutionIndependentUI/)
-    // This may need to be re-worked as we go further in the resolution-independence stuff.
-    return 72;
-}
-
-
-/*! \internal
-
-    Returns the QuickDraw CGrafPtr of the paint device. 0 is returned
-    if it can't be obtained. Do not hold the pointer around for long
-    as it can be relocated.
-
-    \warning This function is only available on Mac OS X.
-*/
-
-Q_GUI_EXPORT GrafPtr qt_mac_qd_context(const QPaintDevice *device)
-{
-    if (device->devType() == QInternal::Pixmap) {
-        return static_cast<GrafPtr>(static_cast<const QPixmap *>(device)->macQDHandle());
-    } else if(device->devType() == QInternal::Widget) {
-        return static_cast<GrafPtr>(static_cast<const QWidget *>(device)->macQDHandle());
-    } else if(device->devType() == QInternal::Printer) {
-        QPaintEngine *engine = static_cast<const QPrinter *>(device)->paintEngine();
-        return static_cast<GrafPtr>(static_cast<const QMacPrintEngine *>(engine)->handle());
-    }
-    return 0;
-}
-
-extern CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *pdev);
-
-/*! \internal
-
-    Returns the CoreGraphics CGContextRef of the paint device. 0 is
-    returned if it can't be obtained. It is the caller's responsiblity to
-    CGContextRelease the context when finished using it.
-
-    \warning This function is only available on Mac OS X.
-*/
-
-Q_GUI_EXPORT CGContextRef qt_mac_cg_context(const QPaintDevice *pdev)
-{
-    if (pdev->devType() == QInternal::Pixmap) {
-        const QPixmap *pm = static_cast<const QPixmap*>(pdev);
-        CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pdev);
-        uint flags = kCGImageAlphaPremultipliedFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
-        flags |= kCGBitmapByteOrder32Host;
-#endif
-        CGContextRef ret = 0;
-
-        // It would make sense to put this into a mac #ifdef'ed
-        // virtual function in the QPixmapData at some point
-        if (pm->data->classId() == QPixmapData::RasterClass) {
-            QImage *image = pm->data->buffer();
-            ret = CGBitmapContextCreate(image->bits(), image->width(), image->height(),
-                                        8, image->bytesPerLine(), colorspace, flags);
-        }
-
-        CGContextTranslateCTM(ret, 0, pm->height());
-        CGContextScaleCTM(ret, 1, -1);
-        return ret;
-    } else if (pdev->devType() == QInternal::Widget) {
-        CGContextRef ret = static_cast<CGContextRef>(static_cast<const QWidget *>(pdev)->macCGHandle());
-        CGContextRetain(ret);
-        return ret;
-    } else if (pdev->devType() == QInternal::MacQuartz) {
-        return static_cast<const QMacQuartzPaintDevice *>(pdev)->cgContext();
-    }
-    return 0;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qpaintdevice_win.cpp b/src/gui/painting/qpaintdevice_win.cpp
deleted file mode 100644 (file)
index 89ceb2d..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qpaintdevice.h"
-#include "qpainter.h"
-#include "qwidget.h"
-#include "qbitmap.h"
-#include "qapplication.h"
-#include <qapplication_p.h>
-#include "qt_windows.h"
-#include "qprinter.h"
-
-QT_BEGIN_NAMESPACE
-
-HDC QPaintDevice::getDC() const
-{
-    return 0;
-}
-
-void QPaintDevice::releaseDC(HDC) const
-{
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qpaintengine_mac.cpp b/src/gui/painting/qpaintengine_mac.cpp
deleted file mode 100644 (file)
index c73691e..0000000
+++ /dev/null
@@ -1,1759 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qbitmap.h>
-#include <qpaintdevice.h>
-#include <qpaintengine_mac_p.h>
-#include <qpainterpath.h>
-#include <qpixmapcache.h>
-#include <qpaintengine_raster_p.h>
-#include <qprintengine_mac_p.h>
-#include <qprinter.h>
-#include <qstack.h>
-#include <qtextcodec.h>
-#include <qwidget.h>
-#include <qdebug.h>
-#include <qcoreapplication.h>
-#include <qmath.h>
-#include <qnumeric.h>
-
-#include <qfont_p.h>
-#include <qfontengine_p.h>
-#include <qfontengine_coretext_p.h>
-#include <qfontengine_mac_p.h>
-#include <qnumeric_p.h>
-#include <qpainter_p.h>
-#include <qpainterpath_p.h>
-#include <qt_mac_p.h>
-#include <qtextengine_p.h>
-#include <qwidget_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-
-#include <string.h>
-
-QT_BEGIN_NAMESPACE
-
-extern int qt_antialiasing_threshold; // QApplication.cpp
-
-/*****************************************************************************
-  External functions
- *****************************************************************************/
-extern CGImageRef qt_mac_create_imagemask(const QPixmap &px, const QRectF &sr); //qpixmap_mac.cpp
-extern QPoint qt_mac_posInWindow(const QWidget *w); //qwidget_mac.cpp
-extern OSWindowRef qt_mac_window_for(const QWidget *); //qwidget_mac.cpp
-extern CGContextRef qt_mac_cg_context(const QPaintDevice *); //qpaintdevice_mac.cpp
-extern void qt_mac_dispose_rgn(RgnHandle r); //qregion_mac.cpp
-extern QPixmap qt_pixmapForBrush(int, bool); //qbrush.cpp
-
-void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform);
-
-
-//Implemented for qt_mac_p.h
-QMacCGContext::QMacCGContext(QPainter *p)
-{
-    QPaintEngine *pe = p->paintEngine();
-    if (pe->type() == QPaintEngine::MacPrinter)
-        pe = static_cast<QMacPrintEngine*>(pe)->paintEngine();
-    pe->syncState();
-    context = 0;
-    if(pe->type() == QPaintEngine::CoreGraphics)
-        context = static_cast<QCoreGraphicsPaintEngine*>(pe)->handle();
-
-    int devType = p->device()->devType();
-    if (pe->type() == QPaintEngine::Raster
-            && (devType == QInternal::Widget || devType == QInternal::Pixmap || devType == QInternal::Image)) {
-
-        extern CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice);
-        CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pe->paintDevice());
-        uint flags = kCGImageAlphaPremultipliedFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
-        flags |= kCGBitmapByteOrder32Host;
-#endif
-        const QImage *image = (const QImage *) pe->paintDevice();
-
-        context = CGBitmapContextCreate((void *) image->bits(), image->width(), image->height(),
-                                        8, image->bytesPerLine(), colorspace, flags);
-
-        CGContextTranslateCTM(context, 0, image->height());
-        CGContextScaleCTM(context, 1, -1);
-
-        if (devType == QInternal::Widget) {
-            QRegion clip = p->paintEngine()->systemClip();
-            QTransform native = p->deviceTransform();
-            QTransform logical = p->combinedTransform();
-
-            if (p->hasClipping()) {
-                QRegion r = p->clipRegion();
-                r.translate(native.dx(), native.dy());
-                if (clip.isEmpty())
-                    clip = r;
-                else
-                    clip &= r;
-            }
-            qt_mac_clip_cg(context, clip, 0);
-
-            CGContextTranslateCTM(context, native.dx(), native.dy());
-        }
-    } else {
-        CGContextRetain(context);
-    }
-}
-
-
-/*****************************************************************************
-  QCoreGraphicsPaintEngine utility functions
- *****************************************************************************/
-
-//conversion
-inline static float qt_mac_convert_color_to_cg(int c) { return ((float)c * 1000 / 255) / 1000; }
-inline static int qt_mac_convert_color_from_cg(float c) { return qRound(c * 255); }
-CGAffineTransform qt_mac_convert_transform_to_cg(const QTransform &t) {
-    return CGAffineTransformMake(t.m11(), t.m12(), t.m21(), t.m22(), t.dx(),  t.dy());
-}
-
-CGColorSpaceRef qt_mac_colorSpaceForDeviceType(const QPaintDevice *paintDevice)
-{
-    bool isWidget = (paintDevice->devType() == QInternal::Widget);
-    return QCoreGraphicsPaintEngine::macDisplayColorSpace(isWidget ? static_cast<const QWidget *>(paintDevice)
-                                                                   : 0);
-}
-
-inline static QCFType<CGColorRef> cgColorForQColor(const QColor &col, QPaintDevice *pdev)
-{
-    CGFloat components[] = {
-        qt_mac_convert_color_to_cg(col.red()),
-        qt_mac_convert_color_to_cg(col.green()),
-        qt_mac_convert_color_to_cg(col.blue()),
-        qt_mac_convert_color_to_cg(col.alpha())
-    };
-    return CGColorCreate(qt_mac_colorSpaceForDeviceType(pdev), components);
-}
-
-// There's architectural problems with using native gradients
-// on the Mac at the moment, so disable them.
-// #define QT_MAC_USE_NATIVE_GRADIENTS
-
-#ifdef QT_MAC_USE_NATIVE_GRADIENTS
-static bool drawGradientNatively(const QGradient *gradient)
-{
-    return gradient->spread() == QGradient::PadSpread;
-}
-
-// gradiant callback
-static void qt_mac_color_gradient_function(void *info, const CGFloat *in, CGFloat *out)
-{
-    QBrush *brush = static_cast<QBrush *>(info);
-    Q_ASSERT(brush && brush->gradient());
-
-    const QGradientStops stops = brush->gradient()->stops();
-    const int n = stops.count();
-    Q_ASSERT(n >= 1);
-    const QGradientStop *begin = stops.constBegin();
-    const QGradientStop *end = begin + n;
-
-    qreal p = in[0];
-    const QGradientStop *i = begin;
-    while (i != end && i->first < p)
-        ++i;
-
-    QRgb c;
-    if (i == begin) {
-        c = begin->second.rgba();
-    } else if (i == end) {
-        c = (end - 1)->second.rgba();
-    } else {
-        const QGradientStop &s1 = *(i - 1);
-        const QGradientStop &s2 = *i;
-        qreal p1 = s1.first;
-        qreal p2 = s2.first;
-        QRgb c1 = s1.second.rgba();
-        QRgb c2 = s2.second.rgba();
-        int idist = 256 * (p - p1) / (p2 - p1);
-        int dist = 256 - idist;
-        c = qRgba(INTERPOLATE_PIXEL_256(qRed(c1), dist, qRed(c2), idist),
-                  INTERPOLATE_PIXEL_256(qGreen(c1), dist, qGreen(c2), idist),
-                  INTERPOLATE_PIXEL_256(qBlue(c1), dist, qBlue(c2), idist),
-                  INTERPOLATE_PIXEL_256(qAlpha(c1), dist, qAlpha(c2), idist));
-    }
-
-    out[0] = qt_mac_convert_color_to_cg(qRed(c));
-    out[1] = qt_mac_convert_color_to_cg(qGreen(c));
-    out[2] = qt_mac_convert_color_to_cg(qBlue(c));
-    out[3] = qt_mac_convert_color_to_cg(qAlpha(c));
-}
-#endif
-
-//clipping handling
-void QCoreGraphicsPaintEnginePrivate::resetClip()
-{
-    static bool inReset = false;
-    if (inReset)
-        return;
-    inReset = true;
-
-    CGAffineTransform old_xform = CGContextGetCTM(hd);
-
-    //setup xforms
-    CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
-    while (stackCount > 0) {
-        restoreGraphicsState();
-    }
-    saveGraphicsState();
-    inReset = false;
-    //reset xforms
-    CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
-    CGContextConcatCTM(hd, old_xform);
-}
-
-static CGRect qt_mac_compose_rect(const QRectF &r, float off=0)
-{
-    return CGRectMake(r.x()+off, r.y()+off, r.width(), r.height());
-}
-
-static CGMutablePathRef qt_mac_compose_path(const QPainterPath &p, float off=0)
-{
-    CGMutablePathRef ret = CGPathCreateMutable();
-    QPointF startPt;
-    for (int i=0; i<p.elementCount(); ++i) {
-        const QPainterPath::Element &elm = p.elementAt(i);
-        switch (elm.type) {
-            case QPainterPath::MoveToElement:
-                if(i > 0
-                        && p.elementAt(i - 1).x == startPt.x()
-                        && p.elementAt(i - 1).y == startPt.y())
-                    CGPathCloseSubpath(ret);
-                startPt = QPointF(elm.x, elm.y);
-                CGPathMoveToPoint(ret, 0, elm.x+off, elm.y+off);
-                break;
-            case QPainterPath::LineToElement:
-                CGPathAddLineToPoint(ret, 0, elm.x+off, elm.y+off);
-                break;
-            case QPainterPath::CurveToElement:
-                Q_ASSERT(p.elementAt(i+1).type == QPainterPath::CurveToDataElement);
-                Q_ASSERT(p.elementAt(i+2).type == QPainterPath::CurveToDataElement);
-                CGPathAddCurveToPoint(ret, 0,
-                        elm.x+off, elm.y+off,
-                        p.elementAt(i+1).x+off, p.elementAt(i+1).y+off,
-                        p.elementAt(i+2).x+off, p.elementAt(i+2).y+off);
-                i+=2;
-                break;
-            default:
-                qFatal("QCoreGraphicsPaintEngine::drawPath(), unhandled type: %d", elm.type);
-                break;
-        }
-    }
-    if(!p.isEmpty()
-            && p.elementAt(p.elementCount() - 1).x == startPt.x()
-            && p.elementAt(p.elementCount() - 1).y == startPt.y())
-        CGPathCloseSubpath(ret);
-    return ret;
-}
-
-CGColorSpaceRef QCoreGraphicsPaintEngine::m_genericColorSpace = 0;
-QHash<QWidget*, CGColorSpaceRef> QCoreGraphicsPaintEngine::m_displayColorSpaceHash; // window -> color space
-bool QCoreGraphicsPaintEngine::m_postRoutineRegistered = false;
-
-CGColorSpaceRef QCoreGraphicsPaintEngine::macGenericColorSpace()
-{
-#if 0
-    if (!m_genericColorSpace) {
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
-        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
-            m_genericColorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
-        } else
-#endif
-        {
-            m_genericColorSpace = CGColorSpaceCreateDeviceRGB();
-        }
-        if (!m_postRoutineRegistered) {
-            m_postRoutineRegistered = true;
-            qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
-        }
-    }
-    return m_genericColorSpace;
-#else
-    // Just return the main display colorspace for the moment.
-    return macDisplayColorSpace();
-#endif
-}
-
-CGColorSpaceRef QCoreGraphicsPaintEngine::macDisplayColorSpace(const QWidget *widget)
-{
-    // The color space depends on which screen the widget's window is on.
-    // widget == 0 is a spacial case where we use the main display.
-    QWidget *window = widget ? widget->window() : 0;
-
-    // Check for cached color space and return if found.
-    if (m_displayColorSpaceHash.contains(window))
-        return m_displayColorSpaceHash.value(window);
-
-    // Find which display the window is on.
-    CGDirectDisplayID displayID;
-    if (window == 0) {
-        displayID = CGMainDisplayID();
-    } else {
-        const QRect &qrect = window->geometry();
-        CGRect rect = CGRectMake(qrect.x(), qrect.y(), qrect.width(), qrect.height());
-        CGDisplayCount throwAway;
-        CGDisplayErr dErr = CGGetDisplaysWithRect(rect, 1, &displayID, &throwAway);
-        if (dErr != kCGErrorSuccess)
-            displayID = CGMainDisplayID();
-    }
-
-    // Get the color space from the display profile.
-    CGColorSpaceRef colorSpace = 0;
-    CMProfileRef displayProfile = 0;
-    CMError err = CMGetProfileByAVID((CMDisplayIDType)displayID, &displayProfile);
-    if (err == noErr) {
-        colorSpace = CGColorSpaceCreateWithPlatformColorSpace(displayProfile);
-        CMCloseProfile(displayProfile);
-    }
-
-    // Fallback: use generic DeviceRGB
-    if (colorSpace == 0)
-        colorSpace = CGColorSpaceCreateDeviceRGB();
-
-    // Install cleanup routines
-    if (!m_postRoutineRegistered) {
-        m_postRoutineRegistered = true;
-        qAddPostRoutine(QCoreGraphicsPaintEngine::cleanUpMacColorSpaces);
-    }
-
-    // Cache and return.
-    m_displayColorSpaceHash.insert(window, colorSpace);
-    return colorSpace;
-}
-
-void QCoreGraphicsPaintEngine::cleanUpMacColorSpaces()
-{
-    if (m_genericColorSpace) {
-        CFRelease(m_genericColorSpace);
-        m_genericColorSpace = 0;
-    }
-    QHash<QWidget*, CGColorSpaceRef>::const_iterator it = m_displayColorSpaceHash.constBegin();
-    while (it != m_displayColorSpaceHash.constEnd()) {
-        if (it.value())
-            CFRelease(it.value());
-        ++it;
-    }
-    m_displayColorSpaceHash.clear();
-}
-
-void qt_mac_clip_cg(CGContextRef hd, const QRegion &rgn, CGAffineTransform *orig_xform)
-{
-    CGAffineTransform old_xform = CGAffineTransformIdentity;
-    if(orig_xform) { //setup xforms
-        old_xform = CGContextGetCTM(hd);
-        CGContextConcatCTM(hd, CGAffineTransformInvert(old_xform));
-        CGContextConcatCTM(hd, *orig_xform);
-    }
-
-    //do the clipping
-    CGContextBeginPath(hd);
-    if(rgn.isEmpty()) {
-        CGContextAddRect(hd, CGRectMake(0, 0, 0, 0));
-    } else {
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-            QCFType<HIMutableShapeRef> shape = rgn.toHIMutableShape();
-            Q_ASSERT(!HIShapeIsEmpty(shape));
-            HIShapeReplacePathInCGContext(shape, hd);
-        } else
-#endif
-        {
-            QVector<QRect> rects = rgn.rects();
-            const int count = rects.size();
-            for(int i = 0; i < count; i++) {
-                const QRect &r = rects[i];
-                CGRect mac_r = CGRectMake(r.x(), r.y(), r.width(), r.height());
-                CGContextAddRect(hd, mac_r);
-            }
-        }
-
-    }
-    CGContextClip(hd);
-
-    if(orig_xform) {//reset xforms
-        CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
-        CGContextConcatCTM(hd, old_xform);
-    }
-}
-
-
-//pattern handling (tiling)
-#if 1
-#  define QMACPATTERN_MASK_MULTIPLIER 32
-#else
-#  define QMACPATTERN_MASK_MULTIPLIER 1
-#endif
-class QMacPattern
-{
-public:
-    QMacPattern() : as_mask(false), pdev(0), image(0) { data.bytes = 0; }
-    ~QMacPattern() { CGImageRelease(image); }
-    int width() {
-        if(image)
-            return CGImageGetWidth(image);
-        if(data.bytes)
-            return 8*QMACPATTERN_MASK_MULTIPLIER;
-        return data.pixmap.width();
-    }
-    int height() {
-        if(image)
-            return CGImageGetHeight(image);
-        if(data.bytes)
-            return 8*QMACPATTERN_MASK_MULTIPLIER;
-        return data.pixmap.height();
-    }
-
-    //input
-    QColor foreground;
-    bool as_mask;
-    struct {
-        QPixmap pixmap;
-        const uchar *bytes;
-    } data;
-    QPaintDevice *pdev;
-    //output
-    CGImageRef image;
-};
-static void qt_mac_draw_pattern(void *info, CGContextRef c)
-{
-    QMacPattern *pat = (QMacPattern*)info;
-    int w = 0, h = 0;
-    bool isBitmap = (pat->data.pixmap.depth() == 1);
-    if(!pat->image) { //lazy cache
-        if(pat->as_mask) {
-            Q_ASSERT(pat->data.bytes);
-            w = h = 8;
-#if (QMACPATTERN_MASK_MULTIPLIER == 1)
-            CGDataProviderRef provider = CGDataProviderCreateWithData(0, pat->data.bytes, w*h, 0);
-            pat->image = CGImageMaskCreate(w, h, 1, 1, 1, provider, 0, false);
-            CGDataProviderRelease(provider);
-#else
-            const int numBytes = (w*h)/sizeof(uchar);
-            uchar xor_bytes[numBytes];
-            for(int i = 0; i < numBytes; ++i)
-                xor_bytes[i] = pat->data.bytes[i] ^ 0xFF;
-            CGDataProviderRef provider = CGDataProviderCreateWithData(0, xor_bytes, w*h, 0);
-            CGImageRef swatch = CGImageMaskCreate(w, h, 1, 1, 1, provider, 0, false);
-            CGDataProviderRelease(provider);
-
-            const QColor c0(0, 0, 0, 0), c1(255, 255, 255, 255);
-            QPixmap pm(w*QMACPATTERN_MASK_MULTIPLIER, h*QMACPATTERN_MASK_MULTIPLIER);
-            pm.fill(c0);
-            CGContextRef pm_ctx = qt_mac_cg_context(&pm);
-            CGContextSetFillColorWithColor(c, cgColorForQColor(c1, pat->pdev));
-            CGRect rect = CGRectMake(0, 0, w, h);
-            for(int x = 0; x < QMACPATTERN_MASK_MULTIPLIER; ++x) {
-                rect.origin.x = x * w;
-                for(int y = 0; y < QMACPATTERN_MASK_MULTIPLIER; ++y) {
-                    rect.origin.y = y * h;
-                    qt_mac_drawCGImage(pm_ctx, &rect, swatch);
-                }
-            }
-            pat->image = qt_mac_create_imagemask(pm, pm.rect());
-            CGImageRelease(swatch);
-            CGContextRelease(pm_ctx);
-            w *= QMACPATTERN_MASK_MULTIPLIER;
-            h *= QMACPATTERN_MASK_MULTIPLIER;
-#endif
-        } else {
-            w = pat->data.pixmap.width();
-            h = pat->data.pixmap.height();
-            if (isBitmap)
-                pat->image = qt_mac_create_imagemask(pat->data.pixmap, pat->data.pixmap.rect());
-            else
-                pat->image = (CGImageRef)pat->data.pixmap.macCGHandle();
-        }
-    } else {
-        w = CGImageGetWidth(pat->image);
-        h = CGImageGetHeight(pat->image);
-    }
-
-    //draw
-    bool needRestore = false;
-    if (CGImageIsMask(pat->image)) {
-        CGContextSaveGState(c);
-        CGContextSetFillColorWithColor(c, cgColorForQColor(pat->foreground, pat->pdev));
-    }
-    CGRect rect = CGRectMake(0, 0, w, h);
-    qt_mac_drawCGImage(c, &rect, pat->image);
-    if(needRestore)
-        CGContextRestoreGState(c);
-}
-static void qt_mac_dispose_pattern(void *info)
-{
-    QMacPattern *pat = (QMacPattern*)info;
-    delete pat;
-}
-
-/*****************************************************************************
-  QCoreGraphicsPaintEngine member functions
- *****************************************************************************/
-
-inline static QPaintEngine::PaintEngineFeatures qt_mac_cg_features()
-{
-    return QPaintEngine::PaintEngineFeatures(QPaintEngine::AllFeatures & ~QPaintEngine::PaintOutsidePaintEvent
-                                              & ~QPaintEngine::PerspectiveTransform
-                                              & ~QPaintEngine::ConicalGradientFill
-                                              & ~QPaintEngine::LinearGradientFill
-                                              & ~QPaintEngine::RadialGradientFill
-                                              & ~QPaintEngine::BrushStroke);
-}
-
-QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine()
-: QPaintEngine(*(new QCoreGraphicsPaintEnginePrivate), qt_mac_cg_features())
-{
-}
-
-QCoreGraphicsPaintEngine::QCoreGraphicsPaintEngine(QPaintEnginePrivate &dptr)
-: QPaintEngine(dptr, qt_mac_cg_features())
-{
-}
-
-QCoreGraphicsPaintEngine::~QCoreGraphicsPaintEngine()
-{
-}
-
-bool
-QCoreGraphicsPaintEngine::begin(QPaintDevice *pdev)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    if(isActive()) {                         // already active painting
-        qWarning("QCoreGraphicsPaintEngine::begin: Painter already active");
-        return false;
-    }
-
-    //initialization
-    d->pdev = pdev;
-    d->complexXForm = false;
-    d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
-    d->cosmeticPenSize = 1;
-    d->current.clipEnabled = false;
-    d->pixelSize = QPoint(1,1);
-    d->hd = qt_mac_cg_context(pdev);
-    if(d->hd) {
-        d->saveGraphicsState();
-        d->orig_xform = CGContextGetCTM(d->hd);
-        if (d->shading) {
-            CGShadingRelease(d->shading);
-            d->shading = 0;
-        }
-        d->setClip(0);  //clear the context's clipping
-    }
-
-    setActive(true);
-
-    if(d->pdev->devType() == QInternal::Widget) {                    // device is a widget
-        QWidget *w = (QWidget*)d->pdev;
-        bool unclipped = w->testAttribute(Qt::WA_PaintUnclipped);
-
-        if((w->windowType() == Qt::Desktop)) {
-            if(!unclipped)
-                qWarning("QCoreGraphicsPaintEngine::begin: Does not support clipped desktop on Mac OS X");
-            // ## need to do [qt_mac_window_for(w) makeKeyAndOrderFront]; (need to rename the file)
-        } else if(unclipped) {
-            qWarning("QCoreGraphicsPaintEngine::begin: Does not support unclipped painting");
-        }
-    } else if(d->pdev->devType() == QInternal::Pixmap) {             // device is a pixmap
-        QPixmap *pm = (QPixmap*)d->pdev;
-        if(pm->isNull()) {
-            qWarning("QCoreGraphicsPaintEngine::begin: Cannot paint null pixmap");
-            end();
-            return false;
-        }
-    }
-
-    setDirty(QPaintEngine::DirtyPen);
-    setDirty(QPaintEngine::DirtyBrush);
-    setDirty(QPaintEngine::DirtyBackground);
-    setDirty(QPaintEngine::DirtyHints);
-    return true;
-}
-
-bool
-QCoreGraphicsPaintEngine::end()
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    setActive(false);
-    if(d->pdev->devType() == QInternal::Widget && static_cast<QWidget*>(d->pdev)->windowType() == Qt::Desktop) {
-#ifndef QT_MAC_USE_COCOA
-        HideWindow(qt_mac_window_for(static_cast<QWidget*>(d->pdev)));
-#else
-//        // ### need to do [qt_mac_window_for(static_cast<QWidget *>(d->pdev)) orderOut]; (need to rename)
-#endif
-
-       }
-    if(d->shading) {
-        CGShadingRelease(d->shading);
-        d->shading = 0;
-    }
-    d->pdev = 0;
-    if(d->hd) {
-        d->restoreGraphicsState();
-        CGContextSynchronize(d->hd);
-        CGContextRelease(d->hd);
-        d->hd = 0;
-    }
-    return true;
-}
-
-void
-QCoreGraphicsPaintEngine::updateState(const QPaintEngineState &state)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    QPaintEngine::DirtyFlags flags = state.state();
-
-    if (flags & DirtyTransform)
-        updateMatrix(state.transform());
-
-    if (flags & DirtyClipEnabled) {
-        if (state.isClipEnabled())
-            updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
-        else
-            updateClipPath(QPainterPath(), Qt::NoClip);
-    }
-
-    if (flags & DirtyClipPath) {
-        updateClipPath(state.clipPath(), state.clipOperation());
-    } else if (flags & DirtyClipRegion) {
-        updateClipRegion(state.clipRegion(), state.clipOperation());
-    }
-
-    // If the clip has changed we need to update all other states
-    // too, since they are included in the system context on OSX,
-    // and changing the clip resets that context back to scratch.
-    if (flags & (DirtyClipPath | DirtyClipRegion | DirtyClipEnabled))
-        flags |= AllDirty;
-
-    if (flags & DirtyPen)
-        updatePen(state.pen());
-    if (flags & (DirtyBrush|DirtyBrushOrigin))
-        updateBrush(state.brush(), state.brushOrigin());
-    if (flags & DirtyFont)
-        updateFont(state.font());
-    if (flags & DirtyOpacity)
-        updateOpacity(state.opacity());
-    if (flags & DirtyHints)
-        updateRenderHints(state.renderHints());
-    if (flags & DirtyCompositionMode)
-        updateCompositionMode(state.compositionMode());
-
-    if (flags & (DirtyPen | DirtyTransform)) {
-        if (!d->current.pen.isCosmetic()) {
-            d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticNone;
-        } else if (d->current.transform.m11() < d->current.transform.m22()-1.0 ||
-                  d->current.transform.m11() > d->current.transform.m22()+1.0) {
-            d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticTransformPath;
-            d->cosmeticPenSize = d->adjustPenWidth(d->current.pen.widthF());
-            if (!d->cosmeticPenSize)
-                d->cosmeticPenSize = 1.0;
-        } else {
-            d->cosmeticPen = QCoreGraphicsPaintEnginePrivate::CosmeticSetPenWidth;
-            static const float sqrt2 = sqrt(2);
-            qreal width = d->current.pen.widthF();
-            if (!width)
-                width = 1;
-            d->cosmeticPenSize = sqrt(pow(d->pixelSize.y(), 2) + pow(d->pixelSize.x(), 2)) / sqrt2 * width;
-        }
-    }
-}
-
-void
-QCoreGraphicsPaintEngine::updatePen(const QPen &pen)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-    d->current.pen = pen;
-    d->setStrokePen(pen);
-}
-
-void
-QCoreGraphicsPaintEngine::updateBrush(const QBrush &brush, const QPointF &brushOrigin)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-    d->current.brush = brush;
-
-#ifdef QT_MAC_USE_NATIVE_GRADIENTS
-    // Quartz supports only pad spread
-    if (const QGradient *gradient = brush.gradient()) {
-        if (drawGradientNatively(gradient)) {
-            gccaps |= QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill;
-        } else {
-            gccaps &= ~(QPaintEngine::LinearGradientFill | QPaintEngine::RadialGradientFill);
-        }
-    }
-#endif
-
-    if (d->shading) {
-        CGShadingRelease(d->shading);
-        d->shading = 0;
-    }
-    d->setFillBrush(brushOrigin);
-}
-
-void
-QCoreGraphicsPaintEngine::updateOpacity(qreal opacity)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    CGContextSetAlpha(d->hd, opacity);
-}
-
-void
-QCoreGraphicsPaintEngine::updateFont(const QFont &)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-    updatePen(d->current.pen);
-}
-
-void
-QCoreGraphicsPaintEngine::updateMatrix(const QTransform &transform)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (qIsNaN(transform.m11()) || qIsNaN(transform.m12()) || qIsNaN(transform.m13())
-       || qIsNaN(transform.m21()) || qIsNaN(transform.m22()) || qIsNaN(transform.m23())
-       || qIsNaN(transform.m31()) || qIsNaN(transform.m32()) || qIsNaN(transform.m33()))
-       return;
-
-    d->current.transform = transform;
-    d->setTransform(transform.isIdentity() ? 0 : &transform);
-    d->complexXForm = (transform.m11() != 1 || transform.m22() != 1
-            || transform.m12() != 0 || transform.m21() != 0);
-    d->pixelSize = d->devicePixelSize(d->hd);
-}
-
-void
-QCoreGraphicsPaintEngine::updateClipPath(const QPainterPath &p, Qt::ClipOperation op)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-    if(op == Qt::NoClip) {
-        if(d->current.clipEnabled) {
-            d->current.clipEnabled = false;
-            d->current.clip = QRegion();
-            d->setClip(0);
-        }
-    } else {
-        if(!d->current.clipEnabled)
-            op = Qt::ReplaceClip;
-        d->current.clipEnabled = true;
-        QRegion clipRegion(p.toFillPolygon().toPolygon(), p.fillRule());
-        if(op == Qt::ReplaceClip) {
-            d->current.clip = clipRegion;
-            d->setClip(0);
-            if(p.isEmpty()) {
-                CGRect rect = CGRectMake(0, 0, 0, 0);
-                CGContextClipToRect(d->hd, rect);
-            } else {
-                CGMutablePathRef path = qt_mac_compose_path(p);
-                CGContextBeginPath(d->hd);
-                CGContextAddPath(d->hd, path);
-                if(p.fillRule() == Qt::WindingFill)
-                    CGContextClip(d->hd);
-                else
-                    CGContextEOClip(d->hd);
-                CGPathRelease(path);
-            }
-        } else if(op == Qt::IntersectClip) {
-            d->current.clip = d->current.clip.intersected(clipRegion);
-            d->setClip(&d->current.clip);
-        } else if(op == Qt::UniteClip) {
-            d->current.clip = d->current.clip.united(clipRegion);
-            d->setClip(&d->current.clip);
-        }
-    }
-}
-
-void
-QCoreGraphicsPaintEngine::updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-    if(op == Qt::NoClip) {
-        d->current.clipEnabled = false;
-        d->current.clip = QRegion();
-        d->setClip(0);
-    } else {
-        if(!d->current.clipEnabled)
-            op = Qt::ReplaceClip;
-        d->current.clipEnabled = true;
-        if(op == Qt::IntersectClip)
-            d->current.clip = d->current.clip.intersected(clipRegion);
-        else if(op == Qt::ReplaceClip)
-            d->current.clip = clipRegion;
-        else if(op == Qt::UniteClip)
-            d->current.clip = d->current.clip.united(clipRegion);
-        d->setClip(&d->current.clip);
-    }
-}
-
-void
-QCoreGraphicsPaintEngine::drawPath(const QPainterPath &p)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    CGMutablePathRef path = qt_mac_compose_path(p);
-    uchar ops = QCoreGraphicsPaintEnginePrivate::CGStroke;
-    if(p.fillRule() == Qt::WindingFill)
-        ops |= QCoreGraphicsPaintEnginePrivate::CGFill;
-    else
-        ops |= QCoreGraphicsPaintEnginePrivate::CGEOFill;
-    CGContextBeginPath(d->hd);
-    d->drawPath(ops, path);
-    CGPathRelease(path);
-}
-
-void
-QCoreGraphicsPaintEngine::drawRects(const QRectF *rects, int rectCount)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    for (int i=0; i<rectCount; ++i) {
-        QRectF r = rects[i];
-
-        CGMutablePathRef path = CGPathCreateMutable();
-        CGPathAddRect(path, 0, qt_mac_compose_rect(r));
-        d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill|QCoreGraphicsPaintEnginePrivate::CGStroke,
-                path);
-        CGPathRelease(path);
-    }
-}
-
-void
-QCoreGraphicsPaintEngine::drawPoints(const QPointF *points, int pointCount)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    if (d->current.pen.capStyle() == Qt::FlatCap)
-        CGContextSetLineCap(d->hd, kCGLineCapSquare);
-
-    CGMutablePathRef path = CGPathCreateMutable();
-    for(int i=0; i < pointCount; i++) {
-        float x = points[i].x(), y = points[i].y();
-        CGPathMoveToPoint(path, 0, x, y);
-        CGPathAddLineToPoint(path, 0, x+0.001, y);
-    }
-
-    bool doRestore = false;
-    if(d->cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticNone && !(state->renderHints() & QPainter::Antialiasing)) {
-        //we don't want adjusted pens for point rendering
-        doRestore = true;
-        d->saveGraphicsState();
-        CGContextSetLineWidth(d->hd, d->current.pen.widthF());
-    }
-    d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
-    if (doRestore)
-        d->restoreGraphicsState();
-    CGPathRelease(path);
-    if (d->current.pen.capStyle() == Qt::FlatCap)
-        CGContextSetLineCap(d->hd, kCGLineCapButt);
-}
-
-void
-QCoreGraphicsPaintEngine::drawEllipse(const QRectF &r)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    CGMutablePathRef path = CGPathCreateMutable();
-    CGAffineTransform transform = CGAffineTransformMakeScale(r.width() / r.height(), 1);
-    CGPathAddArc(path, &transform,(r.x() + (r.width() / 2)) / (r.width() / r.height()),
-            r.y() + (r.height() / 2), r.height() / 2, 0, (2 * M_PI), false);
-    d->drawPath(QCoreGraphicsPaintEnginePrivate::CGFill | QCoreGraphicsPaintEnginePrivate::CGStroke,
-            path);
-    CGPathRelease(path);
-}
-
-void
-QCoreGraphicsPaintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    CGMutablePathRef path = CGPathCreateMutable();
-    CGPathMoveToPoint(path, 0, points[0].x(), points[0].y());
-    for(int x = 1; x < pointCount; ++x)
-        CGPathAddLineToPoint(path, 0, points[x].x(), points[x].y());
-    if(mode != PolylineMode && points[0] != points[pointCount-1])
-        CGPathAddLineToPoint(path, 0, points[0].x(), points[0].y());
-    uint op = QCoreGraphicsPaintEnginePrivate::CGStroke;
-    if (mode != PolylineMode)
-        op |= mode == OddEvenMode ? QCoreGraphicsPaintEnginePrivate::CGEOFill
-            : QCoreGraphicsPaintEnginePrivate::CGFill;
-    d->drawPath(op, path);
-    CGPathRelease(path);
-}
-
-void
-QCoreGraphicsPaintEngine::drawLines(const QLineF *lines, int lineCount)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    CGMutablePathRef path = CGPathCreateMutable();
-    for(int i = 0; i < lineCount; i++) {
-        const QPointF start = lines[i].p1(), end = lines[i].p2();
-        CGPathMoveToPoint(path, 0, start.x(), start.y());
-        CGPathAddLineToPoint(path, 0, end.x(), end.y());
-    }
-    d->drawPath(QCoreGraphicsPaintEnginePrivate::CGStroke, path);
-    CGPathRelease(path);
-}
-
-void QCoreGraphicsPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    if(pm.isNull())
-        return;
-
-    bool differentSize = (QRectF(0, 0, pm.width(), pm.height()) != sr), doRestore = false;
-    CGRect rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
-    QCFType<CGImageRef> image;
-    bool isBitmap = (pm.depth() == 1);
-    if (isBitmap) {
-        doRestore = true;
-        d->saveGraphicsState();
-
-        const QColor &col = d->current.pen.color();
-        CGContextSetFillColorWithColor(d->hd, cgColorForQColor(col, d->pdev));
-        image = qt_mac_create_imagemask(pm, sr);
-    } else if (differentSize) {
-        QCFType<CGImageRef> img = pm.toMacCGImageRef();
-        image = CGImageCreateWithImageInRect(img, CGRectMake(qRound(sr.x()), qRound(sr.y()), qRound(sr.width()), qRound(sr.height())));
-    } else {
-        image = (CGImageRef)pm.macCGHandle();
-    }
-    qt_mac_drawCGImage(d->hd, &rect, image);
-    if (doRestore)
-        d->restoreGraphicsState();
-}
-
-static void drawImageReleaseData (void *info, const void *, size_t)
-{
-    delete static_cast<QImage *>(info);
-}
-
-CGImageRef qt_mac_createCGImageFromQImage(const QImage &img, const QImage **imagePtr = 0)
-{
-    QImage *image;
-    if (img.depth() != 32)
-        image = new QImage(img.convertToFormat(QImage::Format_ARGB32_Premultiplied));
-    else
-        image = new QImage(img);
-
-    uint cgflags = kCGImageAlphaNone;
-    switch (image->format()) {
-    case QImage::Format_ARGB32_Premultiplied:
-        cgflags = kCGImageAlphaPremultipliedFirst;
-        break;
-    case QImage::Format_ARGB32:
-        cgflags = kCGImageAlphaFirst;
-        break;
-    case QImage::Format_RGB32:
-        cgflags = kCGImageAlphaNoneSkipFirst;
-    default:
-        break;
-    }
-#if defined(kCGBitmapByteOrder32Host) //only needed because CGImage.h added symbols in the minor version
-    cgflags |= kCGBitmapByteOrder32Host;
-#endif
-    QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(image,
-                                                          static_cast<const QImage *>(image)->bits(),
-                                                          image->byteCount(),
-                                                          drawImageReleaseData);
-    if (imagePtr)
-        *imagePtr = image;
-    return CGImageCreate(image->width(), image->height(), 8, 32,
-                                        image->bytesPerLine(),
-                                        QCoreGraphicsPaintEngine::macGenericColorSpace(),
-                                        cgflags, dataProvider, 0, false, kCGRenderingIntentDefault);
-
-}
-
-void QCoreGraphicsPaintEngine::drawImage(const QRectF &r, const QImage &img, const QRectF &sr,
-                                         Qt::ImageConversionFlags flags)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_UNUSED(flags);
-    Q_ASSERT(isActive());
-
-    if (img.isNull() || state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    const QImage *image;
-    QCFType<CGImageRef> cgimage = qt_mac_createCGImageFromQImage(img, &image);
-    CGRect rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
-    if (QRectF(0, 0, img.width(), img.height()) != sr)
-        cgimage = CGImageCreateWithImageInRect(cgimage, CGRectMake(sr.x(), sr.y(),
-                                               sr.width(), sr.height()));
-    qt_mac_drawCGImage(d->hd, &rect, cgimage);
-}
-
-void QCoreGraphicsPaintEngine::initialize()
-{
-}
-
-void QCoreGraphicsPaintEngine::cleanup()
-{
-}
-
-void QCoreGraphicsPaintEngine::clearColorSpace(QWidget* w)
-{
-    m_displayColorSpaceHash.remove(w);
-}
-
-CGContextRef
-QCoreGraphicsPaintEngine::handle() const
-{
-    return d_func()->hd;
-}
-
-void
-QCoreGraphicsPaintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap,
-        const QPointF &p)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    Q_ASSERT(isActive());
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    //save the old state
-    d->saveGraphicsState();
-
-    //setup the pattern
-    QMacPattern *qpattern = new QMacPattern;
-    qpattern->data.pixmap = pixmap;
-    qpattern->foreground = d->current.pen.color();
-    qpattern->pdev = d->pdev;
-    CGPatternCallbacks callbks;
-    callbks.version = 0;
-    callbks.drawPattern = qt_mac_draw_pattern;
-    callbks.releaseInfo = qt_mac_dispose_pattern;
-    const int width = qpattern->width(), height = qpattern->height();
-    CGAffineTransform trans = CGContextGetCTM(d->hd);
-    CGPatternRef pat = CGPatternCreate(qpattern, CGRectMake(0, 0, width, height),
-            trans, width, height,
-            kCGPatternTilingNoDistortion, true, &callbks);
-    CGColorSpaceRef cs = CGColorSpaceCreatePattern(0);
-    CGContextSetFillColorSpace(d->hd, cs);
-    CGFloat component = 1.0; //just one
-    CGContextSetFillPattern(d->hd, pat, &component);
-    CGSize phase = CGSizeApplyAffineTransform(CGSizeMake(-(p.x()-r.x()), -(p.y()-r.y())), trans);
-    CGContextSetPatternPhase(d->hd, phase);
-
-    //fill the rectangle
-    CGRect mac_rect = CGRectMake(r.x(), r.y(), r.width(), r.height());
-    CGContextFillRect(d->hd, mac_rect);
-
-    //restore the state
-    d->restoreGraphicsState();
-    //cleanup
-    CGColorSpaceRelease(cs);
-    CGPatternRelease(pat);
-}
-
-void QCoreGraphicsPaintEngine::drawTextItem(const QPointF &pos, const QTextItem &item)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    if (d->current.transform.type() == QTransform::TxProject
-#ifndef QMAC_NATIVE_GRADIENTS
-        || painter()->pen().brush().gradient()  //Just let the base engine "emulate" the gradient
-#endif
-        ) {
-        QPaintEngine::drawTextItem(pos, item);
-        return;
-    }
-
-    if (state->compositionMode() == QPainter::CompositionMode_Destination)
-        return;
-
-    const QTextItemInt &ti = static_cast<const QTextItemInt &>(item);
-
-    QPen oldPen = painter()->pen();
-    QBrush oldBrush = painter()->brush();
-    QPointF oldBrushOrigin = painter()->brushOrigin();
-    updatePen(Qt::NoPen);
-    updateBrush(oldPen.brush(), QPointF(0, 0));
-
-    Q_ASSERT(type() == QPaintEngine::CoreGraphics);
-
-    QFontEngine *fe = ti.fontEngine;
-
-    const bool textAA = state->renderHints() & QPainter::TextAntialiasing && fe->fontDef.pointSize > qt_antialiasing_threshold && !(fe->fontDef.styleStrategy & QFont::NoAntialias);
-    const bool lineAA = state->renderHints() & QPainter::Antialiasing;
-    if(textAA != lineAA)
-        CGContextSetShouldAntialias(d->hd, textAA);
-
-    if (ti.glyphs.numGlyphs) {
-        switch (fe->type()) {
-        case QFontEngine::Mac:
-#ifdef QT_MAC_USE_COCOA
-            static_cast<QCoreTextFontEngine *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
-#else
-            static_cast<QFontEngineMac *>(fe)->draw(d->hd, pos.x(), pos.y(), ti, paintDevice()->height());
-#endif
-            break;
-        case QFontEngine::Box:
-            d->drawBoxTextItem(pos, ti);
-            break;
-        default:
-            break;
-        }
-    }
-
-    if(textAA != lineAA)
-        CGContextSetShouldAntialias(d->hd, !textAA);
-
-    updatePen(oldPen);
-    updateBrush(oldBrush, oldBrushOrigin);
-}
-
-QPainter::RenderHints
-QCoreGraphicsPaintEngine::supportedRenderHints() const
-{
-    return QPainter::RenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
-}
-enum CGCompositeMode {
-        kCGCompositeModeClear            = 0,
-        kCGCompositeModeCopy             = 1,
-        kCGCompositeModeSourceOver       = 2,
-        kCGCompositeModeSourceIn         = 3,
-        kCGCompositeModeSourceOut        = 4,
-        kCGCompositeModeSourceAtop       = 5,
-        kCGCompositeModeDestinationOver  = 6,
-        kCGCompositeModeDestinationIn    = 7,
-        kCGCompositeModeDestinationOut   = 8,
-        kCGCompositeModeDestinationAtop  = 9,
-        kCGCompositeModeXOR              = 10,
-        kCGCompositeModePlusDarker       = 11, // (max (0, (1-d) + (1-s)))
-        kCGCompositeModePlusLighter      = 12, // (min (1, s + d))
-    };
-extern "C" {
-    extern void CGContextSetCompositeOperation(CGContextRef, int);
-} // private function, but is in all versions of OS X.
-void
-QCoreGraphicsPaintEngine::updateCompositionMode(QPainter::CompositionMode mode)
-{
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-        int cg_mode = kCGBlendModeNormal;
-        switch(mode) {
-        case QPainter::CompositionMode_Multiply:
-            cg_mode = kCGBlendModeMultiply;
-            break;
-        case QPainter::CompositionMode_Screen:
-            cg_mode = kCGBlendModeScreen;
-            break;
-        case QPainter::CompositionMode_Overlay:
-            cg_mode = kCGBlendModeOverlay;
-            break;
-        case QPainter::CompositionMode_Darken:
-            cg_mode = kCGBlendModeDarken;
-            break;
-        case QPainter::CompositionMode_Lighten:
-            cg_mode = kCGBlendModeLighten;
-            break;
-        case QPainter::CompositionMode_ColorDodge:
-            cg_mode = kCGBlendModeColorDodge;
-            break;
-        case QPainter::CompositionMode_ColorBurn:
-            cg_mode = kCGBlendModeColorBurn;
-            break;
-        case QPainter::CompositionMode_HardLight:
-            cg_mode = kCGBlendModeHardLight;
-            break;
-        case QPainter::CompositionMode_SoftLight:
-            cg_mode = kCGBlendModeSoftLight;
-            break;
-        case QPainter::CompositionMode_Difference:
-            cg_mode = kCGBlendModeDifference;
-            break;
-        case QPainter::CompositionMode_Exclusion:
-            cg_mode = kCGBlendModeExclusion;
-            break;
-        case QPainter::CompositionMode_Plus:
-            cg_mode = kCGBlendModePlusLighter;
-            break;
-        case QPainter::CompositionMode_SourceOver:
-            cg_mode = kCGBlendModeNormal;
-            break;
-        case QPainter::CompositionMode_DestinationOver:
-            cg_mode = kCGBlendModeDestinationOver;
-            break;
-        case QPainter::CompositionMode_Clear:
-            cg_mode = kCGBlendModeClear;
-            break;
-        case QPainter::CompositionMode_Source:
-            cg_mode = kCGBlendModeCopy;
-            break;
-        case QPainter::CompositionMode_Destination:
-            cg_mode = -1;
-            break;
-        case QPainter::CompositionMode_SourceIn:
-            cg_mode = kCGBlendModeSourceIn;
-            break;
-        case QPainter::CompositionMode_DestinationIn:
-            cg_mode = kCGCompositeModeDestinationIn;
-            break;
-        case QPainter::CompositionMode_SourceOut:
-            cg_mode = kCGBlendModeSourceOut;
-            break;
-        case QPainter::CompositionMode_DestinationOut:
-            cg_mode = kCGBlendModeDestinationOver;
-            break;
-        case QPainter::CompositionMode_SourceAtop:
-            cg_mode = kCGBlendModeSourceAtop;
-            break;
-        case QPainter::CompositionMode_DestinationAtop:
-            cg_mode = kCGBlendModeDestinationAtop;
-            break;
-        case QPainter::CompositionMode_Xor:
-            cg_mode = kCGBlendModeXOR;
-            break;
-        default:
-            break;
-        }
-        if (cg_mode > -1) {
-            CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
-        }
-    } else
-#endif
-    // The standard porter duff ops.
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_3
-            && mode <= QPainter::CompositionMode_Xor) {
-        int cg_mode = kCGCompositeModeCopy;
-        switch (mode) {
-        case QPainter::CompositionMode_SourceOver:
-            cg_mode = kCGCompositeModeSourceOver;
-            break;
-        case QPainter::CompositionMode_DestinationOver:
-            cg_mode = kCGCompositeModeDestinationOver;
-            break;
-        case QPainter::CompositionMode_Clear:
-            cg_mode = kCGCompositeModeClear;
-            break;
-        default:
-            qWarning("QCoreGraphicsPaintEngine: Unhandled composition mode %d", (int)mode);
-            break;
-        case QPainter::CompositionMode_Source:
-            cg_mode = kCGCompositeModeCopy;
-            break;
-        case QPainter::CompositionMode_Destination:
-            cg_mode = CGCompositeMode(-1);
-            break;
-        case QPainter::CompositionMode_SourceIn:
-            cg_mode = kCGCompositeModeSourceIn;
-            break;
-        case QPainter::CompositionMode_DestinationIn:
-            cg_mode = kCGCompositeModeDestinationIn;
-            break;
-        case QPainter::CompositionMode_SourceOut:
-            cg_mode = kCGCompositeModeSourceOut;
-            break;
-        case QPainter::CompositionMode_DestinationOut:
-            cg_mode = kCGCompositeModeDestinationOut;
-            break;
-        case QPainter::CompositionMode_SourceAtop:
-            cg_mode = kCGCompositeModeSourceAtop;
-            break;
-        case QPainter::CompositionMode_DestinationAtop:
-            cg_mode = kCGCompositeModeDestinationAtop;
-            break;
-        case QPainter::CompositionMode_Xor:
-            cg_mode = kCGCompositeModeXOR;
-            break;
-        }
-        if (cg_mode > -1)
-            CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
-    } else {
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
-        bool needPrivateAPI = false;
-        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4) {
-            int cg_mode = kCGBlendModeNormal;
-            switch (mode) {
-            case QPainter::CompositionMode_Multiply:
-                cg_mode = kCGBlendModeMultiply;
-                break;
-            case QPainter::CompositionMode_Screen:
-                cg_mode = kCGBlendModeScreen;
-                break;
-            case QPainter::CompositionMode_Overlay:
-                cg_mode = kCGBlendModeOverlay;
-                break;
-            case QPainter::CompositionMode_Darken:
-                cg_mode = kCGBlendModeDarken;
-                break;
-            case QPainter::CompositionMode_Lighten:
-                cg_mode = kCGBlendModeLighten;
-                break;
-            case QPainter::CompositionMode_ColorDodge:
-                cg_mode = kCGBlendModeColorDodge;
-                break;
-            case QPainter::CompositionMode_ColorBurn:
-                cg_mode = kCGBlendModeColorBurn;
-                break;
-            case QPainter::CompositionMode_HardLight:
-                cg_mode = kCGBlendModeHardLight;
-                break;
-            case QPainter::CompositionMode_SoftLight:
-                cg_mode = kCGBlendModeSoftLight;
-                break;
-            case QPainter::CompositionMode_Difference:
-                cg_mode = kCGBlendModeDifference;
-                break;
-            case QPainter::CompositionMode_Exclusion:
-                cg_mode = kCGBlendModeExclusion;
-                break;
-            case QPainter::CompositionMode_Plus:
-                needPrivateAPI = true;
-                cg_mode = kCGCompositeModePlusLighter;
-                break;
-            default:
-                break;
-            }
-            if (!needPrivateAPI)
-                CGContextSetBlendMode(d_func()->hd, CGBlendMode(cg_mode));
-            else
-                CGContextSetCompositeOperation(d_func()->hd, CGCompositeMode(cg_mode));
-        }
-#endif
-    }
-}
-
-void
-QCoreGraphicsPaintEngine::updateRenderHints(QPainter::RenderHints hints)
-{
-    Q_D(QCoreGraphicsPaintEngine);
-    CGContextSetShouldAntialias(d->hd, hints & QPainter::Antialiasing);
-    static const CGFloat ScaleFactor = qt_mac_get_scalefactor();
-    if (ScaleFactor > 1.) {
-        CGContextSetInterpolationQuality(d->hd, kCGInterpolationHigh);
-    } else {
-        CGContextSetInterpolationQuality(d->hd, (hints & QPainter::SmoothPixmapTransform) ?
-                                         kCGInterpolationHigh : kCGInterpolationNone);
-    }
-    bool textAntialiasing = (hints & QPainter::TextAntialiasing) == QPainter::TextAntialiasing;
-    if (!textAntialiasing || d->disabledSmoothFonts) {
-        d->disabledSmoothFonts = !textAntialiasing;
-        CGContextSetShouldSmoothFonts(d->hd, textAntialiasing);
-    }
-}
-
-/*
-    Returns the size of one device pixel in user-space coordinates.
-*/
-QPointF QCoreGraphicsPaintEnginePrivate::devicePixelSize(CGContextRef)
-{
-    QPointF p1 = current.transform.inverted().map(QPointF(0, 0));
-    QPointF p2 = current.transform.inverted().map(QPointF(1, 1));
-    return QPointF(qAbs(p2.x() - p1.x()), qAbs(p2.y() - p1.y()));
-}
-
-/*
-    Adjusts the pen width so we get correct line widths in the
-    non-transformed, aliased case.
-*/
-float QCoreGraphicsPaintEnginePrivate::adjustPenWidth(float penWidth)
-{
-    Q_Q(QCoreGraphicsPaintEngine);
-    float ret = penWidth;
-    if (!complexXForm && !(q->state->renderHints() & QPainter::Antialiasing)) {
-        if (penWidth < 2)
-            ret = 1;
-        else if (penWidth < 3)
-            ret = 1.5;
-        else
-            ret = penWidth -1;
-    }
-    return ret;
-}
-
-void
-QCoreGraphicsPaintEnginePrivate::setStrokePen(const QPen &pen)
-{
-    //pencap
-    CGLineCap cglinecap = kCGLineCapButt;
-    if(pen.capStyle() == Qt::SquareCap)
-        cglinecap = kCGLineCapSquare;
-    else if(pen.capStyle() == Qt::RoundCap)
-        cglinecap = kCGLineCapRound;
-    CGContextSetLineCap(hd, cglinecap);
-    CGContextSetLineWidth(hd, adjustPenWidth(pen.widthF()));
-
-    //join
-    CGLineJoin cglinejoin = kCGLineJoinMiter;
-    if(pen.joinStyle() == Qt::BevelJoin)
-        cglinejoin = kCGLineJoinBevel;
-    else if(pen.joinStyle() == Qt::RoundJoin)
-        cglinejoin = kCGLineJoinRound;
-    CGContextSetLineJoin(hd, cglinejoin);
-//    CGContextSetMiterLimit(hd, pen.miterLimit());
-
-    //pen style
-    QVector<CGFloat> linedashes;
-    if(pen.style() == Qt::CustomDashLine) {
-        QVector<qreal> customs = pen.dashPattern();
-        for(int i = 0; i < customs.size(); ++i)
-            linedashes.append(customs.at(i));
-    } else if(pen.style() == Qt::DashLine) {
-        linedashes.append(4);
-        linedashes.append(2);
-    } else if(pen.style() == Qt::DotLine) {
-        linedashes.append(1);
-        linedashes.append(2);
-    } else if(pen.style() == Qt::DashDotLine) {
-        linedashes.append(4);
-        linedashes.append(2);
-        linedashes.append(1);
-        linedashes.append(2);
-    } else if(pen.style() == Qt::DashDotDotLine) {
-        linedashes.append(4);
-        linedashes.append(2);
-        linedashes.append(1);
-        linedashes.append(2);
-        linedashes.append(1);
-        linedashes.append(2);
-    }
-    const CGFloat cglinewidth = pen.widthF() <= 0.0f ? 1.0f : float(pen.widthF());
-    for(int i = 0; i < linedashes.size(); ++i) {
-        linedashes[i] *= cglinewidth;
-        if(cglinewidth < 3 && (cglinecap == kCGLineCapSquare || cglinecap == kCGLineCapRound)) {
-            if((i%2))
-                linedashes[i] += cglinewidth/2;
-            else
-                linedashes[i] -= cglinewidth/2;
-        }
-    }
-    CGContextSetLineDash(hd, pen.dashOffset() * cglinewidth, linedashes.data(), linedashes.size());
-
-    // color
-    CGContextSetStrokeColorWithColor(hd, cgColorForQColor(pen.color(), pdev));
-}
-
-// Add our own patterns here to deal with the fact that the coordinate system
-// is flipped vertically with Quartz2D.
-static const uchar *qt_mac_patternForBrush(int brushStyle)
-{
-    Q_ASSERT(brushStyle > Qt::SolidPattern && brushStyle < Qt::LinearGradientPattern);
-    static const uchar dense1_pat[] = { 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x44, 0x00 };
-    static const uchar dense2_pat[] = { 0x00, 0x22, 0x00, 0x88, 0x00, 0x22, 0x00, 0x88 };
-    static const uchar dense3_pat[] = { 0x11, 0xaa, 0x44, 0xaa, 0x11, 0xaa, 0x44, 0xaa };
-    static const uchar dense4_pat[] = { 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55 };
-    static const uchar dense5_pat[] = { 0xee, 0x55, 0xbb, 0x55, 0xee, 0x55, 0xbb, 0x55 };
-    static const uchar dense6_pat[] = { 0xff, 0xdd, 0xff, 0x77, 0xff, 0xdd, 0xff, 0x77 };
-    static const uchar dense7_pat[] = { 0xff, 0xff, 0xbb, 0xff, 0xff, 0xff, 0xbb, 0xff };
-    static const uchar hor_pat[]    = { 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff };
-    static const uchar ver_pat[]    = { 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef, 0xef };
-    static const uchar cross_pat[]  = { 0xef, 0xef, 0xef, 0xef, 0x00, 0xef, 0xef, 0xef };
-    static const uchar fdiag_pat[]  = { 0x7f, 0xbf, 0xdf, 0xef, 0xf7, 0xfb, 0xfd, 0xfe };
-    static const uchar bdiag_pat[]  = { 0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f };
-    static const uchar dcross_pat[] = { 0x7e, 0xbd, 0xdb, 0xe7, 0xe7, 0xdb, 0xbd, 0x7e };
-    static const uchar *const pat_tbl[] = {
-        dense1_pat, dense2_pat, dense3_pat, dense4_pat, dense5_pat,
-        dense6_pat, dense7_pat,
-        hor_pat, ver_pat, cross_pat, bdiag_pat, fdiag_pat, dcross_pat };
-    return pat_tbl[brushStyle - Qt::Dense1Pattern];
-}
-
-void QCoreGraphicsPaintEnginePrivate::setFillBrush(const QPointF &offset)
-{
-    // pattern
-    Qt::BrushStyle bs = current.brush.style();
-#ifdef QT_MAC_USE_NATIVE_GRADIENTS
-    if (bs == Qt::LinearGradientPattern || bs == Qt::RadialGradientPattern) {
-        const QGradient *grad = static_cast<const QGradient*>(current.brush.gradient());
-        if (drawGradientNatively(grad)) {
-            Q_ASSERT(grad->spread() == QGradient::PadSpread);
-
-            static const CGFloat domain[] = { 0.0f, +1.0f };
-            static const CGFunctionCallbacks callbacks = { 0, qt_mac_color_gradient_function, 0 };
-            CGFunctionRef fill_func = CGFunctionCreate(reinterpret_cast<void *>(&current.brush),
-                    1, domain, 4, 0, &callbacks);
-
-            CGColorSpaceRef colorspace = qt_mac_colorSpaceForDeviceType(pdev);
-            if (bs == Qt::LinearGradientPattern) {
-                const QLinearGradient *linearGrad = static_cast<const QLinearGradient *>(grad);
-                const QPointF start(linearGrad->start());
-                const QPointF stop(linearGrad->finalStop());
-                shading = CGShadingCreateAxial(colorspace, CGPointMake(start.x(), start.y()),
-                                               CGPointMake(stop.x(), stop.y()), fill_func, true, true);
-            } else {
-                Q_ASSERT(bs == Qt::RadialGradientPattern);
-                const QRadialGradient *radialGrad = static_cast<const QRadialGradient *>(grad);
-                QPointF center(radialGrad->center());
-                QPointF focal(radialGrad->focalPoint());
-                qreal radius = radialGrad->radius();
-                qreal focalRadius = radialGrad->focalRadius();
-                shading = CGShadingCreateRadial(colorspace, CGPointMake(focal.x(), focal.y()),
-                                                focalRadius, CGPointMake(center.x(), center.y()), radius, fill_func, false, true);
-            }
-
-            CGFunctionRelease(fill_func);
-        }
-    } else
-#endif
-    if(bs != Qt::SolidPattern && bs != Qt::NoBrush
-#ifndef QT_MAC_USE_NATIVE_GRADIENTS
-       && (bs < Qt::LinearGradientPattern || bs > Qt::ConicalGradientPattern)
-#endif
-        )
-    {
-        QMacPattern *qpattern = new QMacPattern;
-        qpattern->pdev = pdev;
-        CGFloat components[4] = { 1.0, 1.0, 1.0, 1.0 };
-        CGColorSpaceRef base_colorspace = 0;
-        if(bs == Qt::TexturePattern) {
-            qpattern->data.pixmap = current.brush.texture();
-            if(qpattern->data.pixmap.isQBitmap()) {
-                const QColor &col = current.brush.color();
-                components[0] = qt_mac_convert_color_to_cg(col.red());
-                components[1] = qt_mac_convert_color_to_cg(col.green());
-                components[2] = qt_mac_convert_color_to_cg(col.blue());
-                base_colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
-            }
-        } else {
-            qpattern->as_mask = true;
-
-            qpattern->data.bytes = qt_mac_patternForBrush(bs);
-            const QColor &col = current.brush.color();
-            components[0] = qt_mac_convert_color_to_cg(col.red());
-            components[1] = qt_mac_convert_color_to_cg(col.green());
-            components[2] = qt_mac_convert_color_to_cg(col.blue());
-            base_colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
-        }
-        int width = qpattern->width(), height = qpattern->height();
-        qpattern->foreground = current.brush.color();
-
-        CGColorSpaceRef fill_colorspace = CGColorSpaceCreatePattern(base_colorspace);
-        CGContextSetFillColorSpace(hd, fill_colorspace);
-
-        CGAffineTransform xform = CGContextGetCTM(hd);
-        xform = CGAffineTransformConcat(qt_mac_convert_transform_to_cg(current.brush.transform()), xform);
-        xform = CGAffineTransformTranslate(xform, offset.x(), offset.y());
-
-        CGPatternCallbacks callbks;
-        callbks.version = 0;
-        callbks.drawPattern = qt_mac_draw_pattern;
-        callbks.releaseInfo = qt_mac_dispose_pattern;
-        CGPatternRef fill_pattern = CGPatternCreate(qpattern, CGRectMake(0, 0, width, height),
-                xform, width, height, kCGPatternTilingNoDistortion,
-                !base_colorspace, &callbks);
-        CGContextSetFillPattern(hd, fill_pattern, components);
-
-        CGPatternRelease(fill_pattern);
-        CGColorSpaceRelease(fill_colorspace);
-    } else if(bs != Qt::NoBrush) {
-        CGContextSetFillColorWithColor(hd, cgColorForQColor(current.brush.color(), pdev));
-    }
-}
-
-void
-QCoreGraphicsPaintEnginePrivate::setClip(const QRegion *rgn)
-{
-    Q_Q(QCoreGraphicsPaintEngine);
-    if(hd) {
-        resetClip();
-        QRegion sysClip = q->systemClip();
-        if(!sysClip.isEmpty())
-            qt_mac_clip_cg(hd, sysClip, &orig_xform);
-        if(rgn)
-            qt_mac_clip_cg(hd, *rgn, 0);
-    }
-}
-
-struct qt_mac_cg_transform_path {
-    CGMutablePathRef path;
-    CGAffineTransform transform;
-};
-
-void qt_mac_cg_transform_path_apply(void *info, const CGPathElement *element)
-{
-    Q_ASSERT(info && element);
-    qt_mac_cg_transform_path *t = (qt_mac_cg_transform_path*)info;
-    switch(element->type) {
-    case kCGPathElementMoveToPoint:
-        CGPathMoveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
-        break;
-    case kCGPathElementAddLineToPoint:
-        CGPathAddLineToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y);
-        break;
-    case kCGPathElementAddQuadCurveToPoint:
-        CGPathAddQuadCurveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y,
-                                  element->points[1].x, element->points[1].y);
-        break;
-    case kCGPathElementAddCurveToPoint:
-        CGPathAddCurveToPoint(t->path, &t->transform, element->points[0].x, element->points[0].y,
-                              element->points[1].x, element->points[1].y,
-                              element->points[2].x, element->points[2].y);
-        break;
-    case kCGPathElementCloseSubpath:
-        CGPathCloseSubpath(t->path);
-        break;
-    default:
-        qDebug() << "Unhandled path transform type: " << element->type;
-    }
-}
-
-void QCoreGraphicsPaintEnginePrivate::drawPath(uchar ops, CGMutablePathRef path)
-{
-    Q_Q(QCoreGraphicsPaintEngine);
-    Q_ASSERT((ops & (CGFill | CGEOFill)) != (CGFill | CGEOFill)); //can't really happen
-    if((ops & (CGFill | CGEOFill))) {
-        if (shading) {
-            Q_ASSERT(path);
-            CGContextBeginPath(hd);
-            CGContextAddPath(hd, path);
-            saveGraphicsState();
-            if (ops & CGFill)
-                CGContextClip(hd);
-            else if (ops & CGEOFill)
-                CGContextEOClip(hd);
-            if (current.brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
-                CGRect boundingBox = CGPathGetBoundingBox(path);
-                CGContextConcatCTM(hd,
-                    CGAffineTransformMake(boundingBox.size.width, 0,
-                                          0, boundingBox.size.height,
-                                          boundingBox.origin.x, boundingBox.origin.y));
-            }
-            CGContextDrawShading(hd, shading);
-            restoreGraphicsState();
-            ops &= ~CGFill;
-            ops &= ~CGEOFill;
-        } else if (current.brush.style() == Qt::NoBrush) {
-            ops &= ~CGFill;
-            ops &= ~CGEOFill;
-        }
-    }
-    if((ops & CGStroke) && current.pen.style() == Qt::NoPen)
-        ops &= ~CGStroke;
-
-    if(ops & (CGEOFill | CGFill)) {
-        CGContextBeginPath(hd);
-        CGContextAddPath(hd, path);
-        if (ops & CGEOFill) {
-            CGContextEOFillPath(hd);
-        } else {
-            CGContextFillPath(hd);
-        }
-    }
-
-    // Avoid saving and restoring the context if we can.
-    const bool needContextSave = (cosmeticPen != QCoreGraphicsPaintEnginePrivate::CosmeticNone ||
-                                  !(q->state->renderHints() & QPainter::Antialiasing));
-    if(ops & CGStroke) {
-        if (needContextSave)
-            saveGraphicsState();
-        CGContextBeginPath(hd);
-
-        // Translate a fraction of a pixel size in the y direction
-        // to make sure that primitives painted at pixel borders
-        // fills the right pixel. This is needed since the y xais
-        // in the Quartz coordinate system is inverted compared to Qt.
-        if (!(q->state->renderHints() & QPainter::Antialiasing)) {
-            if (current.pen.style() == Qt::SolidLine || current.pen.width() >= 3)
-                CGContextTranslateCTM(hd, double(pixelSize.x()) * 0.25, double(pixelSize.y()) * 0.25);
-            else if (current.pen.style() == Qt::DotLine && QSysInfo::MacintoshVersion == QSysInfo::MV_10_3)
-                ; // Do nothing.
-            else
-                CGContextTranslateCTM(hd, 0, double(pixelSize.y()) * 0.1);
-        }
-
-        if (cosmeticPen != QCoreGraphicsPaintEnginePrivate::CosmeticNone) {
-            // If antialiazing is enabled, use the cosmetic pen size directly.
-            if (q->state->renderHints() & QPainter::Antialiasing)
-                CGContextSetLineWidth(hd,  cosmeticPenSize);
-            else if (current.pen.widthF() <= 1)
-                CGContextSetLineWidth(hd, cosmeticPenSize * 0.9f);
-            else
-                CGContextSetLineWidth(hd, cosmeticPenSize);
-        }
-        if(cosmeticPen == QCoreGraphicsPaintEnginePrivate::CosmeticTransformPath) {
-            qt_mac_cg_transform_path t;
-            t.transform = qt_mac_convert_transform_to_cg(current.transform);
-            t.path = CGPathCreateMutable();
-            CGPathApply(path, &t, qt_mac_cg_transform_path_apply); //transform the path
-            setTransform(0); //unset the context transform
-            CGContextSetLineWidth(hd,  cosmeticPenSize);
-            CGContextAddPath(hd, t.path);
-            CGPathRelease(t.path);
-        } else {
-            CGContextAddPath(hd, path);
-        }
-
-        CGContextStrokePath(hd);
-        if (needContextSave)
-            restoreGraphicsState();
-    }
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qpaintengine_mac_p.h b/src/gui/painting/qpaintengine_mac_p.h
deleted file mode 100644 (file)
index 2eedec7..0000000
+++ /dev/null
@@ -1,257 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPAINTENGINE_MAC_P_H
-#define QPAINTENGINE_MAC_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 "qpaintengine.h"
-#include "qpen.h"
-#include "qt_mac_p.h"
-#include "qpaintengine_p.h"
-#include "qpolygonclipper_p.h"
-#include "qfont_p.h"
-#include "qhash.h"
-
-typedef struct CGColorSpace *CGColorSpaceRef;
-QT_BEGIN_NAMESPACE
-
-class QCoreGraphicsPaintEnginePrivate;
-class QCoreGraphicsPaintEngine : public QPaintEngine
-{
-    Q_DECLARE_PRIVATE(QCoreGraphicsPaintEngine)
-
-public:
-    QCoreGraphicsPaintEngine();
-    ~QCoreGraphicsPaintEngine();
-
-    bool begin(QPaintDevice *pdev);
-    bool end();
-    static CGColorSpaceRef macGenericColorSpace();
-    static CGColorSpaceRef macDisplayColorSpace(const QWidget *widget = 0);
-
-    void updateState(const QPaintEngineState &state);
-
-    void updatePen(const QPen &pen);
-    void updateBrush(const QBrush &brush, const QPointF &pt);
-    void updateFont(const QFont &font);
-    void updateOpacity(qreal opacity);
-    void updateMatrix(const QTransform &matrix);
-    void updateTransform(const QTransform &matrix);
-    void updateClipRegion(const QRegion &region, Qt::ClipOperation op);
-    void updateClipPath(const QPainterPath &path, Qt::ClipOperation op);
-    void updateCompositionMode(QPainter::CompositionMode mode);
-    void updateRenderHints(QPainter::RenderHints hints);
-
-    void drawLines(const QLineF *lines, int lineCount);
-    void drawRects(const QRectF *rects, int rectCount);
-    void drawPoints(const QPointF *p, int pointCount);
-    void drawEllipse(const QRectF &r);
-    void drawPath(const QPainterPath &path);
-
-    void drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode);
-    void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
-    void drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, const QPointF &s);
-
-    void drawTextItem(const QPointF &pos, const QTextItem &item);
-    void drawImage(const QRectF &r, const QImage &pm, const QRectF &sr,
-                   Qt::ImageConversionFlags flags = Qt::AutoColor);
-
-    Type type() const { return QPaintEngine::CoreGraphics; }
-
-    CGContextRef handle() const;
-
-    static void initialize();
-    static void cleanup();
-    static void clearColorSpace(QWidget* w);
-
-    QPainter::RenderHints supportedRenderHints() const;
-
-    //avoid partial shadowed overload warnings...
-    void drawLines(const QLine *lines, int lineCount) { QPaintEngine::drawLines(lines, lineCount); }
-    void drawRects(const QRect *rects, int rectCount) { QPaintEngine::drawRects(rects, rectCount); }
-    void drawPoints(const QPoint *p, int pointCount) { QPaintEngine::drawPoints(p, pointCount); }
-    void drawEllipse(const QRect &r) { QPaintEngine::drawEllipse(r); }
-    void drawPolygon(const QPoint *points, int pointCount, PolygonDrawMode mode)
-    { QPaintEngine::drawPolygon(points, pointCount, mode); }
-
-    bool supportsTransformations(qreal, const QTransform &) const { return true; };
-
-protected:
-    friend class QMacPrintEngine;
-    friend class QMacPrintEnginePrivate;
-    friend void qt_mac_display_change_callbk(CGDirectDisplayID, CGDisplayChangeSummaryFlags, void *);
-    friend void qt_color_profile_changed(CFNotificationCenterRef center, void *,
-                                         CFStringRef , const void *, CFDictionaryRef);
-    QCoreGraphicsPaintEngine(QPaintEnginePrivate &dptr);
-
-private:
-    static bool m_postRoutineRegistered;
-    static CGColorSpaceRef m_genericColorSpace;
-    static QHash<QWidget*, CGColorSpaceRef> m_displayColorSpaceHash; // window -> color space
-    static void cleanUpMacColorSpaces();
-    Q_DISABLE_COPY(QCoreGraphicsPaintEngine)
-};
-
-/*****************************************************************************
-  Private data
- *****************************************************************************/
-class QCoreGraphicsPaintEnginePrivate : public QPaintEnginePrivate
-{
-    Q_DECLARE_PUBLIC(QCoreGraphicsPaintEngine)
-public:
-    QCoreGraphicsPaintEnginePrivate()
-        : hd(0), shading(0), stackCount(0), complexXForm(false), disabledSmoothFonts(false)
-    {
-    }
-
-    struct {
-        QPen pen;
-        QBrush brush;
-        uint clipEnabled : 1;
-        QRegion clip;
-        QTransform transform;
-   } current;
-
-    //state info (shared with QD)
-    CGAffineTransform orig_xform;
-
-    //cg structures
-    CGContextRef hd;
-    CGShadingRef shading;
-    int stackCount;
-    bool complexXForm;
-    bool disabledSmoothFonts;
-    enum { CosmeticNone, CosmeticTransformPath, CosmeticSetPenWidth } cosmeticPen;
-
-    // pixel and cosmetic pen size in user coordinates.
-    QPointF pixelSize;
-    float cosmeticPenSize;
-
-    //internal functions
-    enum { CGStroke=0x01, CGEOFill=0x02, CGFill=0x04 };
-    void drawPath(uchar ops, CGMutablePathRef path = 0);
-    void setClip(const QRegion *rgn=0);
-    void resetClip();
-    void setFillBrush(const QPointF &origin=QPoint());
-    void setStrokePen(const QPen &pen);
-    inline void saveGraphicsState();
-    inline void restoreGraphicsState();
-    float penOffset();
-    QPointF devicePixelSize(CGContextRef context);
-    float adjustPenWidth(float penWidth);
-    inline void setTransform(const QTransform *matrix=0)
-    {
-        CGContextConcatCTM(hd, CGAffineTransformInvert(CGContextGetCTM(hd)));
-        CGAffineTransform xform = orig_xform;
-        if(matrix) {
-            extern CGAffineTransform qt_mac_convert_transform_to_cg(const QTransform &);
-            xform = CGAffineTransformConcat(qt_mac_convert_transform_to_cg(*matrix), xform);
-        }
-        CGContextConcatCTM(hd, xform);
-        CGContextSetTextMatrix(hd, xform);
-    }
-};
-
-inline void QCoreGraphicsPaintEnginePrivate::saveGraphicsState()
-{
-    ++stackCount;
-    CGContextSaveGState(hd);
-}
-
-inline void QCoreGraphicsPaintEnginePrivate::restoreGraphicsState()
-{
-    --stackCount;
-    Q_ASSERT(stackCount >= 0);
-    CGContextRestoreGState(hd);
-}
-
-class QMacQuartzPaintDevice : public QPaintDevice
-{
-public:
-    QMacQuartzPaintDevice(CGContextRef cg, int width, int height)
-        : mCG(cg), mWidth(width), mHeight(height)
-    { }
-    int devType() const { return QInternal::MacQuartz; }
-    CGContextRef cgContext() const { return mCG; }
-    int metric(PaintDeviceMetric metric) const {
-        switch (metric) {
-        case PdmWidth:
-            return mWidth;
-        case PdmHeight:
-            return mHeight;
-        case PdmWidthMM:
-            return (qt_defaultDpiX() * mWidth) / 2.54;
-        case PdmHeightMM:
-            return (qt_defaultDpiY() * mHeight) / 2.54;
-        case PdmNumColors:
-            return 0;
-        case PdmDepth:
-            return 32;
-        case PdmDpiX:
-        case PdmPhysicalDpiX:
-            return qt_defaultDpiX();
-        case PdmDpiY:
-        case PdmPhysicalDpiY:
-            return qt_defaultDpiY();
-        }
-        return 0;
-    }
-    QPaintEngine *paintEngine() const { qWarning("This function should never be called."); return 0; }
-private:
-    CGContextRef mCG;
-    int mWidth;
-    int mHeight;
-};
-
-QT_END_NAMESPACE
-
-#endif // QPAINTENGINE_MAC_P_H
diff --git a/src/gui/painting/qprintengine_mac.mm b/src/gui/painting/qprintengine_mac.mm
deleted file mode 100644 (file)
index a2ee509..0000000
+++ /dev/null
@@ -1,937 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qprintengine_mac_p.h>
-#include <qthread.h>
-#include <quuid.h>
-#include <QtCore/qcoreapplication.h>
-
-#ifndef QT_NO_PRINTER
-
-QT_BEGIN_NAMESPACE
-
-extern QSizeF qt_paperSizeToQSizeF(QPrinter::PaperSize size);
-
-QMacPrintEngine::QMacPrintEngine(QPrinter::PrinterMode mode) : QPaintEngine(*(new QMacPrintEnginePrivate))
-{
-    Q_D(QMacPrintEngine);
-    d->mode = mode;
-    d->initialize();
-}
-
-bool QMacPrintEngine::begin(QPaintDevice *dev)
-{
-    Q_D(QMacPrintEngine);
-
-    Q_ASSERT(dev && dev->devType() == QInternal::Printer);
-    if (!static_cast<QPrinter *>(dev)->isValid())
-       return false;
-
-    if (d->state == QPrinter::Idle && !d->isPrintSessionInitialized()) // Need to reinitialize
-        d->initialize();
-
-    d->paintEngine->state = state;
-    d->paintEngine->begin(dev);
-    Q_ASSERT_X(d->state == QPrinter::Idle, "QMacPrintEngine", "printer already active");
-
-    if (PMSessionValidatePrintSettings(d->session, d->settings, kPMDontWantBoolean) != noErr
-        || PMSessionValidatePageFormat(d->session, d->format, kPMDontWantBoolean) != noErr) {
-        d->state = QPrinter::Error;
-        return false;
-    }
-
-    if (!d->outputFilename.isEmpty()) {
-        QCFType<CFURLRef> outFile = CFURLCreateWithFileSystemPath(kCFAllocatorSystemDefault,
-                                                                  QCFString(d->outputFilename),
-                                                                  kCFURLPOSIXPathStyle,
-                                                                  false);
-        if (PMSessionSetDestination(d->session, d->settings, kPMDestinationFile,
-                                    kPMDocumentFormatPDF, outFile) != noErr) {
-            qWarning("QMacPrintEngine::begin: Problem setting file [%s]", d->outputFilename.toUtf8().constData());
-            return false;
-        }
-    }
-    OSStatus status = noErr;
-#ifndef QT_MAC_USE_COCOA
-    status = d->shouldSuppressStatus() ? PMSessionBeginCGDocumentNoDialog(d->session, d->settings, d->format)
-                                       : PMSessionBeginCGDocument(d->session, d->settings, d->format);
-#else
-    status = PMSessionBeginCGDocumentNoDialog(d->session, d->settings, d->format);
-#endif
-
-    if (status != noErr) {
-        d->state = QPrinter::Error;
-        return false;
-    }
-
-    d->state = QPrinter::Active;
-    setActive(true);
-    d->newPage_helper();
-    return true;
-}
-
-bool QMacPrintEngine::end()
-{
-    Q_D(QMacPrintEngine);
-    if (d->state == QPrinter::Aborted)
-        return true;  // I was just here a function call ago :)
-    if(d->paintEngine->type() == QPaintEngine::CoreGraphics) {
-        // We dont need the paint engine to call restoreGraphicsState()
-        static_cast<QCoreGraphicsPaintEngine*>(d->paintEngine)->d_func()->stackCount = 0;
-        static_cast<QCoreGraphicsPaintEngine*>(d->paintEngine)->d_func()->hd = 0;
-    }
-    d->paintEngine->end();
-    if (d->state != QPrinter::Idle)
-       d->releaseSession();
-    d->state  = QPrinter::Idle;
-    return true;
-}
-
-QPaintEngine *
-QMacPrintEngine::paintEngine() const
-{
-    return d_func()->paintEngine;
-}
-
-Qt::HANDLE QMacPrintEngine::handle() const
-{
-    QCoreGraphicsPaintEngine *cgEngine = static_cast<QCoreGraphicsPaintEngine*>(paintEngine());
-    return cgEngine->d_func()->hd;
-}
-
-QMacPrintEnginePrivate::~QMacPrintEnginePrivate()
-{
-#ifdef QT_MAC_USE_COCOA
-    [printInfo release];
-#endif
-    delete paintEngine;
-}
-
-void QMacPrintEnginePrivate::setPaperSize(QPrinter::PaperSize ps)
-{
-    Q_Q(QMacPrintEngine);
-    if (hasCustomPaperSize) {
-        PMRelease(customPaper);
-        customPaper = 0;
-    }
-    hasCustomPaperSize = (ps == QPrinter::Custom);
-    PMPrinter printer;
-
-    if (PMSessionGetCurrentPrinter(session, &printer) == noErr) {
-        if (ps != QPrinter::Custom) {
-            QSize newSize = qt_paperSizeToQSizeF(ps).toSize();
-            QCFType<CFArrayRef> formats;
-            if (PMSessionCreatePageFormatList(session, printer, &formats) == noErr) {
-                CFIndex total = CFArrayGetCount(formats);
-                PMPageFormat tmp;
-                PMRect paper;
-                for (CFIndex idx = 0; idx < total; ++idx) {
-                    tmp = static_cast<PMPageFormat>(const_cast<void *>(CFArrayGetValueAtIndex(formats, idx)));
-                    PMGetUnadjustedPaperRect(tmp, &paper);
-                    int wMM = int((paper.right - paper.left) / 72 * 25.4 + 0.5);
-                    int hMM = int((paper.bottom - paper.top) / 72 * 25.4 + 0.5);
-                    if (newSize.width() == wMM && newSize.height() == hMM) {
-                        PMCopyPageFormat(tmp, format);
-                        // reset the orientation and resolution as they are lost in the copy.
-                        q->setProperty(QPrintEngine::PPK_Orientation, orient);
-                        if (PMSessionValidatePageFormat(session, format, kPMDontWantBoolean) != noErr) {
-                            // Don't know, warn for the moment.
-                            qWarning("QMacPrintEngine, problem setting format and resolution for this page size");
-                        }
-                        break;
-                    }
-                }
-            }
-        } else {
-            QCFString paperId = QCFString::toCFStringRef(QUuid::createUuid().toString());
-            PMPaperMargins paperMargins;
-            paperMargins.left = leftMargin;
-            paperMargins.top = topMargin;
-            paperMargins.right = rightMargin;
-            paperMargins.bottom = bottomMargin;
-            PMPaperCreateCustom(printer, paperId, QCFString("Custom size"), customSize.width(), customSize.height(), &paperMargins, &customPaper);
-            PMPageFormat tmp;
-            PMCreatePageFormatWithPMPaper(&tmp, customPaper);
-            PMCopyPageFormat(tmp, format);
-            if (PMSessionValidatePageFormat(session, format, kPMDontWantBoolean) != noErr) {
-                // Don't know, warn for the moment.
-                qWarning("QMacPrintEngine, problem setting paper name");
-            }
-        }
-    }
-}
-
-QPrinter::PaperSize QMacPrintEnginePrivate::paperSize() const
-{
-    if (hasCustomPaperSize)
-        return QPrinter::Custom;
-    PMRect paper;
-    PMGetUnadjustedPaperRect(format, &paper);
-    int wMM = int((paper.right - paper.left) / 72 * 25.4 + 0.5);
-    int hMM = int((paper.bottom - paper.top) / 72 * 25.4 + 0.5);
-    for (int i = QPrinter::A4; i < QPrinter::NPaperSize; ++i) {
-        QSize s = qt_paperSizeToQSizeF(QPrinter::PaperSize(i)).toSize();
-        if (s.width() == wMM && s.height() == hMM)
-            return (QPrinter::PaperSize)i;
-    }
-    return QPrinter::Custom;
-}
-
-QList<QVariant> QMacPrintEnginePrivate::supportedResolutions() const
-{
-    Q_ASSERT_X(session, "QMacPrinterEngine::supportedResolutions",
-               "must have a valid printer session");
-    UInt32 resCount;
-    QList<QVariant> resolutions;
-    PMPrinter printer;
-    if (PMSessionGetCurrentPrinter(session, &printer) == noErr) {
-        PMResolution res;
-        OSStatus status = PMPrinterGetPrinterResolutionCount(printer, &resCount);
-        if (status  == kPMNotImplemented) {
-#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
-            // *Sigh* we have to use the non-indexed version.
-            if (PMPrinterGetPrinterResolution(printer, kPMMinSquareResolution, &res) == noErr)
-                resolutions.append(int(res.hRes));
-            if (PMPrinterGetPrinterResolution(printer, kPMMaxSquareResolution, &res) == noErr) {
-                QVariant var(int(res.hRes));
-                if (!resolutions.contains(var))
-                    resolutions.append(var);
-            }
-            if (PMPrinterGetPrinterResolution(printer, kPMDefaultResolution, &res) == noErr) {
-                QVariant var(int(res.hRes));
-                if (!resolutions.contains(var))
-                    resolutions.append(var);
-            }
-#endif
-        } else if (status == noErr) {
-            // According to the docs, index start at 1.
-            for (UInt32 i = 1; i <= resCount; ++i) {
-                if (PMPrinterGetIndexedPrinterResolution(printer, i, &res) == noErr)
-                    resolutions.append(QVariant(int(res.hRes)));
-            }
-        } else {
-            qWarning("QMacPrintEngine::supportedResolutions: Unexpected error: %ld", long(status));
-        }
-    }
-    return resolutions;
-}
-
-bool QMacPrintEnginePrivate::shouldSuppressStatus() const
-{
-    if (suppressStatus == true)
-        return true;
-
-    // Supress displaying the automatic progress dialog if we are printing
-    // from a non-gui thread.
-    return (qApp->thread() != QThread::currentThread());
-}
-
-QPrinter::PrinterState QMacPrintEngine::printerState() const
-{
-    return d_func()->state;
-}
-
-bool QMacPrintEngine::newPage()
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    OSStatus err =
-#ifndef QT_MAC_USE_COCOA
-    d->shouldSuppressStatus() ? PMSessionEndPageNoDialog(d->session)
-                              : PMSessionEndPage(d->session);
-#else
-    PMSessionEndPageNoDialog(d->session);
-#endif
-    if (err != noErr)  {
-        if (err == kPMCancel) {
-            // User canceled, we need to abort!
-            abort();
-        } else {
-            // Not sure what the problem is...
-            qWarning("QMacPrintEngine::newPage: Cannot end current page. %ld", long(err));
-            d->state = QPrinter::Error;
-        }
-        return false;
-    }
-    return d->newPage_helper();
-}
-
-bool QMacPrintEngine::abort()
-{
-    Q_D(QMacPrintEngine);
-    if (d->state != QPrinter::Active)
-        return false;
-    bool ret = end();
-    d->state = QPrinter::Aborted;
-    return ret;
-}
-
-static inline int qt_get_PDMWidth(PMPageFormat pformat, bool fullPage,
-                                  const PMResolution &resolution)
-{
-    int val = 0;
-    PMRect r;
-    qreal hRatio = resolution.hRes / 72;
-    if (fullPage) {
-        if (PMGetAdjustedPaperRect(pformat, &r) == noErr)
-            val = qRound((r.right - r.left) * hRatio);
-    } else {
-        if (PMGetAdjustedPageRect(pformat, &r) == noErr)
-            val = qRound((r.right - r.left) * hRatio);
-    }
-    return val;
-}
-
-static inline int qt_get_PDMHeight(PMPageFormat pformat, bool fullPage,
-                                   const PMResolution &resolution)
-{
-    int val = 0;
-    PMRect r;
-    qreal vRatio = resolution.vRes / 72;
-    if (fullPage) {
-        if (PMGetAdjustedPaperRect(pformat, &r) == noErr)
-            val = qRound((r.bottom - r.top) * vRatio);
-    } else {
-        if (PMGetAdjustedPageRect(pformat, &r) == noErr)
-            val = qRound((r.bottom - r.top) * vRatio);
-    }
-    return val;
-}
-
-
-int QMacPrintEngine::metric(QPaintDevice::PaintDeviceMetric m) const
-{
-    Q_D(const QMacPrintEngine);
-    int val = 1;
-    switch (m) {
-    case QPaintDevice::PdmWidth:
-        if (d->hasCustomPaperSize) {
-            val = qRound(d->customSize.width());
-            if (d->hasCustomPageMargins) {
-                val -= qRound(d->leftMargin + d->rightMargin);
-            } else {
-                QList<QVariant> margins = property(QPrintEngine::PPK_PageMargins).toList();
-                val -= qRound(margins.at(0).toDouble() + margins.at(2).toDouble());
-            }
-        } else {
-            val = qt_get_PDMWidth(d->format, property(PPK_FullPage).toBool(), d->resolution);
-        }
-        break;
-    case QPaintDevice::PdmHeight:
-        if (d->hasCustomPaperSize) {
-            val = qRound(d->customSize.height());
-            if (d->hasCustomPageMargins) {
-                val -= qRound(d->topMargin + d->bottomMargin);
-            } else {
-                QList<QVariant> margins = property(QPrintEngine::PPK_PageMargins).toList();
-                val -= qRound(margins.at(1).toDouble() + margins.at(3).toDouble());
-            }
-        } else {
-            val = qt_get_PDMHeight(d->format, property(PPK_FullPage).toBool(), d->resolution);
-        }
-        break;
-    case QPaintDevice::PdmWidthMM:
-        val = metric(QPaintDevice::PdmWidth);
-        val = int((val * 254 + 5 * d->resolution.hRes) / (10 * d->resolution.hRes));
-        break;
-    case QPaintDevice::PdmHeightMM:
-        val = metric(QPaintDevice::PdmHeight);
-        val = int((val * 254 + 5 * d->resolution.vRes) / (10 * d->resolution.vRes));
-        break;
-    case QPaintDevice::PdmPhysicalDpiX:
-    case QPaintDevice::PdmPhysicalDpiY: {
-        PMPrinter printer;
-        if(PMSessionGetCurrentPrinter(d->session, &printer) == noErr) {
-            PMResolution resolution;
-#ifndef QT_MAC_USE_COCOA
-#  if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-            if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-                PMPrinterGetOutputResolution(printer, d->settings, &resolution);
-            } else
-#  endif
-            {
-                PMPrinterGetPrinterResolution(printer, kPMCurrentValue, &resolution);
-            }
-#else
-            PMPrinterGetOutputResolution(printer, d->settings, &resolution);
-#endif
-            val = (int)resolution.vRes;
-            break;
-        }
-        //otherwise fall through
-    }
-    case QPaintDevice::PdmDpiY:
-        val = (int)d->resolution.vRes;
-        break;
-    case QPaintDevice::PdmDpiX:
-        val = (int)d->resolution.hRes;
-        break;
-    case QPaintDevice::PdmNumColors:
-        val = (1 << metric(QPaintDevice::PdmDepth));
-        break;
-    case QPaintDevice::PdmDepth:
-        val = 24;
-        break;
-    default:
-        val = 0;
-        qWarning("QPrinter::metric: Invalid metric command");
-    }
-    return val;
-}
-
-void QMacPrintEnginePrivate::initialize()
-{
-    Q_Q(QMacPrintEngine);
-
-#ifndef QT_MAC_USE_COCOA
-    Q_ASSERT(!session);
-#else
-    Q_ASSERT(!printInfo);
-#endif
-
-    if (!paintEngine)
-        paintEngine = new QCoreGraphicsPaintEngine();
-
-    q->gccaps = paintEngine->gccaps;
-
-    fullPage = false;
-
-#ifndef QT_MAC_USE_COCOA
-    if (PMCreateSession(&session) != 0)
-        session = 0;
-#else
-    QMacCocoaAutoReleasePool pool;
-    printInfo = [[NSPrintInfo alloc] initWithDictionary:[NSDictionary dictionary]];
-    session = static_cast<PMPrintSession>([printInfo PMPrintSession]);
-#endif
-
-    PMPrinter printer;
-    if (session && PMSessionGetCurrentPrinter(session, &printer) == noErr) {
-        QList<QVariant> resolutions = supportedResolutions();
-        if (!resolutions.isEmpty() && mode != QPrinter::ScreenResolution) {
-            if (resolutions.count() > 1 && mode == QPrinter::HighResolution) {
-                int max = 0;
-                for (int i = 0; i < resolutions.count(); ++i) {
-                    int value = resolutions.at(i).toInt();
-                    if (value > max)
-                        max = value;
-                }
-                resolution.hRes = resolution.vRes = max;
-            } else {
-                resolution.hRes = resolution.vRes = resolutions.at(0).toInt();
-            }
-            if(resolution.hRes == 0)
-                resolution.hRes = resolution.vRes = 600;
-        } else {
-            resolution.hRes = resolution.vRes = qt_defaultDpi();
-        }
-    }
-
-#ifndef QT_MAC_USE_COCOA
-    bool settingsInitialized = (settings != 0);
-    bool settingsOK = !settingsInitialized ? PMCreatePrintSettings(&settings) == noErr : true;
-    if (settingsOK && !settingsInitialized)
-        settingsOK = PMSessionDefaultPrintSettings(session, settings) == noErr;
-
-
-    bool formatInitialized = (format != 0);
-    bool formatOK = !formatInitialized ? PMCreatePageFormat(&format) == noErr : true;
-    if (formatOK) {
-        if (!formatInitialized) {
-            formatOK = PMSessionDefaultPageFormat(session, format) == noErr;
-        }
-        formatOK = PMSessionValidatePageFormat(session, format, kPMDontWantBoolean) == noErr;
-    }
-#else
-    settings = static_cast<PMPrintSettings>([printInfo PMPrintSettings]);
-    format = static_cast<PMPageFormat>([printInfo PMPageFormat]);
-#endif
-
-#ifndef QT_MAC_USE_COCOA
-    if (!settingsOK || !formatOK) {
-        qWarning("QMacPrintEngine::initialize: Unable to initialize QPainter");
-        state = QPrinter::Error;
-    }
-#endif
-
-    QHash<QMacPrintEngine::PrintEnginePropertyKey, QVariant>::const_iterator propC;
-    for (propC = valueCache.constBegin(); propC != valueCache.constEnd(); propC++) {
-        q->setProperty(propC.key(), propC.value());
-    }
-}
-
-void QMacPrintEnginePrivate::releaseSession()
-{
-#ifndef QT_MAC_USE_COCOA
-    if (shouldSuppressStatus()) {
-       PMSessionEndPageNoDialog(session);
-       PMSessionEndDocumentNoDialog(session);
-    } else {
-       PMSessionEndPage(session);
-       PMSessionEndDocument(session);
-    }
-    PMRelease(session);
-#else
-    PMSessionEndPageNoDialog(session);
-    PMSessionEndDocumentNoDialog(session);
-    [printInfo release];
-#endif
-    if (hasCustomPaperSize)
-        PMRelease(customPaper);
-    printInfo = 0;
-    session = 0;
-}
-
-bool QMacPrintEnginePrivate::newPage_helper()
-{
-    Q_Q(QMacPrintEngine);
-    Q_ASSERT(state == QPrinter::Active);
-
-    if (PMSessionError(session) != noErr) {
-        q->abort();
-        return false;
-    }
-
-    // pop the stack of saved graphic states, in case we get the same
-    // context back - either way, the stack count should be 0 when we
-    // get the new one
-    QCoreGraphicsPaintEngine *cgEngine = static_cast<QCoreGraphicsPaintEngine*>(paintEngine);
-    while (cgEngine->d_func()->stackCount > 0)
-        cgEngine->d_func()->restoreGraphicsState();
-
-    OSStatus status =
-#ifndef QT_MAC_USE_COCOA
-        shouldSuppressStatus() ? PMSessionBeginPageNoDialog(session, format, 0)
-                               : PMSessionBeginPage(session, format, 0);
-#else
-        PMSessionBeginPageNoDialog(session, format, 0);
-#endif
-    if(status != noErr) {
-        state = QPrinter::Error;
-        return false;
-    }
-
-    QRect page = q->property(QPrintEngine::PPK_PageRect).toRect();
-    QRect paper = q->property(QPrintEngine::PPK_PaperRect).toRect();
-
-    CGContextRef cgContext;
-    OSStatus err = noErr;
-    err = PMSessionGetCGGraphicsContext(session, &cgContext);
-    if(err != noErr) {
-        qWarning("QMacPrintEngine::newPage: Cannot retrieve CoreGraphics context: %ld", long(err));
-        state = QPrinter::Error;
-        return false;
-    }
-    cgEngine->d_func()->hd = cgContext;
-
-    // Set the resolution as a scaling ration of 72 (the default).
-    CGContextScaleCTM(cgContext, 72 / resolution.hRes, 72 / resolution.vRes);
-
-    CGContextScaleCTM(cgContext, 1, -1);
-    CGContextTranslateCTM(cgContext, 0, -paper.height());
-    if (!fullPage)
-        CGContextTranslateCTM(cgContext, page.x() - paper.x(), page.y() - paper.y());
-    cgEngine->d_func()->orig_xform = CGContextGetCTM(cgContext);
-    cgEngine->d_func()->setClip(0);
-    cgEngine->state->dirtyFlags = QPaintEngine::DirtyFlag(QPaintEngine::AllDirty
-                                                         & ~(QPaintEngine::DirtyClipEnabled
-                                                             | QPaintEngine::DirtyClipRegion
-                                                             | QPaintEngine::DirtyClipPath));
-    if (cgEngine->painter()->hasClipping())
-        cgEngine->state->dirtyFlags |= QPaintEngine::DirtyClipEnabled;
-    cgEngine->syncState();
-    return true;
-}
-
-
-void QMacPrintEngine::updateState(const QPaintEngineState &state)
-{
-    d_func()->paintEngine->updateState(state);
-}
-
-void QMacPrintEngine::drawRects(const QRectF *r, int num)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawRects(r, num);
-}
-
-void QMacPrintEngine::drawPoints(const QPointF *points, int pointCount)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawPoints(points, pointCount);
-}
-
-void QMacPrintEngine::drawEllipse(const QRectF &r)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawEllipse(r);
-}
-
-void QMacPrintEngine::drawLines(const QLineF *lines, int lineCount)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawLines(lines, lineCount);
-}
-
-void QMacPrintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawPolygon(points, pointCount, mode);
-}
-
-void QMacPrintEngine::drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawPixmap(r, pm, sr);
-}
-
-void QMacPrintEngine::drawImage(const QRectF &r, const QImage &pm, const QRectF &sr, Qt::ImageConversionFlags flags)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawImage(r, pm, sr, flags);
-}
-
-void QMacPrintEngine::drawTextItem(const QPointF &p, const QTextItem &ti)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawTextItem(p, ti);
-}
-
-void QMacPrintEngine::drawTiledPixmap(const QRectF &dr, const QPixmap &pixmap, const QPointF &sr)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawTiledPixmap(dr, pixmap, sr);
-}
-
-void QMacPrintEngine::drawPath(const QPainterPath &path)
-{
-    Q_D(QMacPrintEngine);
-    Q_ASSERT(d->state == QPrinter::Active);
-    d->paintEngine->drawPath(path);
-}
-
-
-void QMacPrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant &value)
-{
-    Q_D(QMacPrintEngine);
-
-    d->valueCache.insert(key, value);
-    if (!d->session)
-        return;
-
-    switch (key) {
-    case PPK_CollateCopies:
-        break;
-    case PPK_ColorMode:
-        break;
-    case PPK_Creator:
-        break;
-    case PPK_DocumentName:
-        break;
-    case PPK_PageOrder:
-        break;
-    case PPK_PaperSource:
-        break;
-    case PPK_SelectionOption:
-        break;
-    case PPK_Resolution:  {
-        PMPrinter printer;
-        UInt32 count;
-        if (PMSessionGetCurrentPrinter(d->session, &printer) != noErr)
-            break;
-        if (PMPrinterGetPrinterResolutionCount(printer, &count) != noErr)
-            break;
-        PMResolution resolution = { 0.0, 0.0 };
-        PMResolution bestResolution = { 0.0, 0.0 };
-        int dpi = value.toInt();
-        int bestDistance = INT_MAX;
-        for (UInt32 i = 1; i <= count; ++i) {  // Yes, it starts at 1
-            if (PMPrinterGetIndexedPrinterResolution(printer, i, &resolution) == noErr) {
-                if (dpi == int(resolution.hRes)) {
-                    bestResolution = resolution;
-                    break;
-                } else {
-                    int distance = qAbs(dpi - int(resolution.hRes));
-                    if (distance < bestDistance) {
-                        bestDistance = distance;
-                        bestResolution = resolution;
-                    }
-                }
-            }
-        }
-        PMSessionValidatePageFormat(d->session, d->format, kPMDontWantBoolean);
-        break;
-    }
-
-    case PPK_FullPage:
-        d->fullPage = value.toBool();
-        break;
-    case PPK_CopyCount: // fallthrough
-    case PPK_NumberOfCopies:
-        PMSetCopies(d->settings, value.toInt(), false);
-        break;
-    case PPK_Orientation: {
-        if (d->state == QPrinter::Active) {
-            qWarning("QMacPrintEngine::setOrientation: Orientation cannot be changed during a print job, ignoring change");
-        } else {
-            QPrinter::Orientation newOrientation = QPrinter::Orientation(value.toInt());
-            if (d->hasCustomPaperSize && (d->orient != newOrientation))
-                d->customSize = QSizeF(d->customSize.height(), d->customSize.width());
-            d->orient = newOrientation;
-            PMOrientation o = d->orient == QPrinter::Portrait ? kPMPortrait : kPMLandscape;
-            PMSetOrientation(d->format, o, false);
-            PMSessionValidatePageFormat(d->session, d->format, kPMDontWantBoolean);
-        }
-        break; }
-    case PPK_OutputFileName:
-        d->outputFilename = value.toString();
-        break;
-    case PPK_PaperSize:
-        d->setPaperSize(QPrinter::PaperSize(value.toInt()));
-        break;
-    case PPK_PrinterName: {
-        bool printerNameSet = false;
-        OSStatus status = noErr;
-        QCFType<CFArrayRef> printerList;
-        status = PMServerCreatePrinterList(kPMServerLocal, &printerList);
-        if (status == noErr) {
-            CFIndex count = CFArrayGetCount(printerList);
-            for (CFIndex i=0; i<count; ++i) {
-                PMPrinter printer = static_cast<PMPrinter>(const_cast<void *>(CFArrayGetValueAtIndex(printerList, i)));
-                QString name = QCFString::toQString(PMPrinterGetName(printer));
-                if (name == value.toString()) {
-                    status = PMSessionSetCurrentPMPrinter(d->session, printer);
-                    printerNameSet = true;
-                    break;
-                }
-            }
-        }
-        if (status != noErr)
-            qWarning("QMacPrintEngine::setPrinterName: Error setting printer: %ld", long(status));
-       if (!printerNameSet) {
-            qWarning("QMacPrintEngine::setPrinterName: Failed to set printer named '%s'.", qPrintable(value.toString()));
-            d->releaseSession();
-            d->state = QPrinter::Idle;
-        }
-        break; }
-    case PPK_SuppressSystemPrintStatus:
-        d->suppressStatus = value.toBool();
-        break;
-    case PPK_CustomPaperSize:
-    {
-        PMOrientation orientation;
-        PMGetOrientation(d->format, &orientation);
-        d->customSize = value.toSizeF();
-        if (orientation != kPMPortrait)
-            d->customSize = QSizeF(d->customSize.height(), d->customSize.width());
-        d->setPaperSize(QPrinter::Custom);
-        break;
-    }
-    case PPK_PageMargins:
-    {
-        QList<QVariant> margins(value.toList());
-        Q_ASSERT(margins.size() == 4);
-        d->leftMargin = margins.at(0).toDouble();
-        d->topMargin = margins.at(1).toDouble();
-        d->rightMargin = margins.at(2).toDouble();
-        d->bottomMargin = margins.at(3).toDouble();
-        d->hasCustomPageMargins = true;
-        break;
-    }
-
-    default:
-        break;
-    }
-}
-
-QVariant QMacPrintEngine::property(PrintEnginePropertyKey key) const
-{
-    Q_D(const QMacPrintEngine);
-    QVariant ret;
-
-    if (!d->session && d->valueCache.contains(key))
-        return *d->valueCache.find(key);
-
-    switch (key) {
-    case PPK_CollateCopies:
-        ret = false;
-        break;
-    case PPK_ColorMode:
-        ret = QPrinter::Color;
-        break;
-    case PPK_Creator:
-        break;
-    case PPK_DocumentName:
-        break;
-    case PPK_FullPage:
-        ret = d->fullPage;
-        break;
-    case PPK_NumberOfCopies:
-        ret = 1;
-        break;
-    case PPK_CopyCount: {
-        UInt32 copies = 1;
-        PMGetCopies(d->settings, &copies);
-        ret = (uint) copies;
-        break;
-    }
-    case PPK_SupportsMultipleCopies:
-        ret = true;
-        break;
-    case PPK_Orientation:
-        PMOrientation orientation;
-        PMGetOrientation(d->format, &orientation);
-        ret = orientation == kPMPortrait ? QPrinter::Portrait : QPrinter::Landscape;
-        break;
-    case PPK_OutputFileName:
-        ret = d->outputFilename;
-        break;
-    case PPK_PageOrder:
-        break;
-    case PPK_PaperSource:
-        break;
-    case PPK_PageRect: {
-        // PageRect is returned in device pixels
-        QRect r;
-        PMRect macrect, macpaper;
-        qreal hRatio = d->resolution.hRes / 72;
-        qreal vRatio = d->resolution.vRes / 72;
-        if (d->hasCustomPaperSize) {
-            r = QRect(0, 0, qRound(d->customSize.width() * hRatio), qRound(d->customSize.height() * vRatio));
-            if (d->hasCustomPageMargins) {
-                r.adjust(qRound(d->leftMargin * hRatio), qRound(d->topMargin * vRatio), 
-                         -qRound(d->rightMargin * hRatio), -qRound(d->bottomMargin * vRatio));
-            } else {
-                QList<QVariant> margins = property(QPrintEngine::PPK_PageMargins).toList();
-                r.adjust(qRound(margins.at(0).toDouble() * hRatio),
-                         qRound(margins.at(1).toDouble() * vRatio),
-                         -qRound(margins.at(2).toDouble() * hRatio),
-                         -qRound(margins.at(3).toDouble()) * vRatio);
-            }
-        } else if (PMGetAdjustedPageRect(d->format, &macrect) == noErr
-                   && PMGetAdjustedPaperRect(d->format, &macpaper) == noErr)
-        {
-            if (d->fullPage || d->hasCustomPageMargins) {
-                r.setCoords(int(macpaper.left * hRatio), int(macpaper.top * vRatio),
-                            int(macpaper.right * hRatio), int(macpaper.bottom * vRatio));
-                r.translate(-r.x(), -r.y());
-                if (d->hasCustomPageMargins) {
-                    r.adjust(qRound(d->leftMargin * hRatio), qRound(d->topMargin * vRatio),
-                             -qRound(d->rightMargin * hRatio), -qRound(d->bottomMargin * vRatio));
-                }
-            } else {
-                r.setCoords(int(macrect.left * hRatio), int(macrect.top * vRatio),
-                            int(macrect.right * hRatio), int(macrect.bottom * vRatio));
-                r.translate(int(-macpaper.left * hRatio), int(-macpaper.top * vRatio));
-            } 
-        }
-        ret = r;
-        break; }
-    case PPK_PaperSize:
-        ret = d->paperSize();
-        break;
-    case PPK_PaperRect: {
-        QRect r;
-        PMRect macrect;
-        qreal hRatio = d->resolution.hRes / 72;
-        qreal vRatio = d->resolution.vRes / 72;
-        if (d->hasCustomPaperSize) {
-            r = QRect(0, 0, qRound(d->customSize.width() * hRatio), qRound(d->customSize.height() * vRatio));
-        } else if (PMGetAdjustedPaperRect(d->format, &macrect) == noErr) {
-            r.setCoords(int(macrect.left * hRatio), int(macrect.top * vRatio),
-                        int(macrect.right * hRatio), int(macrect.bottom * vRatio));
-            r.translate(-r.x(), -r.y());
-        }
-        ret = r;
-        break; }
-    case PPK_PrinterName: {
-        PMPrinter printer;
-        OSStatus status = PMSessionGetCurrentPrinter(d->session, &printer);
-        if (status != noErr)
-            qWarning("QMacPrintEngine::printerName: Failed getting current PMPrinter: %ld", long(status));
-        if (printer)
-            ret = QCFString::toQString(PMPrinterGetName(printer));
-        break; }
-    case PPK_Resolution: {
-        ret = d->resolution.hRes;
-        break;
-    }
-    case PPK_SupportedResolutions:
-        ret = d->supportedResolutions();
-        break;
-    case PPK_CustomPaperSize:
-        ret = d->customSize;
-        break;
-    case PPK_PageMargins:
-    {
-        QList<QVariant> margins;
-        if (d->hasCustomPageMargins) {
-            margins << d->leftMargin << d->topMargin
-                    << d->rightMargin << d->bottomMargin;
-        } else {
-            PMPaperMargins paperMargins;
-            PMPaper paper;
-            PMGetPageFormatPaper(d->format, &paper);
-            PMPaperGetMargins(paper, &paperMargins);
-            margins << paperMargins.left << paperMargins.top
-                    << paperMargins.right << paperMargins.bottom;
-        }
-        ret = margins;
-        break;
-    }
-    default:
-        break;
-    }
-    return ret;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
diff --git a/src/gui/painting/qprintengine_mac_p.h b/src/gui/painting/qprintengine_mac_p.h
deleted file mode 100644 (file)
index c4a64d8..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPRINTENGINE_MAC_P_H
-#define QPRINTENGINE_MAC_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.
-//
-
-#ifndef QT_NO_PRINTER
-
-#include "QtGui/qprinter.h"
-#include "QtGui/qprintengine.h"
-#include "qpaintengine_mac_p.h"
-#include "qpainter_p.h"
-
-#ifdef __OBJC__
-@class NSPrintInfo;
-#else
-typedef void NSPrintInfo;
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QPrinterPrivate;
-class QMacPrintEnginePrivate;
-class QMacPrintEngine : public QPaintEngine, public QPrintEngine
-{
-    Q_DECLARE_PRIVATE(QMacPrintEngine)
-public:
-    QMacPrintEngine(QPrinter::PrinterMode mode);
-
-    Qt::HANDLE handle() const;
-
-    bool begin(QPaintDevice *dev);
-    bool end();
-    virtual QPaintEngine::Type type() const { return QPaintEngine::MacPrinter; }
-
-    QPaintEngine *paintEngine() const;
-
-    void setProperty(PrintEnginePropertyKey key, const QVariant &value);
-    QVariant property(PrintEnginePropertyKey key) const;
-
-    QPrinter::PrinterState printerState() const;
-
-    bool newPage();
-    bool abort();
-    int metric(QPaintDevice::PaintDeviceMetric) const;
-
-    //forwarded functions
-
-    void updateState(const QPaintEngineState &state);
-
-    virtual void drawLines(const QLineF *lines, int lineCount);
-    virtual void drawRects(const QRectF *r, int num);
-    virtual void drawPoints(const QPointF *p, int pointCount);
-    virtual void drawEllipse(const QRectF &r);
-    virtual void drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode);
-    virtual void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
-    virtual void drawImage(const QRectF &r, const QImage &pm, const QRectF &sr, Qt::ImageConversionFlags flags);
-    virtual void drawTextItem(const QPointF &p, const QTextItem &ti);
-    virtual void drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, const QPointF &s);
-    virtual void drawPath(const QPainterPath &);
-
-private:
-    friend class QPrintDialog;
-    friend class QPageSetupDialog;
-};
-
-class QMacPrintEnginePrivate : public QPaintEnginePrivate
-{
-    Q_DECLARE_PUBLIC(QMacPrintEngine)
-public:
-    QPrinter::PrinterMode mode;
-    QPrinter::PrinterState state;
-    QPrinter::Orientation orient;
-    NSPrintInfo *printInfo;
-    PMPageFormat format;
-    PMPrintSettings settings;
-    PMPrintSession session;
-    PMResolution resolution;
-    QString outputFilename;
-    bool fullPage;
-    QPaintEngine *paintEngine;
-    bool suppressStatus;
-    bool hasCustomPaperSize;
-    QSizeF customSize;
-    bool hasCustomPageMargins;
-    qreal leftMargin;
-    qreal topMargin;
-    qreal rightMargin;
-    qreal bottomMargin;
-    QHash<QMacPrintEngine::PrintEnginePropertyKey, QVariant> valueCache;
-    PMPaper customPaper;
-    QMacPrintEnginePrivate() : mode(QPrinter::ScreenResolution), state(QPrinter::Idle),
-                               orient(QPrinter::Portrait), printInfo(0), format(0), settings(0),
-                               session(0), paintEngine(0), suppressStatus(false),
-                               hasCustomPaperSize(false), hasCustomPageMargins(false) {}
-    ~QMacPrintEnginePrivate();
-    void initialize();
-    void releaseSession();
-    bool newPage_helper();
-    void setPaperSize(QPrinter::PaperSize ps);
-    QPrinter::PaperSize paperSize() const;
-    QList<QVariant> supportedResolutions() const;
-    inline bool isPrintSessionInitialized() const
-    {
-#ifndef QT_MAC_USE_COCOA
-        return session != 0;
-#else
-        return printInfo != 0;
-#endif
-    }
-    bool shouldSuppressStatus() const;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
-
-#endif // QPRINTENGINE_WIN_P_H
diff --git a/src/gui/painting/qprintengine_win.cpp b/src/gui/painting/qprintengine_win.cpp
deleted file mode 100644 (file)
index f1218ba..0000000
+++ /dev/null
@@ -1,1776 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QT_NO_PRINTER
-
-#include "qprinter_p.h"
-#include "qprintengine_win_p.h"
-
-#include <limits.h>
-
-#include <qfont_p.h>
-#include <qfontengine_p.h>
-#include <qpainter_p.h>
-
-#include <qbitmap.h>
-#include <qdebug.h>
-#include <qvector.h>
-#include <qpicture.h>
-#include <qpicture_p.h>
-
-QT_BEGIN_NAMESPACE
-
-extern QPainterPath qt_regionToPath(const QRegion &region);
-
-// #define QT_DEBUG_DRAW
-
-static void draw_text_item_win(const QPointF &_pos, const QTextItemInt &ti, HDC hdc,
-                               bool convertToText, const QTransform &xform, const QPointF &topLeft);
-
-static const struct {
-    int winSizeName;
-    QPrinter::PaperSize qtSizeName;
-} dmMapping[] = {
-    { DMPAPER_LETTER,             QPrinter::Letter },
-    { DMPAPER_LETTERSMALL,        QPrinter::Letter },
-    { DMPAPER_TABLOID,            QPrinter::Tabloid },
-    { DMPAPER_LEDGER,             QPrinter::Ledger },
-    { DMPAPER_LEGAL,              QPrinter::Legal },
-    { DMPAPER_EXECUTIVE,          QPrinter::Executive },
-    { DMPAPER_A3,                 QPrinter::A3 },
-    { DMPAPER_A4,                 QPrinter::A4 },
-    { DMPAPER_A4SMALL,            QPrinter::A4 },
-    { DMPAPER_A5,                 QPrinter::A5 },
-    { DMPAPER_B4,                 QPrinter::B4 },
-    { DMPAPER_B5,                 QPrinter::B5 },
-    { DMPAPER_FOLIO,              QPrinter::Folio },
-    { DMPAPER_ENV_10,             QPrinter::Comm10E },
-    { DMPAPER_ENV_DL,             QPrinter::DLE },
-    { DMPAPER_ENV_C3,             QPrinter::C5E },
-    { DMPAPER_LETTER_EXTRA,       QPrinter::Letter },
-    { DMPAPER_LEGAL_EXTRA,        QPrinter::Legal },
-    { DMPAPER_TABLOID_EXTRA,      QPrinter::Tabloid },
-    { DMPAPER_A4_EXTRA,           QPrinter::A4},
-    { DMPAPER_LETTER_TRANSVERSE,  QPrinter::Letter},
-    { DMPAPER_A4_TRANSVERSE,      QPrinter::A4},
-    { DMPAPER_LETTER_EXTRA_TRANSVERSE, QPrinter::Letter },
-    { DMPAPER_A_PLUS,             QPrinter::A4 },
-    { DMPAPER_B_PLUS,             QPrinter::A3 },
-    { DMPAPER_LETTER_PLUS,        QPrinter::Letter },
-    { DMPAPER_A4_PLUS,            QPrinter::A4 },
-    { DMPAPER_A5_TRANSVERSE,      QPrinter::A5 },
-    { DMPAPER_B5_TRANSVERSE,      QPrinter::B5 },
-    { DMPAPER_A3_EXTRA,           QPrinter::A3 },
-    { DMPAPER_A5_EXTRA,           QPrinter::A5 },
-    { DMPAPER_B5_EXTRA,           QPrinter::B5 },
-    { DMPAPER_A2,                 QPrinter::A2 },
-    { DMPAPER_A3_TRANSVERSE,      QPrinter::A3 },
-    { DMPAPER_A3_EXTRA_TRANSVERSE,QPrinter::A3 },
-    { 0, QPrinter::Custom }
-};
-
-QPrinter::PaperSize mapDevmodePaperSize(int s)
-{
-    int i = 0;
-    while ((dmMapping[i].winSizeName > 0) && (dmMapping[i].winSizeName != s))
-        i++;
-    return dmMapping[i].qtSizeName;
-}
-
-static int mapPaperSizeDevmode(QPrinter::PaperSize s)
-{
-    int i = 0;
- while ((dmMapping[i].winSizeName > 0) && (dmMapping[i].qtSizeName != s))
-        i++;
-    return dmMapping[i].winSizeName;
-}
-
-static const struct {
-    int winSourceName;
-    QPrinter::PaperSource qtSourceName;
-}  sources[] = {
-    { DMBIN_ONLYONE,        QPrinter::OnlyOne },
-    { DMBIN_LOWER,          QPrinter::Lower },
-    { DMBIN_MIDDLE,         QPrinter::Middle },
-    { DMBIN_MANUAL,         QPrinter::Manual },
-    { DMBIN_ENVELOPE,       QPrinter::Envelope },
-    { DMBIN_ENVMANUAL,      QPrinter::EnvelopeManual },
-    { DMBIN_AUTO,           QPrinter::Auto },
-    { DMBIN_TRACTOR,        QPrinter::Tractor },
-    { DMBIN_SMALLFMT,       QPrinter::SmallFormat },
-    { DMBIN_LARGEFMT,       QPrinter::LargeFormat },
-    { DMBIN_LARGECAPACITY,  QPrinter::LargeCapacity },
-    { DMBIN_CASSETTE,       QPrinter::Cassette },
-    { DMBIN_FORMSOURCE,     QPrinter::FormSource },
-    { 0, (QPrinter::PaperSource) -1 }
-};
-
-static QPrinter::PaperSource mapDevmodePaperSource(int s)
-{
-    int i = 0;
-    while ((sources[i].winSourceName > 0) && (sources[i].winSourceName != s))
-        i++;
-    return sources[i].winSourceName ? sources[i].qtSourceName : (QPrinter::PaperSource) s;
-}
-
-static int mapPaperSourceDevmode(QPrinter::PaperSource s)
-{
-    int i = 0;
-    while ((sources[i].qtSourceName >= 0) && (sources[i].qtSourceName != s))
-        i++;
-    return sources[i].winSourceName ? sources[i].winSourceName : s;
-}
-
-QWin32PrintEngine::QWin32PrintEngine(QPrinter::PrinterMode mode)
-    : QAlphaPaintEngine(*(new QWin32PrintEnginePrivate),
-                   PaintEngineFeatures(PrimitiveTransform
-                                       | PixmapTransform
-                                       | PerspectiveTransform
-                                       | PainterPaths
-                                       | Antialiasing
-                                       | PaintOutsidePaintEvent))
-{
-    Q_D(QWin32PrintEngine);
-    d->docName = QLatin1String("document1");
-    d->mode = mode;
-    d->queryDefault();
-    d->initialize();
-}
-
-bool QWin32PrintEngine::begin(QPaintDevice *pdev)
-{
-    Q_D(QWin32PrintEngine);
-
-    QAlphaPaintEngine::begin(pdev);
-    if (!continueCall())
-        return true;
-
-    if (d->reinit) {
-       d->resetDC();
-       d->reinit = false;
-    }
-
-    // ### set default colors and stuff...
-
-    bool ok = d->state == QPrinter::Idle;
-
-    if (!d->hdc)
-        return false;
-
-    // Assign the FILE: to get the query...
-    if (d->printToFile && d->fileName.isEmpty())
-        d->fileName = d->port;
-
-    d->devMode->dmCopies = d->num_copies;
-
-    DOCINFO di;
-    memset(&di, 0, sizeof(DOCINFO));
-    di.cbSize = sizeof(DOCINFO);
-    di.lpszDocName = reinterpret_cast<const wchar_t *>(d->docName.utf16());
-    if (d->printToFile && !d->fileName.isEmpty())
-        di.lpszOutput = reinterpret_cast<const wchar_t *>(d->fileName.utf16());
-    if (ok && StartDoc(d->hdc, &di) == SP_ERROR) {
-        qErrnoWarning("QWin32PrintEngine::begin: StartDoc failed");
-        ok = false;
-    }
-
-    if (StartPage(d->hdc) <= 0) {
-        qErrnoWarning("QWin32PrintEngine::begin: StartPage failed");
-        ok = false;
-    }
-
-    if (!ok) {
-        d->state = QPrinter::Idle;
-    } else {
-        d->state = QPrinter::Active;
-    }
-
-    d->matrix = QTransform();
-    d->has_pen = true;
-    d->pen = QColor(Qt::black);
-    d->has_brush = false;
-
-    d->complex_xform = false;
-
-    updateMatrix(d->matrix);
-
-    if (!ok)
-        cleanUp();
-
-    return ok;
-}
-
-bool QWin32PrintEngine::end()
-{
-    Q_D(QWin32PrintEngine);
-
-    if (d->hdc) {
-        if (d->state == QPrinter::Aborted) {
-            cleanUp();
-            AbortDoc(d->hdc);
-            return true;
-        }
-    }
-
-    QAlphaPaintEngine::end();
-    if (!continueCall())
-        return true;
-
-    if (d->hdc) {
-        EndPage(d->hdc);                 // end; printing done
-        EndDoc(d->hdc);
-    }
-
-    d->state = QPrinter::Idle;
-    d->reinit = true;
-    return true;
-}
-
-bool QWin32PrintEngine::newPage()
-{
-    Q_D(QWin32PrintEngine);
-    Q_ASSERT(isActive());
-
-    Q_ASSERT(d->hdc);
-
-    flushAndInit();
-
-    bool transparent = GetBkMode(d->hdc) == TRANSPARENT;
-
-    if (!EndPage(d->hdc)) {
-        qErrnoWarning("QWin32PrintEngine::newPage: EndPage failed");
-        return false;
-    }
-
-    if (d->reinit) {
-        if (!d->resetDC()) {
-            qErrnoWarning("QWin32PrintEngine::newPage: ResetDC failed");
-            return false;
-        }
-        d->reinit = false;
-    }
-
-    if (!StartPage(d->hdc)) {
-        qErrnoWarning("Win32PrintEngine::newPage: StartPage failed");
-        return false;
-    }
-
-    SetTextAlign(d->hdc, TA_BASELINE);
-    if (transparent)
-        SetBkMode(d->hdc, TRANSPARENT);
-
-    // ###
-    return true;
-
-    bool success = false;
-    if (d->hdc && d->state == QPrinter::Active) {
-        if (EndPage(d->hdc) != SP_ERROR) {
-            // reinitialize the DC before StartPage if needed,
-            // because resetdc is disabled between calls to the StartPage and EndPage functions
-            // (see StartPage documentation in the Platform SDK:Windows GDI)
-//          state = PST_ACTIVEDOC;
-//          reinit();
-//          state = PST_ACTIVE;
-            // start the new page now
-            if (d->reinit) {
-                if (!d->resetDC())
-                    qErrnoWarning("QWin32PrintEngine::newPage(), ResetDC failed (2)");
-                d->reinit = false;
-            }
-            success = (StartPage(d->hdc) != SP_ERROR);
-        }
-        if (!success) {
-            d->state = QPrinter::Aborted;
-            return false;
-        }
-    }
-    return true;
-}
-
-bool QWin32PrintEngine::abort()
-{
-    // do nothing loop.
-    return false;
-}
-
-void QWin32PrintEngine::drawTextItem(const QPointF &p, const QTextItem &textItem)
-{
-    Q_D(const QWin32PrintEngine);
-
-    QAlphaPaintEngine::drawTextItem(p, textItem);
-    if (!continueCall())
-        return;
-
-    const QTextItemInt &ti = static_cast<const QTextItemInt &>(textItem);
-    QRgb brushColor = state->pen().brush().color().rgb();
-    bool fallBack = state->pen().brush().style() != Qt::SolidPattern
-                    || qAlpha(brushColor) != 0xff
-                    || d->txop >= QTransform::TxProject
-                    || ti.fontEngine->type() != QFontEngine::Win;
-
-
-    if (!fallBack) {
-        QFontEngineWin *fe = static_cast<QFontEngineWin *>(ti.fontEngine);
-
-        // Try selecting the font to see if we get a substitution font
-        SelectObject(d->hdc, fe->hfont);
-
-        if (GetDeviceCaps(d->hdc, TECHNOLOGY) != DT_CHARSTREAM) {
-            wchar_t n[64];
-            GetTextFace(d->hdc, 64, n);
-            fallBack = QString::fromWCharArray(n)
-                    != QString::fromWCharArray(fe->logfont.lfFaceName);
-        }
-    }
-
-
-    if (fallBack) {
-        QPaintEngine::drawTextItem(p, textItem);
-        return ;
-    }
-
-    // We only want to convert the glyphs to text if the entire string is compatible with ASCII
-    // and if we actually have access to the chars.
-    bool convertToText = ti.chars != 0;
-    for (int i=0;  i < ti.num_chars; ++i) {
-        if (ti.chars[i].unicode() >= 0x80) {
-            convertToText = false;
-            break;
-        }
-
-        if (ti.logClusters[i] != i) {
-            convertToText = false;
-            break;
-        }
-    }
-
-    COLORREF cf = RGB(qRed(brushColor), qGreen(brushColor), qBlue(brushColor));
-    SelectObject(d->hdc, CreateSolidBrush(cf));
-    SelectObject(d->hdc, CreatePen(PS_SOLID, 1, cf));
-    SetTextColor(d->hdc, cf);
-
-    draw_text_item_win(p, ti, d->hdc, convertToText, d->matrix, d->devPaperRect.topLeft());
-    DeleteObject(SelectObject(d->hdc,GetStockObject(HOLLOW_BRUSH)));
-    DeleteObject(SelectObject(d->hdc,GetStockObject(BLACK_PEN)));
-}
-
-static inline qreal mmToInches(double mm)
-{
-    return mm*0.039370147;
-}
-
-static inline qreal inchesToMM(double in)
-{
-    return in/0.039370147;
-}
-
-int QWin32PrintEngine::metric(QPaintDevice::PaintDeviceMetric m) const
-{
-    Q_D(const QWin32PrintEngine);
-
-    if (!d->hdc)
-        return 0;
-
-    int val;
-    int res = d->resolution;
-
-    switch (m) {
-    case QPaintDevice::PdmWidth:
-        if (d->has_custom_paper_size) {
-            val =  qRound(d->paper_size.width() * res / 72.0);
-        } else {
-            int logPixelsX = GetDeviceCaps(d->hdc, LOGPIXELSX);
-            if (logPixelsX == 0) {
-                qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
-                        "might be a driver problem");
-                logPixelsX = 600; // Reasonable default
-            }
-            val = res
-                  * GetDeviceCaps(d->hdc, d->fullPage ? PHYSICALWIDTH : HORZRES)
-                  / logPixelsX;
-        }
-        if (d->pageMarginsSet)
-            val -= int(mmToInches((d->previousDialogMargins.left() +
-                                   d->previousDialogMargins.width()) / 100.0) * res);
-        break;
-    case QPaintDevice::PdmHeight:
-        if (d->has_custom_paper_size) {
-            val = qRound(d->paper_size.height() * res / 72.0);
-        } else {
-            int logPixelsY = GetDeviceCaps(d->hdc, LOGPIXELSY);
-            if (logPixelsY == 0) {
-                qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
-                        "might be a driver problem");
-                logPixelsY = 600; // Reasonable default
-            }
-            val = res
-                  * GetDeviceCaps(d->hdc, d->fullPage ? PHYSICALHEIGHT : VERTRES)
-                  / logPixelsY;
-        }
-        if (d->pageMarginsSet)
-            val -= int(mmToInches((d->previousDialogMargins.top() +
-                                   d->previousDialogMargins.height()) / 100.0) * res);
-        break;
-    case QPaintDevice::PdmDpiX:
-        val = res;
-        break;
-    case QPaintDevice::PdmDpiY:
-        val = res;
-        break;
-    case QPaintDevice::PdmPhysicalDpiX:
-        val = GetDeviceCaps(d->hdc, LOGPIXELSX);
-        break;
-    case QPaintDevice::PdmPhysicalDpiY:
-        val = GetDeviceCaps(d->hdc, LOGPIXELSY);
-        break;
-    case QPaintDevice::PdmWidthMM:
-        if (d->has_custom_paper_size) {
-            val = qRound(d->paper_size.width()*25.4/72);
-        } else {
-            if (!d->fullPage) {
-                val = GetDeviceCaps(d->hdc, HORZSIZE);
-            } else {
-                float wi = 25.4 * GetDeviceCaps(d->hdc, PHYSICALWIDTH);
-                int logPixelsX = GetDeviceCaps(d->hdc,  LOGPIXELSX);
-                if (logPixelsX == 0) {
-                    qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
-                            "might be a driver problem");
-                    logPixelsX = 600; // Reasonable default
-                }
-                val = qRound(wi / logPixelsX);
-            }
-        }
-        if (d->pageMarginsSet)
-            val -= (d->previousDialogMargins.left() +
-                    d->previousDialogMargins.width()) / 100.0;
-        break;
-    case QPaintDevice::PdmHeightMM:
-        if (d->has_custom_paper_size) {
-            val = qRound(d->paper_size.height()*25.4/72);
-        } else {
-            if (!d->fullPage) {
-                val = GetDeviceCaps(d->hdc, VERTSIZE);
-            } else {
-                float hi = 25.4 * GetDeviceCaps(d->hdc, PHYSICALHEIGHT);
-                int logPixelsY = GetDeviceCaps(d->hdc,  LOGPIXELSY);
-                if (logPixelsY == 0) {
-                    qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
-                            "might be a driver problem");
-                    logPixelsY = 600; // Reasonable default
-                }
-                val = qRound(hi / logPixelsY);
-            }
-        }
-        if (d->pageMarginsSet)
-            val -= (d->previousDialogMargins.top() +
-                    d->previousDialogMargins.height()) / 100.0;
-        break;
-    case QPaintDevice::PdmNumColors:
-        {
-            int bpp = GetDeviceCaps(d->hdc, BITSPIXEL);
-            if(bpp==32)
-                val = INT_MAX;
-            else if(bpp<=8)
-                val = GetDeviceCaps(d->hdc, NUMCOLORS);
-            else
-                val = 1 << (bpp * GetDeviceCaps(d->hdc, PLANES));
-        }
-        break;
-    case QPaintDevice::PdmDepth:
-        val = GetDeviceCaps(d->hdc, PLANES);
-        break;
-    default:
-        qWarning("QPrinter::metric: Invalid metric command");
-        return 0;
-    }
-    return val;
-}
-
-void QWin32PrintEngine::updateState(const QPaintEngineState &state)
-{
-    Q_D(QWin32PrintEngine);
-
-    QAlphaPaintEngine::updateState(state);
-    if (!continueCall())
-        return;
-
-    if (state.state() & DirtyTransform) {
-        updateMatrix(state.transform());
-    }
-
-    if (state.state() & DirtyPen) {
-        d->pen = state.pen();
-        d->has_pen = d->pen.style() != Qt::NoPen && d->pen.isSolid();
-    }
-
-    if (state.state() & DirtyBrush) {
-        QBrush brush = state.brush();
-        d->has_brush = brush.style() == Qt::SolidPattern;
-        d->brush_color = brush.color();
-    }
-
-    if (state.state() & DirtyClipEnabled) {
-        if (state.isClipEnabled())
-            updateClipPath(painter()->clipPath(), Qt::ReplaceClip);
-        else
-            updateClipPath(QPainterPath(), Qt::NoClip);
-    }
-
-    if (state.state() & DirtyClipPath) {
-        updateClipPath(state.clipPath(), state.clipOperation());
-    }
-
-    if (state.state() & DirtyClipRegion) {
-        QRegion clipRegion = state.clipRegion();
-        QPainterPath clipPath = qt_regionToPath(clipRegion);
-        updateClipPath(clipPath, state.clipOperation());
-    }
-}
-
-void QWin32PrintEngine::updateClipPath(const QPainterPath &clipPath, Qt::ClipOperation op)
-{
-    Q_D(QWin32PrintEngine);
-
-    bool doclip = true;
-    if (op == Qt::NoClip) {
-        SelectClipRgn(d->hdc, 0);
-        doclip = false;
-    }
-
-    if (doclip) {
-        QPainterPath xformed = clipPath * d->matrix;
-
-        if (xformed.isEmpty()) {
-            QRegion empty(-0x1000000, -0x1000000, 1, 1);
-            SelectClipRgn(d->hdc, empty.handle());
-        } else {
-            d->composeGdiPath(xformed);
-            const int ops[] = {
-                -1,         // Qt::NoClip, covered above
-                RGN_COPY,   // Qt::ReplaceClip
-                RGN_AND,    // Qt::IntersectClip
-                RGN_OR      // Qt::UniteClip
-            };
-            Q_ASSERT(op > 0 && unsigned(op) <= sizeof(ops) / sizeof(int));
-            SelectClipPath(d->hdc, ops[op]);
-        }
-    }
-
-    QPainterPath aclip = qt_regionToPath(alphaClipping());
-    if (!aclip.isEmpty()) {
-        QTransform tx(d->stretch_x, 0, 0, d->stretch_y, d->origin_x, d->origin_y);
-        d->composeGdiPath(tx.map(aclip));
-        SelectClipPath(d->hdc, RGN_DIFF);
-    }
-}
-
-void QWin32PrintEngine::updateMatrix(const QTransform &m)
-{
-    Q_D(QWin32PrintEngine);
-
-    QTransform stretch(d->stretch_x, 0, 0, d->stretch_y, d->origin_x, d->origin_y);
-    d->painterMatrix = m;
-    d->matrix = d->painterMatrix * stretch;
-    d->txop = d->matrix.type();
-    d->complex_xform = (d->txop > QTransform::TxScale);
-}
-
-void QWin32PrintEngine::drawPixmap(const QRectF &targetRect,
-                                   const QPixmap &originalPixmap,
-                                   const QRectF &sourceRect)
-{
-    Q_D(QWin32PrintEngine);
-
-    QAlphaPaintEngine::drawPixmap(targetRect, originalPixmap, sourceRect);
-    if (!continueCall())
-        return;
-
-    const int tileSize = 2048;
-
-    QRectF r = targetRect;
-    QRectF sr = sourceRect;
-
-    QPixmap pixmap = originalPixmap;
-    if (sr.size() != pixmap.size()) {
-        pixmap = pixmap.copy(sr.toRect());
-    }
-
-    qreal scaleX = 1.0f;
-    qreal scaleY = 1.0f;
-
-    QTransform scaleMatrix = QTransform::fromScale(r.width() / pixmap.width(), r.height() / pixmap.height());
-    QTransform adapted = QPixmap::trueMatrix(d->painterMatrix * scaleMatrix,
-                                             pixmap.width(), pixmap.height());
-
-    qreal xform_offset_x = adapted.dx();
-    qreal xform_offset_y = adapted.dy();
-
-    if (d->complex_xform) {
-        pixmap = pixmap.transformed(adapted);
-        scaleX = d->stretch_x;
-        scaleY = d->stretch_y;
-    } else {
-        scaleX = d->stretch_x * (r.width() / pixmap.width()) * d->painterMatrix.m11();
-        scaleY = d->stretch_y * (r.height() / pixmap.height()) * d->painterMatrix.m22();
-    }
-
-    QPointF topLeft = r.topLeft() * d->painterMatrix;
-    int tx = int(topLeft.x() * d->stretch_x + d->origin_x);
-    int ty = int(topLeft.y() * d->stretch_y + d->origin_y);
-    int tw = qAbs(int(pixmap.width() * scaleX));
-    int th = qAbs(int(pixmap.height() * scaleY));
-
-    xform_offset_x *= d->stretch_x;
-    xform_offset_y *= d->stretch_y;
-
-    int dc_state = SaveDC(d->hdc);
-
-    int tilesw = pixmap.width() / tileSize;
-    int tilesh = pixmap.height() / tileSize;
-    ++tilesw;
-    ++tilesh;
-
-    int txinc = tileSize*scaleX;
-    int tyinc = tileSize*scaleY;
-
-    for (int y = 0; y < tilesh; ++y) {
-        int tposy = ty + (y * tyinc);
-        int imgh = tileSize;
-        int height = tyinc;
-        if (y == (tilesh - 1)) {
-            imgh = pixmap.height() - (y * tileSize);
-            height = (th - (y * tyinc));
-        }
-        for (int x = 0; x < tilesw; ++x) {
-            int tposx = tx + (x * txinc);
-            int imgw = tileSize;
-            int width = txinc;
-            if (x == (tilesw - 1)) {
-                imgw = pixmap.width() - (x * tileSize);
-                width = (tw - (x * txinc));
-            }
-
-            QPixmap p = pixmap.copy(tileSize * x, tileSize * y, imgw, imgh);
-            HBITMAP hbitmap = p.toWinHBITMAP(QPixmap::NoAlpha);
-            HDC display_dc = GetDC(0);
-            HDC hbitmap_hdc = CreateCompatibleDC(display_dc);
-            HGDIOBJ null_bitmap = SelectObject(hbitmap_hdc, hbitmap);
-
-            ReleaseDC(0, display_dc);
-
-            if (!StretchBlt(d->hdc, qRound(tposx - xform_offset_x), qRound(tposy - xform_offset_y), width, height,
-                            hbitmap_hdc, 0, 0, p.width(), p.height(), SRCCOPY))
-                qErrnoWarning("QWin32PrintEngine::drawPixmap, StretchBlt failed");
-
-            SelectObject(hbitmap_hdc, null_bitmap);
-            DeleteObject(hbitmap);
-            DeleteDC(hbitmap_hdc);
-        }
-    }
-
-    RestoreDC(d->hdc, dc_state);
-}
-
-
-void QWin32PrintEngine::drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &pos)
-{
-    Q_D(QWin32PrintEngine);
-
-    QAlphaPaintEngine::drawTiledPixmap(r, pm, pos);
-    if (!continueCall())
-        return;
-
-    if (d->complex_xform || !pos.isNull()) {
-        QPaintEngine::drawTiledPixmap(r, pm, pos);
-    } else {
-        int dc_state = SaveDC(d->hdc);
-
-        HDC display_dc = GetDC(0);
-        HBITMAP hbitmap = pm.toWinHBITMAP(QPixmap::NoAlpha);
-        HDC hbitmap_hdc = CreateCompatibleDC(display_dc);
-        HGDIOBJ null_bitmap = SelectObject(hbitmap_hdc, hbitmap);
-
-        ReleaseDC(0, display_dc);
-
-        QRectF trect = d->painterMatrix.mapRect(r);
-        int tx = int(trect.left() * d->stretch_x + d->origin_x);
-        int ty = int(trect.top() * d->stretch_y + d->origin_y);
-
-        int xtiles = int(trect.width() / pm.width()) + 1;
-        int ytiles = int(trect.height() / pm.height()) + 1;
-        int xinc = int(pm.width() * d->stretch_x);
-        int yinc = int(pm.height() * d->stretch_y);
-
-        for (int y = 0; y < ytiles; ++y) {
-            int ity = ty + (yinc * y);
-            int ith = pm.height();
-            if (y == (ytiles - 1)) {
-                ith = int(trect.height() - (pm.height() * y));
-            }
-
-            for (int x = 0; x < xtiles; ++x) {
-                int itx = tx + (xinc * x);
-                int itw = pm.width();
-                if (x == (xtiles - 1)) {
-                    itw = int(trect.width() - (pm.width() * x));
-                }
-
-                if (!StretchBlt(d->hdc, itx, ity, int(itw * d->stretch_x), int(ith * d->stretch_y),
-                                hbitmap_hdc, 0, 0, itw, ith, SRCCOPY))
-                    qErrnoWarning("QWin32PrintEngine::drawPixmap, StretchBlt failed");
-
-            }
-        }
-
-        SelectObject(hbitmap_hdc, null_bitmap);
-        DeleteObject(hbitmap);
-        DeleteDC(hbitmap_hdc);
-
-        RestoreDC(d->hdc, dc_state);
-    }
-}
-
-
-void QWin32PrintEnginePrivate::composeGdiPath(const QPainterPath &path)
-{
-    if (!BeginPath(hdc))
-        qErrnoWarning("QWin32PrintEnginePrivate::drawPath: BeginPath failed");
-
-    // Drawing the subpaths
-    int start = -1;
-    for (int i=0; i<path.elementCount(); ++i) {
-        const QPainterPath::Element &elm = path.elementAt(i);
-        switch (elm.type) {
-        case QPainterPath::MoveToElement:
-            if (start >= 0
-                && path.elementAt(start).x == path.elementAt(i-1).x
-                && path.elementAt(start).y == path.elementAt(i-1).y)
-                CloseFigure(hdc);
-            start = i;
-            MoveToEx(hdc, qRound(elm.x), qRound(elm.y), 0);
-            break;
-        case QPainterPath::LineToElement:
-            LineTo(hdc, qRound(elm.x), qRound(elm.y));
-            break;
-        case QPainterPath::CurveToElement: {
-            POINT pts[3] = {
-                { qRound(elm.x), qRound(elm.y) },
-                { qRound(path.elementAt(i+1).x), qRound(path.elementAt(i+1).y) },
-                { qRound(path.elementAt(i+2).x), qRound(path.elementAt(i+2).y) }
-            };
-            i+=2;
-            PolyBezierTo(hdc, pts, 3);
-            break;
-        }
-        default:
-            qFatal("QWin32PaintEngine::drawPath: Unhandled type: %d", elm.type);
-        }
-    }
-
-    if (start >= 0
-        && path.elementAt(start).x == path.elementAt(path.elementCount()-1).x
-        && path.elementAt(start).y == path.elementAt(path.elementCount()-1).y)
-        CloseFigure(hdc);
-
-    if (!EndPath(hdc))
-        qErrnoWarning("QWin32PaintEngine::drawPath: EndPath failed");
-
-    SetPolyFillMode(hdc, path.fillRule() == Qt::WindingFill ? WINDING : ALTERNATE);
-}
-
-
-void QWin32PrintEnginePrivate::fillPath_dev(const QPainterPath &path, const QColor &color)
-{
-#ifdef QT_DEBUG_DRAW
-    qDebug() << " --- QWin32PrintEnginePrivate::fillPath() bound:" << path.boundingRect() << color;
-#endif
-
-    composeGdiPath(path);
-
-    HBRUSH brush = CreateSolidBrush(RGB(color.red(), color.green(), color.blue()));
-    HGDIOBJ old_brush = SelectObject(hdc, brush);
-    FillPath(hdc);
-    DeleteObject(SelectObject(hdc, old_brush));
-}
-
-void QWin32PrintEnginePrivate::strokePath_dev(const QPainterPath &path, const QColor &color, qreal penWidth)
-{
-    composeGdiPath(path);
-    LOGBRUSH brush;
-    brush.lbStyle = BS_SOLID;
-    brush.lbColor = RGB(color.red(), color.green(), color.blue());
-    DWORD capStyle = PS_ENDCAP_SQUARE;
-    DWORD joinStyle = PS_JOIN_BEVEL;
-    if (pen.capStyle() == Qt::FlatCap)
-        capStyle = PS_ENDCAP_FLAT;
-    else if (pen.capStyle() == Qt::RoundCap)
-        capStyle = PS_ENDCAP_ROUND;
-
-    if (pen.joinStyle() == Qt::MiterJoin)
-        joinStyle = PS_JOIN_MITER;
-    else if (pen.joinStyle() == Qt::RoundJoin)
-        joinStyle = PS_JOIN_ROUND;
-
-    HPEN pen = ExtCreatePen(((penWidth == 0) ? PS_COSMETIC : PS_GEOMETRIC)
-                            | PS_SOLID | capStyle | joinStyle,
-                            (penWidth == 0) ? 1 : penWidth, &brush, 0, 0);
-
-    HGDIOBJ old_pen = SelectObject(hdc, pen);
-    StrokePath(hdc);
-    DeleteObject(SelectObject(hdc, old_pen));
-}
-
-
-void QWin32PrintEnginePrivate::fillPath(const QPainterPath &path, const QColor &color)
-{
-    fillPath_dev(path * matrix, color);
-}
-
-void QWin32PrintEnginePrivate::strokePath(const QPainterPath &path, const QColor &color)
-{
-    QPainterPathStroker stroker;
-    if (pen.style() == Qt::CustomDashLine) {
-        stroker.setDashPattern(pen.dashPattern());
-        stroker.setDashOffset(pen.dashOffset());
-    } else {
-        stroker.setDashPattern(pen.style());
-    }
-    stroker.setCapStyle(pen.capStyle());
-    stroker.setJoinStyle(pen.joinStyle());
-    stroker.setMiterLimit(pen.miterLimit());
-
-    QPainterPath stroke;
-    qreal width = pen.widthF();
-    if (pen.style() == Qt::SolidLine && (pen.isCosmetic() || matrix.type() < QTransform::TxScale)) {
-        strokePath_dev(path * matrix, color, width);
-    } else {
-        stroker.setWidth(width);
-        if (pen.isCosmetic()) {
-            stroke = stroker.createStroke(path * matrix);
-        } else {
-            stroke = stroker.createStroke(path) * painterMatrix;
-            QTransform stretch(stretch_x, 0, 0, stretch_y, origin_x, origin_y);
-            stroke = stroke * stretch;
-        }
-
-        if (stroke.isEmpty())
-            return;
-
-        fillPath_dev(stroke, color);
-    }
-}
-
-
-void QWin32PrintEngine::drawPath(const QPainterPath &path)
-{
-#ifdef QT_DEBUG_DRAW
-    qDebug() << " - QWin32PrintEngine::drawPath(), bounds: " << path.boundingRect();
-#endif
-
-    Q_D(QWin32PrintEngine);
-
-    QAlphaPaintEngine::drawPath(path);
-    if (!continueCall())
-        return;
-
-    if (d->has_brush)
-        d->fillPath(path, d->brush_color);
-
-    if (d->has_pen)
-        d->strokePath(path, d->pen.color());
-}
-
-
-void QWin32PrintEngine::drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode)
-{
-#ifdef QT_DEBUG_DRAW
-    qDebug() << " - QWin32PrintEngine::drawPolygon(), pointCount: " << pointCount;
-#endif
-
-    QAlphaPaintEngine::drawPolygon(points, pointCount, mode);
-    if (!continueCall())
-        return;
-
-    Q_ASSERT(pointCount > 1);
-
-    QPainterPath path(points[0]);
-
-    for (int i=1; i<pointCount; ++i) {
-        path.lineTo(points[i]);
-    }
-
-    Q_D(QWin32PrintEngine);
-
-    bool has_brush = d->has_brush;
-
-    if (mode == PolylineMode)
-        d->has_brush = false; // No brush for polylines
-    else
-        path.closeSubpath(); // polygons are should always be closed.
-
-    drawPath(path);
-    d->has_brush = has_brush;
-}
-
-void QWin32PrintEnginePrivate::queryDefault()
-{
-    /* Read the default printer name, driver and port with the intuitive function
-     * Strings "windows" and "device" are specified in the MSDN under EnumPrinters()
-     */
-    QString noPrinters(QLatin1String("qt_no_printers"));
-    wchar_t buffer[256];
-    GetProfileString(L"windows", L"device",
-                     reinterpret_cast<const wchar_t *>(noPrinters.utf16()),
-                     buffer, 256);
-    QString output = QString::fromWCharArray(buffer);
-    if (output.isEmpty() || output == noPrinters) // no printers
-        return;
-
-    QStringList info = output.split(QLatin1Char(','));
-    int infoSize = info.size();
-    if (infoSize > 0) {
-        if (name.isEmpty())
-            name = info.at(0);
-        if (program.isEmpty() && infoSize > 1)
-            program = info.at(1);
-        if (port.isEmpty() && infoSize > 2)
-            port = info.at(2);
-    }
-}
-
-QWin32PrintEnginePrivate::~QWin32PrintEnginePrivate()
-{
-    if (hdc)
-        release();
-}
-
-void QWin32PrintEnginePrivate::initialize()
-{
-    if (hdc)
-        release();
-    Q_ASSERT(!hPrinter);
-    Q_ASSERT(!hdc);
-    Q_ASSERT(!devMode);
-    Q_ASSERT(!pInfo);
-
-    if (name.isEmpty())
-        return;
-
-    txop = QTransform::TxNone;
-
-    bool ok = OpenPrinter((LPWSTR)name.utf16(), (LPHANDLE)&hPrinter, 0);
-    if (!ok) {
-        qErrnoWarning("QWin32PrintEngine::initialize: OpenPrinter failed");
-        return;
-    }
-
-    // Fetch the PRINTER_INFO_2 with DEVMODE data containing the
-    // printer settings.
-    DWORD infoSize, numBytes;
-    GetPrinter(hPrinter, 2, NULL, 0, &infoSize);
-    hMem = GlobalAlloc(GHND, infoSize);
-    pInfo = (PRINTER_INFO_2*) GlobalLock(hMem);
-    ok = GetPrinter(hPrinter, 2, (LPBYTE)pInfo, infoSize, &numBytes);
-
-    if (!ok) {
-        qErrnoWarning("QWin32PrintEngine::initialize: GetPrinter failed");
-        GlobalUnlock(pInfo);
-        GlobalFree(hMem);
-        ClosePrinter(hPrinter);
-        pInfo = 0;
-        hMem = 0;
-        hPrinter = 0;
-        return;
-    }
-
-    devMode = pInfo->pDevMode;
-    hdc = CreateDC(reinterpret_cast<const wchar_t *>(program.utf16()),
-                   reinterpret_cast<const wchar_t *>(name.utf16()), 0, devMode);
-
-    Q_ASSERT(hPrinter);
-    Q_ASSERT(pInfo);
-
-    if (devMode) {
-        num_copies = devMode->dmCopies;
-    }
-
-    initHDC();
-
-#ifdef QT_DEBUG_DRAW
-    qDebug() << "QWin32PrintEngine::initialize()" << endl
-             << " - paperRect" << devPaperRect << endl
-             << " - pageRect" << devPageRect << endl
-             << " - stretch_x" << stretch_x << endl
-             << " - stretch_y" << stretch_y << endl
-             << " - origin_x" << origin_x << endl
-             << " - origin_y" << origin_y << endl;
-#endif
-}
-
-void QWin32PrintEnginePrivate::initHDC()
-{
-    Q_ASSERT(hdc);
-
-    HDC display_dc = GetDC(0);
-    dpi_x = GetDeviceCaps(hdc, LOGPIXELSX);
-    dpi_y = GetDeviceCaps(hdc, LOGPIXELSY);
-    dpi_display = GetDeviceCaps(display_dc, LOGPIXELSY);
-    ReleaseDC(0, display_dc);
-    if (dpi_display == 0) {
-        qWarning("QWin32PrintEngine::metric: GetDeviceCaps() failed, "
-                "might be a driver problem");
-        dpi_display = 96; // Reasonable default
-    }
-
-    switch(mode) {
-    case QPrinter::ScreenResolution:
-        resolution = dpi_display;
-        stretch_x = dpi_x / double(dpi_display);
-        stretch_y = dpi_y / double(dpi_display);
-        break;
-    case QPrinter::PrinterResolution:
-    case QPrinter::HighResolution:
-        resolution = dpi_y;
-        stretch_x = 1;
-        stretch_y = 1;
-        break;
-    default:
-        break;
-    }
-
-    initDevRects();
-}
-
-void QWin32PrintEnginePrivate::initDevRects()
-{
-    devPaperRect = QRect(0, 0,
-                         GetDeviceCaps(hdc, PHYSICALWIDTH),
-                         GetDeviceCaps(hdc, PHYSICALHEIGHT));
-    devPhysicalPageRect = QRect(GetDeviceCaps(hdc, PHYSICALOFFSETX),
-                                GetDeviceCaps(hdc, PHYSICALOFFSETY),
-                                GetDeviceCaps(hdc, HORZRES),
-                                GetDeviceCaps(hdc, VERTRES));
-    if (!pageMarginsSet)
-        devPageRect = devPhysicalPageRect;
-    else
-        devPageRect = devPaperRect.adjusted(qRound(mmToInches(previousDialogMargins.left() / 100.0) * dpi_x),
-                                            qRound(mmToInches(previousDialogMargins.top() / 100.0) * dpi_y),
-                                            -qRound(mmToInches(previousDialogMargins.width() / 100.0) * dpi_x),
-                                            -qRound(mmToInches(previousDialogMargins.height() / 100.0) * dpi_y));
-    updateOrigin();
-}
-
-void QWin32PrintEnginePrivate::setPageMargins(int marginLeft, int marginTop, int marginRight, int marginBottom)
-{
-    pageMarginsSet = true;
-    previousDialogMargins = QRect(marginLeft, marginTop, marginRight, marginBottom);
-
-    devPageRect = devPaperRect.adjusted(qRound(mmToInches(marginLeft / 100.0) * dpi_x),
-                                        qRound(mmToInches(marginTop / 100.0) * dpi_y),
-                                        - qRound(mmToInches(marginRight / 100.0) * dpi_x),
-                                        - qRound(mmToInches(marginBottom / 100.0) * dpi_y));
-    updateOrigin();
-}
-
-QRect QWin32PrintEnginePrivate::getPageMargins() const
-{
-    if (pageMarginsSet)
-        return previousDialogMargins;
-    else
-        return QRect(qRound(inchesToMM(devPhysicalPageRect.left()) * 100.0 / dpi_x),
-                     qRound(inchesToMM(devPhysicalPageRect.top()) * 100.0 / dpi_y),
-                     qRound(inchesToMM(devPaperRect.right() - devPhysicalPageRect.right()) * 100.0 / dpi_x),
-                     qRound(inchesToMM(devPaperRect.bottom() - devPhysicalPageRect.bottom()) * 100.0 / dpi_y));
-}
-
-void QWin32PrintEnginePrivate::release()
-{
-    if (hdc == 0)
-        return;
-
-    if (globalDevMode) { // Devmode comes from print dialog
-        GlobalUnlock(globalDevMode);
-    } else {            // Devmode comes from initialize...
-        // devMode is a part of the same memory block as pInfo so one free is enough...
-        GlobalUnlock(hMem);
-        GlobalFree(hMem);
-    }
-    if (hPrinter)
-        ClosePrinter(hPrinter);
-    DeleteDC(hdc);
-
-    hdc = 0;
-    hPrinter = 0;
-    pInfo = 0;
-    hMem = 0;
-    devMode = 0;
-}
-
-QList<QVariant> QWin32PrintEnginePrivate::queryResolutions() const
-{
-    // Read the supported resolutions of the printer.
-    QList<QVariant> list;
-
-    DWORD numRes = DeviceCapabilities(reinterpret_cast<const wchar_t *>(name.utf16()),
-                                      reinterpret_cast<const wchar_t *>(port.utf16()),
-                                      DC_ENUMRESOLUTIONS, 0, 0);
-    if (numRes == (DWORD)-1)
-        return list;
-
-    LONG *enumRes = (LONG*)malloc(numRes * 2 * sizeof(LONG));
-    DWORD errRes = DeviceCapabilities(reinterpret_cast<const wchar_t *>(name.utf16()),
-                                      reinterpret_cast<const wchar_t *>(port.utf16()),
-                                      DC_ENUMRESOLUTIONS, (LPWSTR)enumRes, 0);
-
-    if (errRes == (DWORD)-1) {
-        qErrnoWarning("QWin32PrintEngine::queryResolutions: DeviceCapabilities failed");
-        return list;
-    }
-
-    for (uint i=0; i<numRes; ++i)
-        list.append(int(enumRes[i * 2]));
-
-    return list;
-}
-
-void QWin32PrintEnginePrivate::doReinit()
-{
-    if (state == QPrinter::Active) {
-        reinit = true;
-    } else {
-        resetDC();
-        initDevRects();
-        reinit = false;
-    }
-}
-
-void QWin32PrintEnginePrivate::updateOrigin()
-{
-    if (fullPage) {
-        // subtract physical margins to make (0,0) absolute top corner of paper
-        // then add user defined margins
-        origin_x = -devPhysicalPageRect.x();
-        origin_y = -devPhysicalPageRect.y();
-        if (pageMarginsSet) {
-            origin_x += devPageRect.left();
-            origin_y += devPageRect.top();
-        }
-    } else {
-        origin_x = 0;
-        origin_y = 0;
-        if (pageMarginsSet) {
-            origin_x = devPageRect.left() - devPhysicalPageRect.x();
-            origin_y = devPageRect.top() - devPhysicalPageRect.y();
-        }
-    }
-}
-
-void QWin32PrintEngine::setProperty(PrintEnginePropertyKey key, const QVariant &value)
-{
-    Q_D(QWin32PrintEngine);
-    switch (key) {
-    case PPK_CollateCopies:
-        {
-            if (!d->devMode)
-                break;
-            d->devMode->dmCollate = value.toBool() ? DMCOLLATE_TRUE : DMCOLLATE_FALSE;
-            d->doReinit();
-        }
-        break;
-
-    case PPK_ColorMode:
-        {
-            if (!d->devMode)
-                break;
-            d->devMode->dmColor = (value.toInt() == QPrinter::Color) ? DMCOLOR_COLOR : DMCOLOR_MONOCHROME;
-            d->doReinit();
-        }
-        break;
-
-    case PPK_Creator:
-
-        break;
-
-    case PPK_DocumentName:
-        if (isActive()) {
-            qWarning("QWin32PrintEngine: Cannot change document name while printing is active");
-            return;
-        }
-        d->docName = value.toString();
-        break;
-
-    case PPK_FullPage:
-        d->fullPage = value.toBool();
-        d->updateOrigin();
-        break;
-
-    case PPK_CopyCount: // fallthrough
-    case PPK_NumberOfCopies:
-        if (!d->devMode)
-            break;
-        d->num_copies = value.toInt();
-        d->devMode->dmCopies = d->num_copies;
-        d->doReinit();
-        break;
-
-    case PPK_Orientation:
-        {
-            if (!d->devMode)
-                break;
-            int orientation = value.toInt() == QPrinter::Landscape ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT;
-            int old_orientation = d->devMode->dmOrientation;
-            d->devMode->dmOrientation = orientation;
-            if (d->has_custom_paper_size && old_orientation != orientation)
-                d->paper_size = QSizeF(d->paper_size.height(), d->paper_size.width());
-            d->doReinit();
-        }
-        break;
-
-    case PPK_OutputFileName:
-        if (isActive()) {
-            qWarning("QWin32PrintEngine: Cannot change filename while printing");
-        } else {
-            d->fileName = value.toString();
-            d->printToFile = !value.toString().isEmpty();
-        }
-        break;
-
-    case PPK_PaperSize:
-        if (!d->devMode)
-            break;
-        d->devMode->dmPaperSize = mapPaperSizeDevmode(QPrinter::PaperSize(value.toInt()));
-        d->has_custom_paper_size = (QPrinter::PaperSize(value.toInt()) == QPrinter::Custom);
-        d->doReinit();
-        break;
-
-    case PPK_PaperSource:
-        {
-            if (!d->devMode)
-                break;
-            int dmMapped = DMBIN_AUTO;
-
-            QList<QVariant> v = property(PPK_PaperSources).toList();
-            if (v.contains(value))
-                dmMapped = mapPaperSourceDevmode(QPrinter::PaperSource(value.toInt()));
-
-            d->devMode->dmDefaultSource = dmMapped;
-            d->doReinit();
-        }
-        break;
-
-    case PPK_PrinterName:
-        d->name = value.toString();
-        if(d->name.isEmpty())
-            d->queryDefault();
-        d->initialize();
-        break;
-
-    case PPK_Resolution:
-        {
-            d->resolution = value.toInt();
-
-            d->stretch_x = d->dpi_x / double(d->resolution);
-            d->stretch_y = d->dpi_y / double(d->resolution);
-        }
-        break;
-
-    case PPK_SelectionOption:
-
-        break;
-
-    case PPK_SupportedResolutions:
-
-        break;
-
-
-    case PPK_WindowsPageSize:
-        if (!d->devMode)
-            break;
-        d->has_custom_paper_size = false;
-        d->devMode->dmPaperSize = value.toInt();
-        d->doReinit();
-        break;
-
-    case PPK_CustomPaperSize:
-    {
-        d->has_custom_paper_size = true;
-        d->paper_size = value.toSizeF();
-        if (!d->devMode)
-            break;
-        int orientation = d->devMode->dmOrientation;
-        DWORD needed = 0;
-        DWORD returned = 0;
-        if (!EnumForms(d->hPrinter, 1, 0, 0, &needed, &returned)) {
-            BYTE *forms = (BYTE *) malloc(needed);
-            if (EnumForms(d->hPrinter, 1, forms, needed, &needed, &returned)) {
-                for (DWORD i=0; i< returned; ++i) {
-                    FORM_INFO_1 *formArray = reinterpret_cast<FORM_INFO_1 *>(forms);
-                    // the form sizes are specified in 1000th of a mm,
-                    // convert the size to Points
-                    QSizeF size((formArray[i].Size.cx * 72/25.4)/1000.0,
-                                (formArray[i].Size.cy * 72/25.4)/1000.0);
-                    if (qAbs(d->paper_size.width() - size.width()) <= 2
-                        && qAbs(d->paper_size.height() - size.height()) <= 2)
-                    {
-                        d->devMode->dmPaperSize = i + 1;
-                        break;
-                    }
-                }
-            }
-            free(forms);
-        }
-        if (orientation != DMORIENT_PORTRAIT)
-            d->paper_size = QSizeF(d->paper_size.height(), d->paper_size.width());
-        break;
-    }
-
-    case PPK_PageMargins:
-    {
-        QList<QVariant> margins(value.toList());
-        Q_ASSERT(margins.size() == 4);
-        int left, top, right, bottom;
-        // specified in 1/100 mm
-        left = (margins.at(0).toReal()*25.4/72.0) * 100;
-        top = (margins.at(1).toReal()*25.4/72.0) * 100;
-        right = (margins.at(2).toReal()*25.4/72.0) * 100;
-        bottom = (margins.at(3).toReal()*25.4/72.0) * 100;
-        d->setPageMargins(left, top, right, bottom);
-        break;
-    }
-    default:
-        // Do nothing
-        break;
-    }
-}
-
-QVariant QWin32PrintEngine::property(PrintEnginePropertyKey key) const
-{
-    Q_D(const QWin32PrintEngine);
-    QVariant value;
-    switch (key) {
-
-    case PPK_CollateCopies:
-        value = false;
-        break;
-
-    case PPK_ColorMode:
-        {
-            if (!d->devMode) {
-                value = QPrinter::Color;
-            } else {
-                value = (d->devMode->dmColor == DMCOLOR_COLOR) ? QPrinter::Color : QPrinter::GrayScale;
-            }
-        }
-        break;
-
-    case PPK_DocumentName:
-        value = d->docName;
-        break;
-
-    case PPK_FullPage:
-        value = d->fullPage;
-        break;
-
-    case PPK_CopyCount:
-        value = d->num_copies;
-        break;
-
-    case PPK_SupportsMultipleCopies:
-        value = true;
-        break;
-
-    case PPK_NumberOfCopies:
-        value = 1;
-        break;
-
-    case PPK_Orientation:
-        {
-            if (!d->devMode) {
-                value = QPrinter::Portrait;
-            } else {
-                value = (d->devMode->dmOrientation == DMORIENT_LANDSCAPE) ? QPrinter::Landscape : QPrinter::Portrait;
-            }
-        }
-        break;
-
-    case PPK_OutputFileName:
-        value = d->fileName;
-        break;
-
-    case PPK_PageRect:
-        if (d->has_custom_paper_size) {
-            QRect rect(0, 0,
-                       qRound(d->paper_size.width() * d->resolution / 72.0),
-                       qRound(d->paper_size.height() * d->resolution / 72.0));
-            if (d->pageMarginsSet) {
-                rect = rect.adjusted(qRound(mmToInches(d->previousDialogMargins.left()/100.0) * d->resolution),
-                                     qRound(mmToInches(d->previousDialogMargins.top()/100.0) * d->resolution),
-                                     -qRound(mmToInches(d->previousDialogMargins.width()/100.0) * d->resolution),
-                                     -qRound(mmToInches(d->previousDialogMargins.height()/100.0) * d->resolution));
-            }
-            value = rect;
-        } else {
-            value = QTransform(1/d->stretch_x, 0, 0, 1/d->stretch_y, 0, 0)
-                    .mapRect(d->fullPage ? d->devPhysicalPageRect : d->devPageRect);
-        }
-        break;
-
-    case PPK_PaperSize:
-        if (d->has_custom_paper_size) {
-            value = QPrinter::Custom;
-        } else {
-            if (!d->devMode) {
-                value = QPrinter::A4;
-            } else {
-                value = mapDevmodePaperSize(d->devMode->dmPaperSize);
-            }
-        }
-        break;
-
-    case PPK_PaperRect:
-        if (d->has_custom_paper_size) {
-            value = QRect(0, 0,
-                          qRound(d->paper_size.width() * d->resolution / 72.0),
-                          qRound(d->paper_size.height() * d->resolution / 72.0));
-        } else {
-            value = QTransform(1/d->stretch_x, 0, 0, 1/d->stretch_y, 0, 0).mapRect(d->devPaperRect);
-        }
-        break;
-
-    case PPK_PaperSource:
-        if (!d->devMode) {
-            value = QPrinter::Auto;
-        } else {
-            value = mapDevmodePaperSource(d->devMode->dmDefaultSource);
-        }
-        break;
-
-    case PPK_PrinterName:
-        value = d->name;
-        break;
-
-    case PPK_Resolution:
-        if (d->resolution || !d->name.isEmpty())
-            value = d->resolution;
-        break;
-
-    case PPK_SupportedResolutions:
-        value = d->queryResolutions();
-        break;
-
-    case PPK_WindowsPageSize:
-        if (!d->devMode) {
-            value = -1;
-        } else {
-            value = d->devMode->dmPaperSize;
-        }
-        break;
-
-    case PPK_PaperSources:
-        {
-            int available = DeviceCapabilities((const wchar_t *)d->name.utf16(),
-                                               (const wchar_t *)d->port.utf16(), DC_BINS, 0, d->devMode);
-
-            if (available <= 0)
-                break;
-
-            wchar_t *data = new wchar_t[available];
-            int count = DeviceCapabilities((const wchar_t *)d->name.utf16(),
-                                           (const wchar_t *)d->port.utf16(), DC_BINS, data, d->devMode);
-
-            QList<QVariant> out;
-            for (int i=0; i<count; ++i) {
-                QPrinter::PaperSource src = mapDevmodePaperSource(data[i]);
-                if (src != -1)
-                    out << (int) src;
-            }
-            value = out;
-
-            delete [] data;
-        }
-        break;
-
-    case PPK_CustomPaperSize:
-        value = d->paper_size;
-        break;
-
-    case PPK_PageMargins:
-    {
-        QList<QVariant> margins;
-        QRect pageMargins(d->getPageMargins());
-
-        // specified in 1/100 mm
-        margins << (mmToInches(pageMargins.left()/100.0) * 72)
-                << (mmToInches(pageMargins.top()/100.0) * 72)
-                << (mmToInches(pageMargins.width()/100.0) * 72)
-                << (mmToInches(pageMargins.height()/100.0) * 72);
-        value = margins;
-        break;
-    }
-    default:
-        // Do nothing
-        break;
-    }
-    return value;
-}
-
-QPrinter::PrinterState QWin32PrintEngine::printerState() const
-{
-    return d_func()->state;
-}
-
-HDC QWin32PrintEngine::getDC() const
-{
-    return d_func()->hdc;
-}
-
-void QWin32PrintEngine::releaseDC(HDC) const
-{
-
-}
-
-HGLOBAL *QWin32PrintEnginePrivate::createDevNames()
-{
-    int size = sizeof(DEVNAMES)
-               + program.length() * 2 + 2
-               + name.length() * 2 + 2
-               + port.length() * 2 + 2;
-    HGLOBAL *hGlobal = (HGLOBAL *) GlobalAlloc(GMEM_MOVEABLE, size);
-    DEVNAMES *dn = (DEVNAMES*) GlobalLock(hGlobal);
-
-    dn->wDriverOffset = sizeof(DEVNAMES) / sizeof(wchar_t);
-    dn->wDeviceOffset = dn->wDriverOffset + program.length() + 1;
-    dn->wOutputOffset = dn->wDeviceOffset + name.length() + 1;
-
-    memcpy((ushort*)dn + dn->wDriverOffset, program.utf16(), program.length() * 2 + 2);
-    memcpy((ushort*)dn + dn->wDeviceOffset, name.utf16(), name.length() * 2 + 2);
-    memcpy((ushort*)dn + dn->wOutputOffset, port.utf16(), port.length() * 2 + 2);
-    dn->wDefault = 0;
-
-    GlobalUnlock(hGlobal);
-
-//         printf("QPrintDialogWinPrivate::createDevNames()\n"
-//                " -> wDriverOffset: %d\n"
-//                " -> wDeviceOffset: %d\n"
-//                " -> wOutputOffset: %d\n",
-//                dn->wDriverOffset,
-//                dn->wDeviceOffset,
-//                dn->wOutputOffset);
-
-//         printf("QPrintDialogWinPrivate::createDevNames(): %s, %s, %s\n",
-//                QString::fromWCharArray((wchar_t*)(dn) + dn->wDriverOffset).latin1(),
-//                QString::fromWCharArray((wchar_t*)(dn) + dn->wDeviceOffset).latin1(),
-//                QString::fromWCharArray((wchar_t*)(dn) + dn->wOutputOffset).latin1());
-
-    return hGlobal;
-}
-
-void QWin32PrintEnginePrivate::readDevnames(HGLOBAL globalDevnames)
-{
-    if (globalDevnames) {
-        DEVNAMES *dn = (DEVNAMES*) GlobalLock(globalDevnames);
-        name = QString::fromWCharArray((wchar_t*)(dn) + dn->wDeviceOffset);
-        port = QString::fromWCharArray((wchar_t*)(dn) + dn->wOutputOffset);
-        program = QString::fromWCharArray((wchar_t*)(dn) + dn->wDriverOffset);
-        GlobalUnlock(globalDevnames);
-    }
-}
-
-void QWin32PrintEnginePrivate::readDevmode(HGLOBAL globalDevmode)
-{
-    if (globalDevmode) {
-        DEVMODE *dm = (DEVMODE*) GlobalLock(globalDevmode);
-        release();
-        globalDevMode = globalDevmode;
-        devMode = dm;
-        hdc = CreateDC(reinterpret_cast<const wchar_t *>(program.utf16()),
-                       reinterpret_cast<const wchar_t *>(name.utf16()), 0, dm);
-
-        num_copies = devMode->dmCopies;
-        if (!OpenPrinter((wchar_t*)name.utf16(), &hPrinter, 0))
-            qWarning("QPrinter: OpenPrinter() failed after reading DEVMODE.");
-    }
-
-    if (hdc)
-        initHDC();
-}
-
-static void draw_text_item_win(const QPointF &pos, const QTextItemInt &ti, HDC hdc,
-                               bool convertToText, const QTransform &xform, const QPointF &topLeft)
-{
-    QFontEngine *fe = ti.fontEngine;
-    QPointF baseline_pos = xform.inverted().map(xform.map(pos) - topLeft);
-
-    SetTextAlign(hdc, TA_BASELINE);
-    SetBkMode(hdc, TRANSPARENT);
-
-    bool has_kerning = ti.f && ti.f->kerning();
-    QFontEngineWin *winfe = (fe->type() == QFontEngine::Win) ? static_cast<QFontEngineWin *>(fe) : 0;
-
-    HFONT hfont;
-    bool ttf = false;
-
-    if (winfe) {
-        hfont = winfe->hfont;
-        ttf = winfe->ttf;
-    } else {
-        hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
-    }
-
-    HGDIOBJ old_font = SelectObject(hdc, hfont);
-    unsigned int options = (ttf && !convertToText) ? ETO_GLYPH_INDEX : 0;
-    wchar_t *convertedGlyphs = (wchar_t *)ti.chars;
-    QGlyphLayout glyphs = ti.glyphs;
-
-    bool fast = !has_kerning && !(ti.flags & QTextItem::RightToLeft);
-    for (int i = 0; fast && i < glyphs.numGlyphs; i++) {
-        if (glyphs.offsets[i].x != 0 || glyphs.offsets[i].y != 0 || glyphs.justifications[i].space_18d6 != 0
-            || glyphs.attributes[i].dontPrint) {
-            fast = false;
-            break;
-        }
-    }
-
-#if !defined(Q_OS_WINCE)
-    // Scale, rotate and translate here.
-    XFORM win_xform;
-    win_xform.eM11 = xform.m11();
-    win_xform.eM12 = xform.m12();
-    win_xform.eM21 = xform.m21();
-    win_xform.eM22 = xform.m22();
-    win_xform.eDx = xform.dx();
-    win_xform.eDy = xform.dy();
-
-    SetGraphicsMode(hdc, GM_ADVANCED);
-    SetWorldTransform(hdc, &win_xform);
-#endif
-
-    if (fast) {
-        // fast path
-        QVarLengthArray<wchar_t> g(glyphs.numGlyphs);
-        for (int i = 0; i < glyphs.numGlyphs; ++i)
-            g[i] = glyphs.glyphs[i];
-        ExtTextOut(hdc,
-                   qRound(baseline_pos.x() + glyphs.offsets[0].x.toReal()),
-                   qRound(baseline_pos.y() + glyphs.offsets[0].y.toReal()),
-                   options, 0, convertToText ? convertedGlyphs : g.data(), glyphs.numGlyphs, 0);
-    } else {
-        QVarLengthArray<QFixedPoint> positions;
-        QVarLengthArray<glyph_t> _glyphs;
-
-        QTransform matrix = QTransform::fromTranslate(baseline_pos.x(), baseline_pos.y());
-        ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags,
-            _glyphs, positions);
-        if (_glyphs.size() == 0) {
-            SelectObject(hdc, old_font);
-            return;
-        }
-
-        convertToText = convertToText && glyphs.numGlyphs == _glyphs.size();
-        bool outputEntireItem = _glyphs.size() > 0;
-
-        if (outputEntireItem) {
-            options |= ETO_PDY;
-            QVarLengthArray<INT> glyphDistances(_glyphs.size() * 2);
-            QVarLengthArray<wchar_t> g(_glyphs.size());
-            for (int i=0; i<_glyphs.size() - 1; ++i) {
-                glyphDistances[i * 2] = qRound(positions[i + 1].x) - qRound(positions[i].x);
-                glyphDistances[i * 2 + 1] = qRound(positions[i + 1].y) - qRound(positions[i].y);
-                g[i] = _glyphs[i];
-            }
-            glyphDistances[(_glyphs.size() - 1) * 2] = 0;
-            glyphDistances[(_glyphs.size() - 1) * 2 + 1] = 0;
-            g[_glyphs.size() - 1] = _glyphs[_glyphs.size() - 1];
-            ExtTextOut(hdc, qRound(positions[0].x), qRound(positions[0].y), options, 0,
-                       convertToText ? convertedGlyphs : g.data(), _glyphs.size(),
-                       glyphDistances.data());
-        } else {
-            int i = 0;
-            while(i < _glyphs.size()) {
-                wchar_t g = _glyphs[i];
-
-                ExtTextOut(hdc, qRound(positions[i].x),
-                           qRound(positions[i].y), options, 0,
-                           convertToText ? convertedGlyphs + i : &g, 1, 0);
-                ++i;
-            }
-        }
-    }
-
-#if !defined(Q_OS_WINCE)
-        win_xform.eM11 = win_xform.eM22 = 1.0;
-        win_xform.eM12 = win_xform.eM21 = win_xform.eDx = win_xform.eDy = 0.0;
-        SetWorldTransform(hdc, &win_xform);
-#endif
-
-    SelectObject(hdc, old_font);
-}
-
-
-void QWin32PrintEnginePrivate::updateCustomPaperSize()
-{
-    uint paperSize = devMode->dmPaperSize;
-    if (paperSize > 0 && mapDevmodePaperSize(paperSize) == QPrinter::Custom) {
-        has_custom_paper_size = true;
-        DWORD needed = 0;
-        DWORD returned = 0;
-        if (!EnumForms(hPrinter, 1, 0, 0, &needed, &returned)) {
-            BYTE *forms = (BYTE *) malloc(needed);
-            if (EnumForms(hPrinter, 1, forms, needed, &needed, &returned)) {
-                if (paperSize <= returned) {
-                    FORM_INFO_1 *formArray = (FORM_INFO_1 *) forms;
-                    int width = formArray[paperSize - 1].Size.cx; // 1/1000 of a mm
-                    int height = formArray[paperSize - 1].Size.cy; // 1/1000 of a mm
-                    paper_size = QSizeF((width * 72 /25.4) / 1000.0, (height * 72 / 25.4) / 1000.0);
-                } else {
-                    has_custom_paper_size = false;
-                }
-            }
-            free(forms);
-        }
-    } else {
-        has_custom_paper_size = false;
-    }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
diff --git a/src/gui/painting/qprintengine_win_p.h b/src/gui/painting/qprintengine_win_p.h
deleted file mode 100644 (file)
index 3e183a4..0000000
+++ /dev/null
@@ -1,261 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPRINTENGINE_WIN_P_H
-#define QPRINTENGINE_WIN_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.
-//
-
-#ifndef QT_NO_PRINTER
-
-#include "QtGui/qprinter.h"
-#include "QtGui/qprintengine.h"
-#include "QtGui/qpaintengine.h"
-#include "QtCore/qt_windows.h"
-#include "qpaintengine_alpha_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QWin32PrintEnginePrivate;
-class QPrinterPrivate;
-class QPainterState;
-
-class QWin32PrintEngine : public QAlphaPaintEngine, public QPrintEngine
-{
-    Q_DECLARE_PRIVATE(QWin32PrintEngine)
-public:
-    QWin32PrintEngine(QPrinter::PrinterMode mode);
-
-    // override QWin32PaintEngine
-    bool begin(QPaintDevice *dev);
-    bool end();
-
-    void updateState(const QPaintEngineState &state);
-
-    void updateMatrix(const QTransform &matrix);
-    void updateClipPath(const QPainterPath &clip, Qt::ClipOperation op);
-
-    void drawPath(const QPainterPath &path);
-    void drawPolygon(const QPointF *points, int pointCount, PolygonDrawMode mode);
-    void drawTextItem(const QPointF &p, const QTextItem &textItem);
-
-    void drawPixmap(const QRectF &r, const QPixmap &pm, const QRectF &sr);
-    void drawTiledPixmap(const QRectF &r, const QPixmap &pm, const QPointF &p);
-    void setProperty(PrintEnginePropertyKey key, const QVariant &value);
-    QVariant property(PrintEnginePropertyKey key) const;
-
-    bool newPage();
-    bool abort();
-    int metric(QPaintDevice::PaintDeviceMetric) const;
-
-    QPrinter::PrinterState printerState() const;
-
-    QPaintEngine::Type type() const { return Windows; }
-
-    HDC getDC() const;
-    void releaseDC(HDC) const;
-
-    HDC getPrinterDC() const { return getDC(); }
-    void releasePrinterDC(HDC dc) const { releaseDC(dc); }
-
-private:
-    friend class QPrintDialog;
-    friend class QPageSetupDialog;
-};
-
-class QWin32PrintEnginePrivate : public QAlphaPaintEnginePrivate
-{
-    Q_DECLARE_PUBLIC(QWin32PrintEngine)
-public:
-    QWin32PrintEnginePrivate() :
-        hPrinter(0),
-        globalDevMode(0),
-        devMode(0),
-        pInfo(0),
-        hdc(0),
-        mode(QPrinter::ScreenResolution),
-        state(QPrinter::Idle),
-        resolution(0),
-        pageMarginsSet(false),
-        num_copies(1),
-        printToFile(false),
-        fullPage(false),
-        reinit(false),
-        has_custom_paper_size(false)
-    {
-    }
-
-    ~QWin32PrintEnginePrivate();
-
-
-    /* Reads the default printer name and its driver (printerProgram) into
-       the engines private data. */
-    void queryDefault();
-
-    /* Initializes the printer data based on the current printer name. This
-       function creates a DEVMODE struct, HDC and a printer handle. If these
-       structures are already in use, they are freed using release
-    */
-    void initialize();
-
-    /* Initializes data in the print engine whenever the HDC has been renewed
-    */
-    void initHDC();
-
-    /* Releases all the handles the printer currently holds, HDC, DEVMODE,
-       etc and resets the corresponding members to 0. */
-    void release();
-
-    /* Queries the resolutions for the current printer, and returns them
-       in a list. */
-    QList<QVariant> queryResolutions() const;
-
-    /* Resets the DC with changes in devmode. If the printer is active
-       this function only sets the reinit variable to true so it
-       is handled in the next begin or newpage. */
-    void doReinit();
-
-    /* Used by print/page setup dialogs */
-    HGLOBAL *createDevNames();
-
-    void readDevmode(HGLOBAL globalDevmode);
-    void readDevnames(HGLOBAL globalDevnames);
-
-    inline bool resetDC() {
-        hdc = ResetDC(hdc, devMode);
-        return hdc != 0;
-    }
-
-    void strokePath(const QPainterPath &path, const QColor &color);
-    void fillPath(const QPainterPath &path, const QColor &color);
-
-    void composeGdiPath(const QPainterPath &path);
-    void fillPath_dev(const QPainterPath &path, const QColor &color);
-    void strokePath_dev(const QPainterPath &path, const QColor &color, qreal width);
-
-    void updateOrigin();
-
-    void initDevRects();
-    void setPageMargins(int margin_left, int margin_top, int margin_right, int margin_bottom);
-    QRect getPageMargins() const;
-    void updateCustomPaperSize();
-
-    // Windows GDI printer references.
-    HANDLE hPrinter;
-
-    HGLOBAL globalDevMode;
-    DEVMODE *devMode;
-    PRINTER_INFO_2 *pInfo;
-    HGLOBAL hMem;
-
-    HDC hdc;
-
-    QPrinter::PrinterMode mode;
-
-    // Printer info
-    QString name;
-    QString program;
-    QString port;
-
-    // Document info
-    QString docName;
-    QString fileName;
-
-    QPrinter::PrinterState state;
-    int resolution;
-
-    // This QRect is used to store the exact values
-    // entered into the PageSetup Dialog because those are
-    // entered in mm but are since converted to device coordinates.
-    // If they were to be converted back when displaying the dialog
-    // again, there would be inaccuracies so when the user entered 10
-    // it may show up as 9.99 the next time the dialog is opened.
-    // We don't want that confusion.
-    QRect previousDialogMargins;
-
-    bool pageMarginsSet;
-    QRect devPageRect;
-    QRect devPhysicalPageRect;
-    QRect devPaperRect;
-    qreal stretch_x;
-    qreal stretch_y;
-    int origin_x;
-    int origin_y;
-
-    int dpi_x;
-    int dpi_y;
-    int dpi_display;
-    int num_copies;
-
-    uint printToFile : 1;
-    uint fullPage : 1;
-    uint reinit : 1;
-
-    uint complex_xform : 1;
-    uint has_pen : 1;
-    uint has_brush : 1;
-    uint has_custom_paper_size : 1;
-
-    uint txop;
-
-    QColor brush_color;
-    QPen pen;
-    QColor pen_color;
-    QSizeF paper_size;
-
-    QTransform painterMatrix;
-    QTransform matrix;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_PRINTER
-
-#endif // QPRINTENGINE_WIN_P_H
diff --git a/src/gui/painting/qprinterinfo_mac.cpp b/src/gui/painting/qprinterinfo_mac.cpp
deleted file mode 100644 (file)
index f4516a9..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qprinterinfo.h"
-#include "qprinterinfo_p.h"
-
-#include "qt_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_PRINTER
-
-extern QPrinter::PaperSize qSizeFTopaperSize(const QSizeF &size);
-
-QList<QPrinterInfo> QPrinterInfo::availablePrinters()
-{
-    QList<QPrinterInfo> printers;
-
-    QCFType<CFArrayRef> array;
-    if (PMServerCreatePrinterList(kPMServerLocal, &array) == noErr) {
-        CFIndex count = CFArrayGetCount(array);
-        for (int i = 0; i < count; ++i) {
-            PMPrinter printer = static_cast<PMPrinter>(const_cast<void *>(CFArrayGetValueAtIndex(array, i)));
-            QString printerName = QCFString::toQString(PMPrinterGetName(printer));
-
-            QPrinterInfo printerInfo(printerName);
-            if (PMPrinterIsDefault(printer))
-                printerInfo.d_ptr->isDefault = true;
-            printers.append(printerInfo);
-        }
-    }
-
-    return printers;
-}
-
-QPrinterInfo QPrinterInfo::defaultPrinter()
-{
-    QList<QPrinterInfo> printers = availablePrinters();
-    foreach (const QPrinterInfo &printerInfo, printers) {
-        if (printerInfo.isDefault())
-            return printerInfo;
-    }
-
-    return printers.value(0);
-}
-
-QList<QPrinter::PaperSize> QPrinterInfo::supportedPaperSizes() const
-{
-    const Q_D(QPrinterInfo);
-
-    QList<QPrinter::PaperSize> paperSizes;
-    if (isNull())
-        return paperSizes;
-
-    PMPrinter cfPrn = PMPrinterCreateFromPrinterID(QCFString::toCFStringRef(d->name));
-    if (!cfPrn)
-        return paperSizes;
-
-    CFArrayRef array;
-    if (PMPrinterGetPaperList(cfPrn, &array) != noErr) {
-        PMRelease(cfPrn);
-        return paperSizes;
-    }
-
-    int count = CFArrayGetCount(array);
-    for (int i = 0; i < count; ++i) {
-        PMPaper paper = static_cast<PMPaper>(const_cast<void *>(CFArrayGetValueAtIndex(array, i)));
-        double width, height;
-        if (PMPaperGetWidth(paper, &width) == noErr && PMPaperGetHeight(paper, &height) == noErr) {
-            QSizeF size(width * 0.3527, height * 0.3527);
-            paperSizes.append(qSizeFTopaperSize(size));
-        }
-    }
-
-    PMRelease(cfPrn);
-
-    return paperSizes;
-}
-
-#endif // QT_NO_PRINTER
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qprinterinfo_win.cpp b/src/gui/painting/qprinterinfo_win.cpp
deleted file mode 100644 (file)
index 6b0d4e8..0000000
+++ /dev/null
@@ -1,122 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qprinterinfo.h"
-#include "qprinterinfo_p.h"
-
-#include <qstringlist.h>
-
-#include <qt_windows.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef QT_NO_PRINTER
-
-extern QPrinter::PaperSize mapDevmodePaperSize(int s);
-
-QList<QPrinterInfo> QPrinterInfo::availablePrinters()
-{
-    QList<QPrinterInfo> printers;
-
-    DWORD needed = 0;
-    DWORD returned = 0;
-    if (!EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, NULL, 4, 0, 0, &needed, &returned)) {
-        LPBYTE buffer = new BYTE[needed];
-        if (EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, NULL, 4, buffer, needed, &needed, &returned)) {
-            PPRINTER_INFO_4 infoList = reinterpret_cast<PPRINTER_INFO_4>(buffer);
-            QPrinterInfo defPrn = defaultPrinter();
-            for (uint i = 0; i < returned; ++i) {
-                QString printerName(QString::fromWCharArray(infoList[i].pPrinterName));
-
-                QPrinterInfo printerInfo(printerName);
-                if (printerInfo.printerName() == defPrn.printerName())
-                    printerInfo.d_ptr->isDefault = true;
-                printers.append(printerInfo);
-            }
-        }
-        delete [] buffer;
-    }
-
-    return printers;
-}
-
-QPrinterInfo QPrinterInfo::defaultPrinter()
-{
-    QString noPrinters(QLatin1String("qt_no_printers"));
-    wchar_t buffer[256];
-    GetProfileString(L"windows", L"device", (wchar_t*)noPrinters.utf16(), buffer, 256);
-    QString output = QString::fromWCharArray(buffer);
-    if (output != noPrinters) {
-        // Filter out the name of the printer, which should be everything before a comma.
-        QString printerName = output.split(QLatin1Char(',')).value(0);
-        QPrinterInfo printerInfo(printerName);
-        printerInfo.d_ptr->isDefault = true;
-        return printerInfo;
-    }
-
-    return QPrinterInfo();
-}
-
-QList<QPrinter::PaperSize> QPrinterInfo::supportedPaperSizes() const
-{
-    const Q_D(QPrinterInfo);
-
-    QList<QPrinter::PaperSize> paperSizes;
-    if (isNull())
-        return paperSizes;
-
-    DWORD size = DeviceCapabilities(reinterpret_cast<const wchar_t*>(d->name.utf16()),
-                                    NULL, DC_PAPERS, NULL, NULL);
-    if ((int)size != -1) {
-        wchar_t *papers = new wchar_t[size];
-        size = DeviceCapabilities(reinterpret_cast<const wchar_t*>(d->name.utf16()),
-                                  NULL, DC_PAPERS, papers, NULL);
-        for (int c = 0; c < (int)size; ++c)
-            paperSizes.append(mapDevmodePaperSize(papers[c]));
-        delete [] papers;
-    }
-
-    return paperSizes;
-}
-
-#endif // QT_NO_PRINTER
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qregion_mac.cpp b/src/gui/painting/qregion_mac.cpp
deleted file mode 100644 (file)
index 7275a7d..0000000
+++ /dev/null
@@ -1,286 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qt_mac_p.h>
-#include "qcoreapplication.h"
-#include <qlibrary.h>
-
-QT_BEGIN_NAMESPACE
-
-QRegion::QRegionData QRegion::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0 };
-
-#if defined(Q_WS_MAC32) && !defined(QT_MAC_USE_COCOA)
-#define RGN_CACHE_SIZE 200
-#ifdef RGN_CACHE_SIZE
-static bool rgncache_init = false;
-static int rgncache_used;
-static RgnHandle rgncache[RGN_CACHE_SIZE];
-static void qt_mac_cleanup_rgncache()
-{
-    rgncache_init = false;
-    for(int i = 0; i < RGN_CACHE_SIZE; ++i) {
-        if(rgncache[i]) {
-            --rgncache_used;
-            DisposeRgn(rgncache[i]);
-            rgncache[i] = 0;
-        }
-    }
-}
-#endif
-
-Q_GUI_EXPORT RgnHandle qt_mac_get_rgn()
-{
-#ifdef RGN_CACHE_SIZE
-    if(!rgncache_init) {
-        rgncache_used = 0;
-        rgncache_init = true;
-        for(int i = 0; i < RGN_CACHE_SIZE; ++i)
-            rgncache[i] = 0;
-        qAddPostRoutine(qt_mac_cleanup_rgncache);
-    } else if(rgncache_used) {
-        for(int i = 0; i < RGN_CACHE_SIZE; ++i) {
-            if(rgncache[i]) {
-                RgnHandle ret = rgncache[i];
-                SetEmptyRgn(ret);
-                rgncache[i] = 0;
-                --rgncache_used;
-                return ret;
-            }
-        }
-    }
-#endif
-    return NewRgn();
-}
-
-Q_GUI_EXPORT void qt_mac_dispose_rgn(RgnHandle r)
-{
-#ifdef RGN_CACHE_SIZE
-    if(rgncache_init && rgncache_used < RGN_CACHE_SIZE) {
-        for(int i = 0; i < RGN_CACHE_SIZE; ++i) {
-            if(!rgncache[i]) {
-                ++rgncache_used;
-                rgncache[i] = r;
-                return;
-            }
-        }
-    }
-#endif
-    DisposeRgn(r);
-}
-
-static OSStatus qt_mac_get_rgn_rect(UInt16 msg, RgnHandle, const Rect *rect, void *reg)
-{
-    if(msg == kQDRegionToRectsMsgParse) {
-        QRect rct(rect->left, rect->top, (rect->right - rect->left), (rect->bottom - rect->top));
-        if(!rct.isEmpty())
-            *((QRegion *)reg) += rct;
-    }
-    return noErr;
-}
-
-Q_GUI_EXPORT QRegion qt_mac_convert_mac_region(RgnHandle rgn)
-{
-    return QRegion::fromQDRgn(rgn);
-}
-
-QRegion QRegion::fromQDRgn(RgnHandle rgn)
-{
-    QRegion ret;
-    ret.detach();
-    OSStatus oss = QDRegionToRects(rgn, kQDParseRegionFromTopLeft, qt_mac_get_rgn_rect, (void *)&ret);
-    if(oss != noErr)
-        return QRegion();
-    return ret;
-}
-
-/*!
-    \internal
-     Create's a RegionHandle, it's the caller's responsibility to release.
-*/
-RgnHandle QRegion::toQDRgn() const
-{
-    RgnHandle rgnHandle = qt_mac_get_rgn();
-    if(d->qt_rgn && d->qt_rgn->numRects) {
-        RgnHandle tmp_rgn = qt_mac_get_rgn();
-        int n = d->qt_rgn->numRects;
-        const QRect *qt_r = (n == 1) ? &d->qt_rgn->extents : d->qt_rgn->rects.constData();
-        while (n--) {
-            SetRectRgn(tmp_rgn,
-                       qMax(SHRT_MIN, qt_r->x()),
-                       qMax(SHRT_MIN, qt_r->y()),
-                       qMin(SHRT_MAX, qt_r->right() + 1),
-                       qMin(SHRT_MAX, qt_r->bottom() + 1));
-            UnionRgn(rgnHandle, tmp_rgn, rgnHandle);
-            ++qt_r;
-        }
-        qt_mac_dispose_rgn(tmp_rgn);
-    }
-    return rgnHandle;
-}
-
-/*!
-    \internal
-     Create's a RegionHandle, it's the caller's responsibility to release.
-     Returns 0 if the QRegion overflows.
-*/
-RgnHandle QRegion::toQDRgnForUpdate_sys() const
-{
-    RgnHandle rgnHandle = qt_mac_get_rgn();
-    if(d->qt_rgn && d->qt_rgn->numRects) {
-        RgnHandle tmp_rgn = qt_mac_get_rgn();
-        int n = d->qt_rgn->numRects;
-        const QRect *qt_r = (n == 1) ? &d->qt_rgn->extents : d->qt_rgn->rects.constData();
-        while (n--) {
-
-            // detect overflow. Tested for use with HIViewSetNeedsDisplayInRegion
-            // in QWidgetPrivate::update_sys().
-            enum { HIViewSetNeedsDisplayInRegionOverflow = 10000 }; // empirically determined conservative value
-            if (qt_r->right() > HIViewSetNeedsDisplayInRegionOverflow || qt_r->bottom() > HIViewSetNeedsDisplayInRegionOverflow) {
-                qt_mac_dispose_rgn(tmp_rgn);
-                qt_mac_dispose_rgn(rgnHandle);
-                return 0;
-            }
-
-            SetRectRgn(tmp_rgn,
-                       qMax(SHRT_MIN, qt_r->x()),
-                       qMax(SHRT_MIN, qt_r->y()),
-                       qMin(SHRT_MAX, qt_r->right() + 1),
-                       qMin(SHRT_MAX, qt_r->bottom() + 1));
-            UnionRgn(rgnHandle, tmp_rgn, rgnHandle);
-            ++qt_r;
-        }
-        qt_mac_dispose_rgn(tmp_rgn);
-    }
-    return rgnHandle;
-}
-
-#endif
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-OSStatus QRegion::shape2QRegionHelper(int inMessage, HIShapeRef,
-                                      const CGRect *inRect, void *inRefcon)
-{
-    QRegion *region = static_cast<QRegion *>(inRefcon);
-    if (!region)
-        return paramErr;
-
-    switch (inMessage) {
-    case kHIShapeEnumerateRect:
-        *region += QRect(inRect->origin.x, inRect->origin.y,
-                         inRect->size.width, inRect->size.height);
-        break;
-    case kHIShapeEnumerateInit:
-        // Assume the region is already setup correctly
-    case kHIShapeEnumerateTerminate:
-    default:
-        break;
-    }
-    return noErr;
-}
-#endif
-
-/*!
-    \internal
-     Create's a mutable shape, it's the caller's responsibility to release.
-     WARNING: this function clamps the coordinates to SHRT_MIN/MAX on 10.4 and below.
-*/
-HIMutableShapeRef QRegion::toHIMutableShape() const
-{
-    HIMutableShapeRef shape = HIShapeCreateMutable();
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-        if (d->qt_rgn && d->qt_rgn->numRects) {
-            int n = d->qt_rgn->numRects;
-            const QRect *qt_r = (n == 1) ? &d->qt_rgn->extents : d->qt_rgn->rects.constData();
-            while (n--) {
-                CGRect cgRect = CGRectMake(qt_r->x(), qt_r->y(), qt_r->width(), qt_r->height());
-                HIShapeUnionWithRect(shape, &cgRect);
-                ++qt_r;
-            }
-        }
-    } else
-#endif
-    {
-#ifndef QT_MAC_USE_COCOA
-        QCFType<HIShapeRef> qdShape = HIShapeCreateWithQDRgn(QMacSmartQuickDrawRegion(toQDRgn()));
-        HIShapeUnion(qdShape, shape, shape);
-#endif
-    }
-    return shape;
-}
-
-#if !defined(Q_WS_MAC64) && !defined(QT_MAC_USE_COCOA)
-typedef OSStatus (*PtrHIShapeGetAsQDRgn)(HIShapeRef, RgnHandle);
-static PtrHIShapeGetAsQDRgn ptrHIShapeGetAsQDRgn = 0;
-#endif
-
-
-QRegion QRegion::fromHIShapeRef(HIShapeRef shape)
-{
-    QRegion returnRegion;
-    returnRegion.detach();
-    // Begin gratuitous #if-defery
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-# ifndef Q_WS_MAC64
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-# endif
-        HIShapeEnumerate(shape, kHIShapeParseFromTopLeft, shape2QRegionHelper, &returnRegion);
-# ifndef Q_WS_MAC64
-    } else
-# endif
-#endif
-    {
-#if !defined(Q_WS_MAC64) && !defined(QT_MAC_USE_COCOA)
-        if (ptrHIShapeGetAsQDRgn == 0) {
-            QLibrary library(QLatin1String("/System/Library/Frameworks/Carbon.framework/Carbon"));
-            library.setLoadHints(QLibrary::ExportExternalSymbolsHint);
-                    ptrHIShapeGetAsQDRgn = reinterpret_cast<PtrHIShapeGetAsQDRgn>(library.resolve("HIShapeGetAsQDRgn"));
-        }
-        RgnHandle rgn = qt_mac_get_rgn();
-        ptrHIShapeGetAsQDRgn(shape, rgn);
-        returnRegion = QRegion::fromQDRgn(rgn);
-        qt_mac_dispose_rgn(rgn);
-#endif
-    }
-    return returnRegion;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qregion_win.cpp b/src/gui/painting/qregion_win.cpp
deleted file mode 100644 (file)
index c3e9b6e..0000000
+++ /dev/null
@@ -1,149 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qatomic.h"
-#include "qbitmap.h"
-#include "qbuffer.h"
-#include "qimage.h"
-#include "qpolygon.h"
-#include "qregion.h"
-#include "qt_windows.h"
-#include "qpainterpath.h"
-
-QT_BEGIN_NAMESPACE
-
-QRegion::QRegionData QRegion::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0 };
-
-HRGN qt_tryCreateRegion(QRegion::RegionType type, int left, int top, int right, int bottom)
-{
-    const int tries = 10;
-    for (int i = 0; i < tries; ++i) {
-        HRGN region = 0;
-        switch (type) {
-        case QRegion::Rectangle:
-            region = CreateRectRgn(left, top, right, bottom);
-            break;
-        case QRegion::Ellipse:
-#ifndef Q_OS_WINCE
-            region = CreateEllipticRgn(left, top, right, bottom);
-#endif
-            break;
-        }
-        if (region) {
-            if (GetRegionData(region, 0, 0))
-                return region;
-            else
-                DeleteObject(region);
-        }
-    }
-    return 0;
-}
-
-QRegion qt_region_from_HRGN(HRGN rgn)
-{
-    int numBytes = GetRegionData(rgn, 0, 0);
-    if (numBytes == 0)
-        return QRegion();
-
-    char *buf = new char[numBytes];
-    if (buf == 0)
-        return QRegion();
-
-    RGNDATA *rd = reinterpret_cast<RGNDATA*>(buf);
-    if (GetRegionData(rgn, numBytes, rd) == 0) {
-        delete [] buf;
-        return QRegion();
-    }
-
-    QRegion region;
-    RECT *r = reinterpret_cast<RECT*>(rd->Buffer);
-    for (uint i = 0; i < rd->rdh.nCount; ++i) {
-        QRect rect;
-        rect.setCoords(r->left, r->top, r->right - 1, r->bottom - 1);
-        ++r;
-        region |= rect;
-    }
-
-    delete [] buf;
-
-    return region;
-}
-
-void qt_win_dispose_rgn(HRGN r)
-{
-    if (r)
-        DeleteObject(r);
-}
-
-static void qt_add_rect(HRGN &winRegion, QRect r)
-{
-    HRGN rgn = CreateRectRgn(r.left(), r.top(), r.x() + r.width(), r.y() + r.height());
-    if (rgn) {
-        HRGN dest = CreateRectRgn(0,0,0,0);
-        int result = CombineRgn(dest, winRegion, rgn, RGN_OR);
-        if (result) {
-            DeleteObject(winRegion);
-            winRegion = dest;
-        }
-        DeleteObject(rgn);
-    }
-}
-
-void QRegion::ensureHandle() const
-{
-    if (d->rgn)
-        DeleteObject(d->rgn);
-    d->rgn = CreateRectRgn(0,0,0,0);
-    if (d->qt_rgn) {
-        if (d->qt_rgn->numRects == 1) {
-            QRect r = d->qt_rgn->extents;
-            qt_add_rect(d->rgn, r);
-            return;
-        }
-        for (int i = 0;i < d->qt_rgn->numRects;i++) {
-            QRect r = d->qt_rgn->rects.at(i);
-            qt_add_rect(d->rgn, r);
-        }
-    }
-}
-
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qunifiedtoolbarsurface_mac.cpp b/src/gui/painting/qunifiedtoolbarsurface_mac.cpp
deleted file mode 100644 (file)
index 3e7d0b2..0000000
+++ /dev/null
@@ -1,263 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qunifiedtoolbarsurface_mac_p.h"
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qbackingstore_p.h>
-#include <qmainwindowlayout_p.h>
-
-#include <QDebug>
-
-#ifdef QT_MAC_USE_COCOA
-
-QT_BEGIN_NAMESPACE
-
-QUnifiedToolbarSurface::QUnifiedToolbarSurface(QWidget *widget)
-    : QRasterWindowSurface(widget, false), d_ptr(new QUnifiedToolbarSurfacePrivate)
-{
-    d_ptr->image = 0;
-    d_ptr->inSetGeometry = false;
-
-    setGeometry(QRect(QPoint(0, 0), QSize(widget->width(), 100))); // FIXME: Fix height.
-}
-
-QUnifiedToolbarSurface::~QUnifiedToolbarSurface()
-{
-    if (d_ptr->image)
-        delete d_ptr->image;
-}
-
-QPaintDevice *QUnifiedToolbarSurface::paintDevice()
-{
-    return &d_ptr->image->image;
-}
-
-void QUnifiedToolbarSurface::recursiveRedirect(QObject *object, QWidget *parent_toolbar, const QPoint &offset)
-{
-    if (object != 0) {
-        if (object->isWidgetType()) {
-            QWidget *widget = qobject_cast<QWidget *>(object);
-
-            // We redirect the painting only if the widget is in the same window
-            // and is not a window in itself.
-            if (!(widget->windowType() & Qt::Window)) {
-                widget->d_func()->unifiedSurface = this;
-                widget->d_func()->isInUnifiedToolbar = true;
-                widget->d_func()->toolbar_offset = offset;
-                widget->d_func()->toolbar_ancestor = parent_toolbar;
-
-                for (int i = 0; i < object->children().size(); ++i) {
-                    recursiveRedirect(object->children().at(i), parent_toolbar, offset);
-                }
-            }
-        }
-    }
-}
-
-void QUnifiedToolbarSurface::insertToolbar(QWidget *toolbar, const QPoint &offset)
-{
-    setGeometry(QRect(QPoint(0, 0), QSize(offset.x() + toolbar->width(), 100))); // FIXME
-    recursiveRedirect(toolbar, toolbar, offset);
-}
-
-// We basically undo what we set in recursiveRedirect().
-void QUnifiedToolbarSurface::recursiveRemoval(QObject *object)
-{
-    if (object != 0) {
-        if (object->isWidgetType()) {
-            QWidget *widget = qobject_cast<QWidget *>(object);
-
-            // If it's a pop-up or something similar, we don't redirect it.
-            if (widget->windowType() & Qt::Window)
-                return;
-
-            widget->d_func()->unifiedSurface = 0;
-            widget->d_func()->isInUnifiedToolbar = false;
-            widget->d_func()->toolbar_offset = QPoint();
-            widget->d_func()->toolbar_ancestor = 0;
-        }
-
-        for (int i = 0; i < object->children().size(); ++i) {
-            recursiveRemoval(object->children().at(i));
-        }
-    }
-}
-
-void QUnifiedToolbarSurface::removeToolbar(QToolBar *toolbar)
-{
-    recursiveRemoval(toolbar);
-}
-
-void QUnifiedToolbarSurface::setGeometry(const QRect &rect)
-{
-    QWindowSurface::setGeometry(rect);
-    Q_D(QUnifiedToolbarSurface);
-    d->inSetGeometry = true;
-    if (d->image == 0 || d->image->width() < rect.width() || d->image->height() < rect.height())
-            prepareBuffer(QImage::Format_ARGB32_Premultiplied, window());
-    d->inSetGeometry = false;
-
-    // FIXME: set unified toolbar height.
-}
-
-void QUnifiedToolbarSurface::beginPaint(const QRegion &rgn)
-{
-    QPainter p(&d_ptr->image->image);
-    p.setCompositionMode(QPainter::CompositionMode_Source);
-    const QVector<QRect> rects = rgn.rects();
-    const QColor blank = Qt::transparent;
-    for (QVector<QRect>::const_iterator it = rects.begin(); it != rects.end(); ++it) {
-        p.fillRect(*it, blank);
-    }
-}
-
-void QUnifiedToolbarSurface::updateToolbarOffset(QWidget *widget)
-{
-    QMainWindowLayout *mlayout = qobject_cast<QMainWindowLayout*> (widget->window()->layout());
-    if (mlayout)
-        mlayout->updateUnifiedToolbarOffset();
-}
-
-void QUnifiedToolbarSurface::flush(QWidget *widget, const QRegion &region, const QPoint &offset)
-{
-    Q_UNUSED(region);
-    Q_UNUSED(offset);
-
-    this->flush(widget);
-}
-
-void QUnifiedToolbarSurface::flush(QWidget *widget)
-{
-    Q_D(QUnifiedToolbarSurface);
-
-    if (!d->image)
-        return;
-
-    if (widget->d_func()->flushRequested)
-        qt_mac_setNeedsDisplay(widget);
-}
-
-void QUnifiedToolbarSurface::prepareBuffer(QImage::Format format, QWidget *widget)
-{
-    Q_D(QUnifiedToolbarSurface);
-
-    int width = geometry().width();
-    int height = 100; // FIXME
-    if (d->image) {
-        width = qMax(d->image->width(), width);
-        height = qMax(d->image->height(), height);
-    }
-
-    if (width == 0 || height == 0) {
-        delete d->image;
-        d->image = 0;
-        return;
-    }
-
-    QImage *oldImage = d->image;
-
-    d->image = new QImage(width, height, format, false, widget);
-
-    if (oldImage && d->inSetGeometry && hasStaticContents()) {
-        // Make sure we use the const version of bits() (no detach).
-        const uchar *src = const_cast<const QImage &>(oldImage->image).bits();
-        uchar *dst = d->image->image.bits();
-
-        const int srcBytesPerLine = oldImage->image.bytesPerLine();
-        const int dstBytesPerLine = d->image->image.bytesPerLine();
-        const int bytesPerPixel = oldImage->image.depth() >> 3;
-
-        QRegion staticRegion(staticContents());
-        // Make sure we're inside the boundaries of the old image.
-        staticRegion &= QRect(0, 0, oldImage->image.width(), oldImage->image.height());
-        const QVector<QRect> &rects = staticRegion.rects();
-        const QRect *srcRect = rects.constData();
-
-        // Copy the static content of the old image into the new one.
-        int numRectsLeft = rects.size();
-        do {
-            const int bytesOffset = srcRect->x() * bytesPerPixel;
-            const int dy = srcRect->y();
-
-            // Adjust src and dst to point to the right offset.
-            const uchar *s = src + dy * srcBytesPerLine + bytesOffset;
-            uchar *d = dst + dy * dstBytesPerLine + bytesOffset;
-            const int numBytes = srcRect->width() * bytesPerPixel;
-
-            int numScanLinesLeft = srcRect->height();
-            do {
-                ::memcpy(d, s, numBytes);
-                d += dstBytesPerLine;
-                s += srcBytesPerLine;
-            } while (--numScanLinesLeft);
-
-            ++srcRect;
-        } while (--numRectsLeft);
-    }
-
-    delete oldImage;
-}
-
-CGContextRef QUnifiedToolbarSurface::imageContext()
-{
-    Q_D(QUnifiedToolbarSurface);
-    return d->image->cg;
-}
-
-void QUnifiedToolbarSurface::renderToolbar(QWidget *widget, bool forceFlush)
-{
-    QWidget *toolbar = widget->d_func()->toolbar_ancestor;
-
-    updateToolbarOffset(toolbar);
-    QRect beginPaintRect(toolbar->d_func()->toolbar_offset.x(), toolbar->d_func()->toolbar_offset.y(), toolbar->geometry().width(), toolbar->geometry().height());
-    QRegion beginPaintRegion(beginPaintRect);
-
-    beginPaint(beginPaintRegion);
-    toolbar->render(paintDevice(), toolbar->d_func()->toolbar_offset, QRegion(toolbar->geometry()), QWidget::DrawChildren);
-    toolbar->d_func()->flushRequested = true;
-
-    if (forceFlush)
-        flush(toolbar);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_MAC_USE_COCOA
diff --git a/src/gui/painting/qunifiedtoolbarsurface_mac_p.h b/src/gui/painting/qunifiedtoolbarsurface_mac_p.h
deleted file mode 100644 (file)
index 9cf01ec..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QUNIFIEDTOOLBARSURFACE_MAC_P_H
-#define QUNIFIEDTOOLBARSURFACE_MAC_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 <qwindowsurface_raster_p.h>
-#include <QWidget>
-#include <QToolBar>
-#include <qwidget_p.h>
-#include <qimage.h>
-
-#ifdef QT_MAC_USE_COCOA
-
-QT_BEGIN_NAMESPACE
-
-//
-// This is the implementation of the unified toolbar on Mac OS X
-// with the graphics system raster.
-//
-// General idea:
-// -------------
-// We redirect the painting of widgets inside the unified toolbar
-// to a special window surface, the QUnifiedToolbarSurface.
-// We need a separate window surface because the unified toolbar
-// is out of the content view.
-// The input system is the same as for the unified toolbar with the
-// native (CoreGraphics) engine.
-//
-// Execution flow:
-// ---------------
-// The unified toolbar is triggered by QMainWindow::setUnifiedTitleAndToolBarOnMac().
-// It calls QMainWindowLayout::insertIntoMacToolbar() which will
-// set all the appropriate variables (offsets, redirection, ...).
-// When Qt tells a widget to repaint, QWidgetPrivate::drawWidget()
-// checks if the widget is inside the unified toolbar and exits without
-// painting is that is the case.
-// We trigger the rendering of the unified toolbar in QWidget::repaint()
-// and QWidget::update().
-// We keep track of flush requests via "flushRequested" variable. That
-// allow flush() to be a no-op if no repaint occurred for a widget.
-// We rely on the needsDisplay: and drawRect: mecanism for drawing our
-// content into the graphics context.
-//
-// Notes:
-// ------
-// The painting of items inside the unified toolbar is expensive.
-// Too many repaints will drastically slow down the whole application.
-//
-
-class QUnifiedToolbarSurfacePrivate
-{
-public:
-    QImage *image;
-    uint inSetGeometry : 1;
-};
-
-class Q_GUI_EXPORT QUnifiedToolbarSurface : public QRasterWindowSurface
-{
-public:
-    QUnifiedToolbarSurface(QWidget *widget);
-    ~QUnifiedToolbarSurface();
-
-    void flush(QWidget *widget);
-    void flush(QWidget *widget, const QRegion &region, const QPoint &offset);
-    void setGeometry(const QRect &rect);
-    void beginPaint(const QRegion &rgn);
-    void insertToolbar(QWidget *toolbar, const QPoint &offset);
-    void removeToolbar(QToolBar *toolbar);
-    void updateToolbarOffset(QWidget *widget);
-    void renderToolbar(QWidget *widget, bool forceFlush = false);
-    void recursiveRedirect(QObject *widget, QWidget *parent_toolbar, const QPoint &offset);
-
-    QPaintDevice *paintDevice();
-    CGContextRef imageContext();
-
-private:
-    void prepareBuffer(QImage::Format format, QWidget *widget);
-    void recursiveRemoval(QObject *object);
-
-    Q_DECLARE_PRIVATE(QUnifiedToolbarSurface)
-    QScopedPointer<QUnifiedToolbarSurfacePrivate> d_ptr;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_MAC_USE_COCOA
-
-#endif // QUNIFIEDTOOLBARSURFACE_MAC_P_H
diff --git a/src/gui/painting/qwindowsurface_mac.cpp b/src/gui/painting/qwindowsurface_mac.cpp
deleted file mode 100644 (file)
index e625713..0000000
+++ /dev/null
@@ -1,139 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qwindowsurface_mac_p.h"
-
-#include <qt_mac_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <QtGui/qwidget.h>
-
-QT_BEGIN_NAMESPACE
-
-struct QMacWindowSurfacePrivate
-{
-    QWidget *widget;
-    QPixmap device;
-};
-
-QMacWindowSurface::QMacWindowSurface(QWidget *widget)
-    : QWindowSurface(widget), d_ptr(new QMacWindowSurfacePrivate)
-{
-    d_ptr->widget = widget;
-}
-
-QMacWindowSurface::~QMacWindowSurface()
-{
-    delete d_ptr;
-}
-
-QPaintDevice *QMacWindowSurface::paintDevice()
-{
-    return &d_ptr->device;
-}
-
-void QMacWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint &offset)
-{
-    Q_UNUSED(offset);
-
-    // Get a context for the widget.
-#ifndef QT_MAC_USE_COCOA
-    CGContextRef context;
-    CGrafPtr port = GetWindowPort(qt_mac_window_for(widget));
-    QDBeginCGContext(port, &context);
-#else
-    extern CGContextRef qt_mac_graphicsContextFor(QWidget *);
-    CGContextRef context = qt_mac_graphicsContextFor(widget);
-#endif
-    CGContextRetain(context);
-    CGContextSaveGState(context);
-
-    // Flip context.
-    CGContextTranslateCTM(context, 0, widget->height());
-    CGContextScaleCTM(context, 1, -1);
-
-    // Clip to region.
-    const QVector<QRect> &rects = rgn.rects();
-    for (int i = 0; i < rects.size(); ++i) {
-        const QRect &rect = rects.at(i);
-        CGContextAddRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height()));
-    }
-    CGContextClip(context);
-
-    // Draw the image onto the window.
-    const CGRect dest = CGRectMake(0, 0, widget->width(), widget->height());
-    const CGImageRef image = d_ptr->device.toMacCGImageRef();
-    qt_mac_drawCGImage(context, &dest, image);
-    CFRelease(image);
-
-    // Restore context.
-    CGContextRestoreGState(context);
-#ifndef QT_MAC_USE_COCOA
-    QDEndCGContext(port, &context);
-#else
-    CGContextFlush(context);
-#endif
-    CGContextRelease(context);
-}
-
-void QMacWindowSurface::setGeometry(const QRect &rect)
-{
-    QWindowSurface::setGeometry(rect);
-    const QSize size = rect.size();
-    if (d_ptr->device.size() != size)
-        d_ptr->device = QPixmap(size);
-}
-
-bool QMacWindowSurface::scroll(const QRegion &area, int dx, int dy)
-{
-    if (d_ptr->device.size().isNull())
-        return false;
-
-    QCFType<CGImageRef> image = d_ptr->device.toMacCGImageRef();
-    const QRect rect(area.boundingRect());
-    const CGRect dest = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
-    QCFType<CGImageRef> subimage = CGImageCreateWithImageInRect(image, dest);
-    QCFType<CGContextRef> context = qt_mac_cg_context(&d_ptr->device);
-    CGContextTranslateCTM(context, dx, dy);
-    qt_mac_drawCGImage(context, &dest, subimage);
-    return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/painting/qwindowsurface_mac_p.h b/src/gui/painting/qwindowsurface_mac_p.h
deleted file mode 100644 (file)
index 8d0daf3..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QWINDOWSURFACE_MAC_P_H
-#define QWINDOWSURFACE_MAC_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 <qglobal.h>
-#include "qwindowsurface_p.h"
-
-QT_BEGIN_NAMESPACE
-
-class QPaintDevice;
-class QPoint;
-class QRegion;
-class QWidget;
-struct QMacWindowSurfacePrivate;
-
-class QMacWindowSurface : public QWindowSurface
-{
-public:
-    QMacWindowSurface(QWidget *widget);
-    ~QMacWindowSurface();
-
-    QPaintDevice *paintDevice();
-    void flush(QWidget *widget, const QRegion &region, const QPoint &offset);
-    void setGeometry(const QRect &rect);
-    bool scroll(const QRegion &area, int dx, int dy);
-
-private:
-    QMacWindowSurfacePrivate *d_ptr;
-};
-
-QT_END_NAMESPACE
-
-#endif // QWINDOWSURFACE_MAC_P_H
diff --git a/src/gui/styles/qmacstyle_mac.h b/src/gui/styles/qmacstyle_mac.h
deleted file mode 100644 (file)
index 36bbee8..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QMACSTYLE_MAC_H
-#define QMACSTYLE_MAC_H
-
-#include <QtGui/qwindowsstyle.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
-
-class QPalette;
-class QPushButton;
-class QStyleOptionButton;
-class QMacStylePrivate;
-class Q_GUI_EXPORT QMacStyle : public QWindowsStyle
-{
-    Q_OBJECT
-public:
-    QMacStyle();
-    virtual ~QMacStyle();
-
-    void polish(QWidget *w);
-    void unpolish(QWidget *w);
-
-    void polish(QApplication*);
-    void unpolish(QApplication*);
-
-    void polish(QPalette &pal);
-
-    void drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
-                       const QWidget *w = 0) const;
-    void drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
-                     const QWidget *w = 0) const;
-    QRect subElementRect(SubElement r, const QStyleOption *opt, const QWidget *widget = 0) const;
-    void drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
-                            const QWidget *w = 0) const;
-    SubControl hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
-                               const QPoint &pt, const QWidget *w = 0) const;
-    QRect subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
-                         const QWidget *w = 0) const;
-    QSize sizeFromContents(ContentsType ct, const QStyleOption *opt,
-                           const QSize &contentsSize, const QWidget *w = 0) const;
-
-    int pixelMetric(PixelMetric pm, const QStyleOption *opt = 0, const QWidget *widget = 0) const;
-
-    QPalette standardPalette() const;
-
-    virtual int styleHint(StyleHint sh, const QStyleOption *opt = 0, const QWidget *w = 0,
-                          QStyleHintReturn *shret = 0) const;
-
-    enum FocusRectPolicy { FocusEnabled, FocusDisabled, FocusDefault };
-    static void setFocusRectPolicy(QWidget *w, FocusRectPolicy policy);
-    static FocusRectPolicy focusRectPolicy(const QWidget *w);
-
-    enum WidgetSizePolicy { SizeSmall, SizeLarge, SizeMini, SizeDefault
-    };
-    static void setWidgetSizePolicy(const QWidget *w, WidgetSizePolicy policy);
-    static WidgetSizePolicy widgetSizePolicy(const QWidget *w);
-
-    QPixmap standardPixmap(StandardPixmap sp, const QStyleOption *opt,
-                           const QWidget *widget = 0) const;
-
-    QPixmap generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
-                                const QStyleOption *opt) const;
-
-    virtual void drawItemText(QPainter *p, const QRect &r, int flags, const QPalette &pal,
-                              bool enabled, const QString &text, QPalette::ColorRole textRole  = QPalette::NoRole) const;
-
-    bool event(QEvent *e);
-
-protected Q_SLOTS:
-    QIcon standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt = 0,
-                                     const QWidget *widget = 0) const;
-    int layoutSpacingImplementation(QSizePolicy::ControlType control1,
-                                    QSizePolicy::ControlType control2, 
-                                    Qt::Orientation orientation,
-                                    const QStyleOption *option = 0, 
-                                    const QWidget *widget = 0) const;
-
-private:
-    Q_DISABLE_COPY(QMacStyle)
-
-    QMacStylePrivate *d;
-
-    friend bool qt_mac_buttonIsRenderedFlat(const QPushButton *pushButton, const QStyleOptionButton *option);
-};
-
-#endif // Q_WS_MAC
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMACSTYLE_H
diff --git a/src/gui/styles/qmacstyle_mac.mm b/src/gui/styles/qmacstyle_mac.mm
deleted file mode 100644 (file)
index 6d2238a..0000000
+++ /dev/null
@@ -1,6068 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*
-  Note: The qdoc comments for QMacStyle are contained in
-  .../doc/src/qstyles.qdoc. 
-*/
-
-#include "qmacstyle_mac.h"
-
-#if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC)
-#define QMAC_QAQUASTYLE_SIZE_CONSTRAIN
-//#define DEBUG_SIZE_CONSTRAINT
-
-#include <qapplication_p.h>
-#include <qcombobox_p.h>
-#include <qmacstylepixmaps_mac_p.h>
-#include <qpaintengine_mac_p.h>
-#include <qpainter_p.h>
-#include <qprintengine_mac_p.h>
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qcheckbox.h>
-#include <qcombobox.h>
-#include <qdialogbuttonbox.h>
-#include <qdockwidget.h>
-#include <qevent.h>
-#include <qfocusframe.h>
-#include <qformlayout.h>
-#include <qgroupbox.h>
-#include <qhash.h>
-#include <qheaderview.h>
-#include <qlayout.h>
-#include <qlineedit.h>
-#include <qlistview.h>
-#include <qmainwindow.h>
-#include <qmap.h>
-#include <qmenubar.h>
-#include <qpaintdevice.h>
-#include <qpainter.h>
-#include <qpixmapcache.h>
-#include <qpointer.h>
-#include <qprogressbar.h>
-#include <qpushbutton.h>
-#include <qradiobutton.h>
-#include <qrubberband.h>
-#include <qsizegrip.h>
-#include <qspinbox.h>
-#include <qsplitter.h>
-#include <qstyleoption.h>
-#include <qtextedit.h>
-#include <qtextstream.h>
-#include <qtoolbar.h>
-#include <qtoolbutton.h>
-#include <qtreeview.h>
-#include <qtableview.h>
-#include <qwizard.h>
-#include <qdebug.h>
-#include <qlibrary.h>
-#include <qdatetimeedit.h>
-#include <qmath.h>
-#include <QtGui/qgraphicsproxywidget.h>
-#include <QtGui/qgraphicsview.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include "qmacstyle_mac_p.h"
-#include <qstylehelper_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// The following constants are used for adjusting the size
-// of push buttons so that they are drawn inside their bounds.
-const int QMacStylePrivate::PushButtonLeftOffset = 6;
-const int QMacStylePrivate::PushButtonTopOffset = 4;
-const int QMacStylePrivate::PushButtonRightOffset = 12;
-const int QMacStylePrivate::PushButtonBottomOffset = 12;
-const int QMacStylePrivate::MiniButtonH = 26;
-const int QMacStylePrivate::SmallButtonH = 30;
-const int QMacStylePrivate::BevelButtonW = 50;
-const int QMacStylePrivate::BevelButtonH = 22;
-const int QMacStylePrivate::PushButtonContentPadding = 6;
-
-// These colors specify the titlebar gradient colors on
-// Leopard. Ideally we should get them from the system.
-static const QColor titlebarGradientActiveBegin(220, 220, 220);
-static const QColor titlebarGradientActiveEnd(151, 151, 151);
-static const QColor titlebarSeparatorLineActive(111, 111, 111);
-static const QColor titlebarGradientInactiveBegin(241, 241, 241);
-static const QColor titlebarGradientInactiveEnd(207, 207, 207);
-static const QColor titlebarSeparatorLineInactive(131, 131, 131);
-
-// Gradient colors used for the dock widget title bar and
-// non-unifed tool bar bacground.
-static const QColor mainWindowGradientBegin(240, 240, 240);
-static const QColor mainWindowGradientEnd(200, 200, 200);
-
-static const int DisclosureOffset = 4;
-
-// Resolve these at run-time, since the functions was moved in Leopard.
-typedef HIRect * (*PtrHIShapeGetBounds)(HIShapeRef, HIRect *);
-static PtrHIShapeGetBounds ptrHIShapeGetBounds = 0;
-
-static int closeButtonSize = 12;
-
-extern QRegion qt_mac_convert_mac_region(RgnHandle); //qregion_mac.cpp
-
-static bool isVerticalTabs(const QTabBar::Shape shape) {
-    return (shape == QTabBar::RoundedEast
-                || shape == QTabBar::TriangularEast
-                || shape == QTabBar::RoundedWest
-                || shape == QTabBar::TriangularWest);
-}
-
-void drawTabCloseButton(QPainter *p, bool hover, bool active, bool selected)
-{
-    // draw background circle
-    QRect rect(0, 0, closeButtonSize, closeButtonSize);
-    QColor background;
-    if (hover) {
-        background = QColor(124, 124, 124);
-    } else {
-        if (active) {
-            if (selected)
-                background = QColor(104, 104, 104);
-            else
-                background = QColor(83, 83, 83);
-        } else {
-            if (selected)
-                background = QColor(144, 144, 144);
-            else
-                background = QColor(114, 114, 114);
-        }
-    }
-    p->setPen(Qt::transparent);
-    p->setBrush(background);
-    p->drawEllipse(rect);
-
-    // draw cross
-    int min = 3;
-    int max = 9;
-    QPen crossPen;
-    crossPen.setColor(QColor(194, 194, 194));
-    crossPen.setWidthF(1.3);
-    crossPen.setCapStyle(Qt::FlatCap);
-    p->setPen(crossPen);
-    p->drawLine(min, min, max, max);
-    p->drawLine(min, max, max, min);
-}
-
-QRect rotateTabPainter(QPainter *p, QTabBar::Shape shape, QRect tabRect)
-{
-    if (isVerticalTabs(shape)) {
-        int newX, newY, newRot;
-        if (shape == QTabBar::RoundedEast
-            || shape == QTabBar::TriangularEast) {
-            newX = tabRect.width();
-            newY = tabRect.y();
-            newRot = 90;
-        } else {
-            newX = 0;
-            newY = tabRect.y() + tabRect.height();
-            newRot = -90;
-        }
-        tabRect.setRect(0, 0, tabRect.height(), tabRect.width());
-        QMatrix m;
-        m.translate(newX, newY);
-        m.rotate(newRot);
-        p->setMatrix(m, true);
-    }
-    return tabRect;
-}
-
-void drawTabShape(QPainter *p, const QStyleOptionTabV3 *tabOpt)
-{
-    QRect r = tabOpt->rect;
-    p->translate(tabOpt->rect.x(), tabOpt->rect.y());
-    r.moveLeft(0);
-    r.moveTop(0);
-    QRect tabRect = rotateTabPainter(p, tabOpt->shape, r);
-
-    int width = tabRect.width();
-    int height = 20;
-    bool active = (tabOpt->state & QStyle::State_Active);
-    bool selected = (tabOpt->state & QStyle::State_Selected);
-
-    if (selected) {
-        QRect rect(1, 0, width - 2, height);
-
-        // fill body
-        if (active) {
-            int d = (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) ? 16 : 0;
-            p->fillRect(rect, QColor(151 + d, 151 + d, 151 + d));
-        } else {
-            int d = (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) ? 9 : 0;
-            QLinearGradient gradient(rect.topLeft(), rect.bottomLeft());
-            gradient.setColorAt(0, QColor(207 + d, 207 + d, 207 + d));
-            gradient.setColorAt(0.5, QColor(206 + d, 206 + d, 206 + d));
-            gradient.setColorAt(1, QColor(201 + d, 201 + d, 201 + d));
-            p->fillRect(rect, gradient);
-        }
-
-        // draw border
-        QColor borderSides;
-        QColor borderBottom;
-        if (active) {
-            borderSides = QColor(88, 88, 88);
-            borderBottom = QColor(88, 88, 88);
-        } else {
-            borderSides = QColor(121, 121, 121);
-            borderBottom = QColor(116, 116, 116);
-        }
-
-        p->setPen(borderSides);
-
-        int bottom = height;
-        // left line
-        p->drawLine(0, 1, 0, bottom-2);
-        // right line
-        p->drawLine(width-1, 1, width-1, bottom-2);
-
-        // bottom line
-        if (active) {
-            p->setPen(QColor(168, 168, 168));
-            p->drawLine(3, bottom-1, width-3, bottom-1);
-        }
-        p->setPen(borderBottom);
-        p->drawLine(2, bottom, width-2, bottom);
-
-        int w = 3;
-        QRectF rectangleLeft(1, height - w, w, w);
-        QRectF rectangleRight(width - 2, height - 1, w, w);
-        int startAngle = 180 * 16;
-        int spanAngle = 90 * 16;
-        p->drawArc(rectangleLeft, startAngle, spanAngle);
-        p->drawArc(rectangleRight, startAngle, -spanAngle);
-    } else {
-        // when the mouse is over non selected tabs they get a new color
-        bool hover = (tabOpt->state & QStyle::State_MouseOver);
-        if (hover) {
-            QRect rect(1, 2, width - 1, height - 1);
-            p->fillRect(rect, QColor(110, 110, 110));
-        }
-
-        // seperator lines between tabs
-        bool west = (tabOpt->shape == QTabBar::RoundedWest || tabOpt->shape == QTabBar::TriangularWest);
-        bool drawOnRight = !west;
-        if ((!drawOnRight && tabOpt->selectedPosition != QStyleOptionTab::NextIsSelected)
-            || (drawOnRight && tabOpt->selectedPosition != QStyleOptionTab::NextIsSelected)) {
-            QColor borderColor;
-            QColor borderHighlightColor;
-            if (active) {
-                borderColor = QColor(64, 64, 64);
-                borderHighlightColor = QColor(140, 140, 140);
-            } else {
-                borderColor = QColor(135, 135, 135);
-                borderHighlightColor = QColor(178, 178, 178);
-            }
-
-            int x = drawOnRight ? width : 0;
-
-            // tab seperator line
-            p->setPen(borderColor);
-            p->drawLine(x, 2, x, height + 1);
-
-            // tab seperator highlight
-            p->setPen(borderHighlightColor);
-            p->drawLine(x-1, 2, x-1, height + 1);
-            p->drawLine(x+1, 2, x+1, height + 1);
-        }
-    }
-}
-
-void drawTabBase(QPainter *p, const QStyleOptionTabBarBaseV2 *tbb, const QWidget *w)
-{
-    QRect r = tbb->rect;
-    if (isVerticalTabs(tbb->shape)) {
-        r.setWidth(w->width());
-    } else {
-        r.setHeight(w->height());
-    }
-    QRect tabRect = rotateTabPainter(p, tbb->shape, r);
-    int width = tabRect.width();
-    int height = tabRect.height();
-    bool active = (tbb->state & QStyle::State_Active);
-
-    // top border lines
-    QColor borderHighlightTop;
-    QColor borderTop;
-    if (active) {
-        borderTop = QColor(64, 64, 64);
-        borderHighlightTop = QColor(174, 174, 174);
-    } else {
-        borderTop = QColor(135, 135, 135);
-        borderHighlightTop = QColor(207, 207, 207);
-    }
-    p->setPen(borderHighlightTop);
-    p->drawLine(tabRect.x(), 0, width, 0);
-    p->setPen(borderTop);
-    p->drawLine(tabRect.x(), 1, width, 1);
-
-    // center block
-    QRect centralRect(tabRect.x(), 2, width, height - 2);
-    if (active) {
-        QColor mainColor = QColor(120, 120, 120);
-        p->fillRect(centralRect, mainColor);
-    } else {
-        QLinearGradient gradient(centralRect.topLeft(), centralRect.bottomLeft());
-        gradient.setColorAt(0, QColor(165, 165, 165));
-        gradient.setColorAt(0.5, QColor(164, 164, 164));
-        gradient.setColorAt(1, QColor(158, 158, 158));
-        p->fillRect(centralRect, gradient);
-    }
-
-    // bottom border lines
-    QColor borderHighlightBottom;
-    QColor borderBottom;
-    if (active) {
-        borderHighlightBottom = QColor(153, 153, 153);
-        borderBottom = QColor(64, 64, 64);
-    } else {
-        borderHighlightBottom = QColor(177, 177, 177);
-        borderBottom = QColor(127, 127, 127);
-    }
-    p->setPen(borderHighlightBottom);
-    p->drawLine(tabRect.x(), height - 2, width, height - 2);
-    p->setPen(borderBottom);
-    p->drawLine(tabRect.x(), height - 1, width, height - 1);
-}
-
-static int getControlSize(const QStyleOption *option, const QWidget *widget)
-{
-    if (option) {
-        if (option->state & (QStyle::State_Small | QStyle::State_Mini))
-            return (option->state & QStyle::State_Mini) ? QAquaSizeMini : QAquaSizeSmall;
-    } else if (widget) {
-        switch (QMacStyle::widgetSizePolicy(widget)) {
-        case QMacStyle::SizeSmall:
-            return QAquaSizeSmall;
-        case QMacStyle::SizeMini:
-            return QAquaSizeMini;
-        default:
-            break;
-        }
-    }
-    return QAquaSizeLarge;
-}
-
-
-static inline bool isTreeView(const QWidget *widget)
-{
-    return (widget && widget->parentWidget() &&
-            (qobject_cast<const QTreeView *>(widget->parentWidget())));
-}
-
-QString qt_mac_removeMnemonics(const QString &original)
-{
-    QString returnText(original.size(), 0);
-    int finalDest = 0;
-    int currPos = 0;
-    int l = original.length();
-    while (l) {
-        if (original.at(currPos) == QLatin1Char('&')
-            && (l == 1 || original.at(currPos + 1) != QLatin1Char('&'))) {
-            ++currPos;
-            --l;
-            if (l == 0)
-                break;
-        }
-        returnText[finalDest] = original.at(currPos);
-        ++currPos;
-        ++finalDest;
-        --l;
-    }
-    returnText.truncate(finalDest);
-    return returnText;
-}
-
-static inline ThemeTabDirection getTabDirection(QTabBar::Shape shape)
-{
-    ThemeTabDirection ttd;
-    switch (shape) {
-    case QTabBar::RoundedSouth:
-    case QTabBar::TriangularSouth:
-        ttd = kThemeTabSouth;
-        break;
-    default:  // Added to remove the warning, since all values are taken care of, really!
-    case QTabBar::RoundedNorth:
-    case QTabBar::TriangularNorth:
-        ttd = kThemeTabNorth;
-        break;
-    case QTabBar::RoundedWest:
-    case QTabBar::TriangularWest:
-        ttd = kThemeTabWest;
-        break;
-    case QTabBar::RoundedEast:
-    case QTabBar::TriangularEast:
-        ttd = kThemeTabEast;
-        break;
-    }
-    return ttd;
-}
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include "moc_qmacstyle_mac.h"
-#include "moc_qmacstyle_mac_p.h"
-QT_END_INCLUDE_NAMESPACE
-
-/*****************************************************************************
-  External functions
- *****************************************************************************/
-extern CGContextRef qt_mac_cg_context(const QPaintDevice *); //qpaintdevice_mac.cpp
-extern QRegion qt_mac_convert_mac_region(HIShapeRef); //qregion_mac.cpp
-void qt_mac_dispose_rgn(RgnHandle r); //qregion_mac.cpp
-extern QPaintDevice *qt_mac_safe_pdev; //qapplication_mac.cpp
-
-/*****************************************************************************
-  QMacCGStyle globals
- *****************************************************************************/
-const int qt_mac_hitheme_version = 0; //the HITheme version we speak
-const int macItemFrame         = 2;    // menu item frame width
-const int macItemHMargin       = 3;    // menu item hor text margin
-const int macItemVMargin       = 2;    // menu item ver text margin
-const int macRightBorder       = 12;   // right border on mac
-const ThemeWindowType QtWinType = kThemeDocumentWindow; // Window type we use for QTitleBar.
-QPixmap *qt_mac_backgroundPattern = 0; // stores the standard widget background.
-
-/*****************************************************************************
-  QMacCGStyle utility functions
- *****************************************************************************/
-static inline int qt_mac_hitheme_tab_version()
-{
-    return 1;
-}
-
-static inline HIRect qt_hirectForQRect(const QRect &convertRect, const QRect &rect = QRect())
-{
-    return CGRectMake(convertRect.x() + rect.x(), convertRect.y() + rect.y(),
-                      convertRect.width() - rect.width(), convertRect.height() - rect.height());
-}
-
-static inline const QRect qt_qrectForHIRect(const HIRect &hirect)
-{
-    return QRect(QPoint(int(hirect.origin.x), int(hirect.origin.y)),
-                 QSize(int(hirect.size.width), int(hirect.size.height)));
-}
-
-inline bool qt_mac_is_metal(const QWidget *w)
-{
-    for (; w; w = w->parentWidget()) {
-        if (w->testAttribute(Qt::WA_MacBrushedMetal))
-            return true;
-        if (w->isWindow() && w->testAttribute(Qt::WA_WState_Created)) {  // If not created will fall through to the opaque check and be fine anyway.
-                       return macWindowIsTextured(qt_mac_window_for(w));
-        }
-        if (w->d_func()->isOpaque)
-            break;
-    }
-    return false;
-}
-
-static int qt_mac_aqua_get_metric(ThemeMetric met)
-{
-    SInt32 ret;
-    GetThemeMetric(met, &ret);
-    return ret;
-}
-
-static QSize qt_aqua_get_known_size(QStyle::ContentsType ct, const QWidget *widg, QSize szHint,
-                                    QAquaWidgetSize sz)
-{
-    QSize ret(-1, -1);
-    if (sz != QAquaSizeSmall && sz != QAquaSizeLarge && sz != QAquaSizeMini) {
-        qDebug("Not sure how to return this...");
-        return ret;
-    }
-    if ((widg && widg->testAttribute(Qt::WA_SetFont)) || !QApplication::desktopSettingsAware()) {
-        // If you're using a custom font and it's bigger than the default font,
-        // then no constraints for you. If you are smaller, we can try to help you out
-        QFont font = qt_app_fonts_hash()->value(widg->metaObject()->className(), QFont());
-        if (widg->font().pointSize() > font.pointSize())
-            return ret;
-    }
-
-    if (ct == QStyle::CT_CustomBase && widg) {
-        if (qobject_cast<const QPushButton *>(widg))
-            ct = QStyle::CT_PushButton;
-        else if (qobject_cast<const QRadioButton *>(widg))
-            ct = QStyle::CT_RadioButton;
-        else if (qobject_cast<const QCheckBox *>(widg))
-            ct = QStyle::CT_CheckBox;
-        else if (qobject_cast<const QComboBox *>(widg))
-            ct = QStyle::CT_ComboBox;
-        else if (qobject_cast<const QToolButton *>(widg))
-            ct = QStyle::CT_ToolButton;
-        else if (qobject_cast<const QSlider *>(widg))
-            ct = QStyle::CT_Slider;
-        else if (qobject_cast<const QProgressBar *>(widg))
-            ct = QStyle::CT_ProgressBar;
-        else if (qobject_cast<const QLineEdit *>(widg))
-            ct = QStyle::CT_LineEdit;
-        else if (qobject_cast<const QHeaderView *>(widg))
-            ct = QStyle::CT_HeaderSection;
-        else if (qobject_cast<const QMenuBar *>(widg))
-            ct = QStyle::CT_MenuBar;
-        else if (qobject_cast<const QSizeGrip *>(widg))
-            ct = QStyle::CT_SizeGrip;
-        else
-            return ret;
-    }
-
-    switch (ct) {
-    case QStyle::CT_PushButton: {
-        const QPushButton *psh = qobject_cast<const QPushButton *>(widg);
-        // If this comparison is false, then the widget was not a push button.
-        // This is bad and there's very little we can do since we were requested to find a
-        // sensible size for a widget that pretends to be a QPushButton but is not.
-        if(psh) {
-            QString buttonText = qt_mac_removeMnemonics(psh->text());
-            if (buttonText.contains(QLatin1Char('\n')))
-                ret = QSize(-1, -1);
-            else if (sz == QAquaSizeLarge)
-                ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricPushButtonHeight));
-            else if (sz == QAquaSizeSmall)
-                ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallPushButtonHeight));
-            else if (sz == QAquaSizeMini)
-                ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniPushButtonHeight));
-
-            if (!psh->icon().isNull()){
-                // If the button got an icon, and the icon is larger than the
-                // button, we can't decide on a default size
-                ret.setWidth(-1);
-                if (ret.height() < psh->iconSize().height())
-                    ret.setHeight(-1);
-            }
-            else if (buttonText == QLatin1String("OK") || buttonText == QLatin1String("Cancel")){
-                // Aqua Style guidelines restrict the size of OK and Cancel buttons to 68 pixels.
-                // However, this doesn't work for German, therefore only do it for English,
-                // I suppose it would be better to do some sort of lookups for languages
-                // that like to have really long words.
-                ret.setWidth(77 - 8);
-            }
-        } else {
-            // The only sensible thing to do is to return whatever the style suggests...
-            if (sz == QAquaSizeLarge)
-                ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricPushButtonHeight));
-            else if (sz == QAquaSizeSmall)
-                ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallPushButtonHeight));
-            else if (sz == QAquaSizeMini)
-                ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniPushButtonHeight));
-            else
-                // Since there's no default size we return the large size...
-                ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricPushButtonHeight));
-         }
-#if 0 //Not sure we are applying the rules correctly for RadioButtons/CheckBoxes --Sam
-    } else if (ct == QStyle::CT_RadioButton) {
-        QRadioButton *rdo = static_cast<QRadioButton *>(widg);
-        // Exception for case where multiline radio button text requires no size constrainment
-        if (rdo->text().find('\n') != -1)
-            return ret;
-        if (sz == QAquaSizeLarge)
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricRadioButtonHeight));
-        else if (sz == QAquaSizeSmall)
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallRadioButtonHeight));
-        else if (sz == QAquaSizeMini)
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniRadioButtonHeight));
-    } else if (ct == QStyle::CT_CheckBox) {
-        if (sz == QAquaSizeLarge)
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricCheckBoxHeight));
-        else if (sz == QAquaSizeSmall)
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallCheckBoxHeight));
-        else if (sz == QAquaSizeMini)
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniCheckBoxHeight));
-#endif
-        break;
-    }
-    case QStyle::CT_SizeGrip:
-        if (sz == QAquaSizeLarge || sz == QAquaSizeSmall) {
-            HIRect r;
-            HIPoint p = { 0, 0 };
-            HIThemeGrowBoxDrawInfo gbi;
-            gbi.version = 0;
-            gbi.state = kThemeStateActive;
-            gbi.kind = kHIThemeGrowBoxKindNormal;
-            gbi.direction = QApplication::isRightToLeft() ? kThemeGrowLeft | kThemeGrowDown
-                                                          : kThemeGrowRight | kThemeGrowDown;
-            gbi.size = sz == QAquaSizeSmall ? kHIThemeGrowBoxSizeSmall : kHIThemeGrowBoxSizeNormal;
-            if (HIThemeGetGrowBoxBounds(&p, &gbi, &r) == noErr)
-                ret = QSize(r.size.width, r.size.height);
-        }
-        break;
-    case QStyle::CT_ComboBox:
-        switch (sz) {
-        case QAquaSizeLarge:
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricPopupButtonHeight));
-            break;
-        case QAquaSizeSmall:
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricSmallPopupButtonHeight));
-            break;
-        case QAquaSizeMini:
-            ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricMiniPopupButtonHeight));
-            break;
-        default:
-            break;
-        }
-        break;
-    case QStyle::CT_ToolButton:
-        if (sz == QAquaSizeSmall) {
-            int width = 0, height = 0;
-            if (szHint == QSize(-1, -1)) { //just 'guess'..
-                const QToolButton *bt = qobject_cast<const QToolButton *>(widg);
-                // If this conversion fails then the widget was not what it claimed to be.
-                if(bt) {
-                    if (!bt->icon().isNull()) {
-                        QSize iconSize = bt->iconSize();
-                        QSize pmSize = bt->icon().actualSize(QSize(32, 32), QIcon::Normal);
-                        width = qMax(width, qMax(iconSize.width(), pmSize.width()));
-                        height = qMax(height, qMax(iconSize.height(), pmSize.height()));
-                    }
-                    if (!bt->text().isNull() && bt->toolButtonStyle() != Qt::ToolButtonIconOnly) {
-                        int text_width = bt->fontMetrics().width(bt->text()),
-                           text_height = bt->fontMetrics().height();
-                        if (bt->toolButtonStyle() == Qt::ToolButtonTextUnderIcon) {
-                            width = qMax(width, text_width);
-                            height += text_height;
-                        } else {
-                            width += text_width;
-                            width = qMax(height, text_height);
-                        }
-                    }
-                } else {
-                    // Let's return the size hint...
-                    width = szHint.width();
-                    height = szHint.height();
-                }
-            } else {
-                width = szHint.width();
-                height = szHint.height();
-            }
-            width =  qMax(20, width +  5); //border
-            height = qMax(20, height + 5); //border
-            ret = QSize(width, height);
-        }
-        break;
-    case QStyle::CT_Slider: {
-        int w = -1;
-        const QSlider *sld = qobject_cast<const QSlider *>(widg);
-        // If this conversion fails then the widget was not what it claimed to be.
-        if(sld) {
-            if (sz == QAquaSizeLarge) {
-                if (sld->orientation() == Qt::Horizontal) {
-                    w = qt_mac_aqua_get_metric(kThemeMetricHSliderHeight);
-                    if (sld->tickPosition() != QSlider::NoTicks)
-                        w += qt_mac_aqua_get_metric(kThemeMetricHSliderTickHeight);
-                } else {
-                    w = qt_mac_aqua_get_metric(kThemeMetricVSliderWidth);
-                    if (sld->tickPosition() != QSlider::NoTicks)
-                        w += qt_mac_aqua_get_metric(kThemeMetricVSliderTickWidth);
-                }
-            } else if (sz == QAquaSizeSmall) {
-                if (sld->orientation() == Qt::Horizontal) {
-                    w = qt_mac_aqua_get_metric(kThemeMetricSmallHSliderHeight);
-                    if (sld->tickPosition() != QSlider::NoTicks)
-                        w += qt_mac_aqua_get_metric(kThemeMetricSmallHSliderTickHeight);
-                } else {
-                    w = qt_mac_aqua_get_metric(kThemeMetricSmallVSliderWidth);
-                    if (sld->tickPosition() != QSlider::NoTicks)
-                        w += qt_mac_aqua_get_metric(kThemeMetricSmallVSliderTickWidth);
-                }
-            } else if (sz == QAquaSizeMini) {
-                if (sld->orientation() == Qt::Horizontal) {
-                    w = qt_mac_aqua_get_metric(kThemeMetricMiniHSliderHeight);
-                    if (sld->tickPosition() != QSlider::NoTicks)
-                        w += qt_mac_aqua_get_metric(kThemeMetricMiniHSliderTickHeight);
-                } else {
-                    w = qt_mac_aqua_get_metric(kThemeMetricMiniVSliderWidth);
-                    if (sld->tickPosition() != QSlider::NoTicks)
-                        w += qt_mac_aqua_get_metric(kThemeMetricMiniVSliderTickWidth);
-                }
-            }
-        } else {
-            // This is tricky, we were requested to find a size for a slider which is not
-            // a slider. We don't know if this is vertical or horizontal or if we need to
-            // have tick marks or not.
-            // For this case we will return an horizontal slider without tick marks.
-            w = qt_mac_aqua_get_metric(kThemeMetricHSliderHeight);
-            w += qt_mac_aqua_get_metric(kThemeMetricHSliderTickHeight);
-        }
-        if (sld->orientation() == Qt::Horizontal)
-            ret.setHeight(w);
-        else
-            ret.setWidth(w);
-        break;
-    }
-    case QStyle::CT_ProgressBar: {
-        int finalValue = -1;
-        Qt::Orientation orient = Qt::Horizontal;
-        if (const QProgressBar *pb = qobject_cast<const QProgressBar *>(widg))
-            orient = pb->orientation();
-
-        if (sz == QAquaSizeLarge)
-            finalValue = qt_mac_aqua_get_metric(kThemeMetricLargeProgressBarThickness)
-                            + qt_mac_aqua_get_metric(kThemeMetricProgressBarShadowOutset);
-        else
-            finalValue = qt_mac_aqua_get_metric(kThemeMetricNormalProgressBarThickness)
-                            + qt_mac_aqua_get_metric(kThemeMetricSmallProgressBarShadowOutset);
-        if (orient == Qt::Horizontal)
-            ret.setHeight(finalValue);
-        else
-            ret.setWidth(finalValue);
-        break;
-    }
-    case QStyle::CT_LineEdit:
-        if (!widg || !qobject_cast<QComboBox *>(widg->parentWidget())) {
-            //should I take into account the font dimentions of the lineedit? -Sam
-            if (sz == QAquaSizeLarge)
-                ret = QSize(-1, 21);
-            else
-                ret = QSize(-1, 19);
-        }
-        break;
-    case QStyle::CT_HeaderSection:
-        if (isTreeView(widg))
-           ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricListHeaderHeight));
-        break;
-    case QStyle::CT_MenuBar:
-        if (sz == QAquaSizeLarge) {
-#ifndef QT_MAC_USE_COCOA
-            SInt16 size;
-            if (!GetThemeMenuBarHeight(&size))
-                ret = QSize(-1, size);
-#else
-            ret = QSize(-1, [[[NSApplication sharedApplication] mainMenu] menuBarHeight]);
-            // In the qt_mac_set_native_menubar(false) case,
-            // we come it here with a zero-height main menu,
-            // preventing the in-window menu from displaying.
-            // Use 22 pixels for the height, by observation.
-            if (ret.height() <= 0)
-                ret.setHeight(22);
-#endif
-        }
-        break;
-    default:
-        break;
-    }
-    return ret;
-}
-
-
-#if defined(QMAC_QAQUASTYLE_SIZE_CONSTRAIN) || defined(DEBUG_SIZE_CONSTRAINT)
-static QAquaWidgetSize qt_aqua_guess_size(const QWidget *widg, QSize large, QSize small, QSize mini)
-{
-    if (large == QSize(-1, -1)) {
-        if (small != QSize(-1, -1))
-            return QAquaSizeSmall;
-        if (mini != QSize(-1, -1))
-            return QAquaSizeMini;
-        return QAquaSizeUnknown;
-    } else if (small == QSize(-1, -1)) {
-        if (mini != QSize(-1, -1))
-            return QAquaSizeMini;
-        return QAquaSizeLarge;
-    } else if (mini == QSize(-1, -1)) {
-        return QAquaSizeLarge;
-    }
-
-#ifndef QT_NO_MAINWINDOW
-    if (qobject_cast<QDockWidget *>(widg->window()) || !qgetenv("QWIDGET_ALL_SMALL").isNull()) {
-        //if (small.width() != -1 || small.height() != -1)
-        return QAquaSizeSmall;
-    } else if (!qgetenv("QWIDGET_ALL_MINI").isNull()) {
-        return QAquaSizeMini;
-    }
-#endif
-
-#if 0
-    /* Figure out which size we're closer to, I just hacked this in, I haven't
-       tested it as it would probably look pretty strange to have some widgets
-       big and some widgets small in the same window?? -Sam */
-    int large_delta=0;
-    if (large.width() != -1) {
-        int delta = large.width() - widg->width();
-        large_delta += delta * delta;
-    }
-    if (large.height() != -1) {
-        int delta = large.height() - widg->height();
-        large_delta += delta * delta;
-    }
-    int small_delta=0;
-    if (small.width() != -1) {
-        int delta = small.width() - widg->width();
-        small_delta += delta * delta;
-    }
-    if (small.height() != -1) {
-        int delta = small.height() - widg->height();
-        small_delta += delta * delta;
-    }
-    int mini_delta=0;
-    if (mini.width() != -1) {
-        int delta = mini.width() - widg->width();
-        mini_delta += delta * delta;
-    }
-    if (mini.height() != -1) {
-        int delta = mini.height() - widg->height();
-        mini_delta += delta * delta;
-    }
-    if (mini_delta < small_delta && mini_delta < large_delta)
-        return QAquaSizeMini;
-    else if (small_delta < large_delta)
-        return QAquaSizeSmall;
-#endif
-    return QAquaSizeLarge;
-}
-#endif
-
-QAquaWidgetSize QMacStylePrivate::aquaSizeConstrain(const QStyleOption *option, const QWidget *widg,
-                                       QStyle::ContentsType ct, QSize szHint, QSize *insz) const
-{
-#if defined(QMAC_QAQUASTYLE_SIZE_CONSTRAIN) || defined(DEBUG_SIZE_CONSTRAINT)
-    if (option) {
-        if (option->state & QStyle::State_Small)
-            return QAquaSizeSmall;
-        if (option->state & QStyle::State_Mini)
-            return QAquaSizeMini;
-    }
-
-    if (!widg) {
-        if (insz)
-            *insz = QSize();
-        if (!qgetenv("QWIDGET_ALL_SMALL").isNull())
-            return QAquaSizeSmall;
-        if (!qgetenv("QWIDGET_ALL_MINI").isNull())
-            return QAquaSizeMini;
-        return QAquaSizeUnknown;
-    }
-    QSize large = qt_aqua_get_known_size(ct, widg, szHint, QAquaSizeLarge),
-          small = qt_aqua_get_known_size(ct, widg, szHint, QAquaSizeSmall),
-          mini  = qt_aqua_get_known_size(ct, widg, szHint, QAquaSizeMini);
-    bool guess_size = false;
-    QAquaWidgetSize ret = QAquaSizeUnknown;
-    QMacStyle::WidgetSizePolicy wsp = q->widgetSizePolicy(widg);
-    if (wsp == QMacStyle::SizeDefault)
-        guess_size = true;
-    else if (wsp == QMacStyle::SizeMini)
-        ret = QAquaSizeMini;
-    else if (wsp == QMacStyle::SizeSmall)
-        ret = QAquaSizeSmall;
-    else if (wsp == QMacStyle::SizeLarge)
-        ret = QAquaSizeLarge;
-    if (guess_size)
-        ret = qt_aqua_guess_size(widg, large, small, mini);
-
-    QSize *sz = 0;
-    if (ret == QAquaSizeSmall)
-        sz = &small;
-    else if (ret == QAquaSizeLarge)
-        sz = &large;
-    else if (ret == QAquaSizeMini)
-        sz = &mini;
-    if (insz)
-        *insz = sz ? *sz : QSize(-1, -1);
-#ifdef DEBUG_SIZE_CONSTRAINT
-    if (sz) {
-        const char *size_desc = "Unknown";
-        if (sz == &small)
-            size_desc = "Small";
-        else if (sz == &large)
-            size_desc = "Large";
-        else if (sz == &mini)
-            size_desc = "Mini";
-        qDebug("%s - %s: %s taken (%d, %d) [%d, %d]",
-               widg ? widg->objectName().toLatin1().constData() : "*Unknown*",
-               widg ? widg->metaObject()->className() : "*Unknown*", size_desc, widg->width(), widg->height(),
-               sz->width(), sz->height());
-    }
-#endif
-    return ret;
-#else
-    if (insz)
-        *insz = QSize();
-    Q_UNUSED(widg);
-    Q_UNUSED(ct);
-    Q_UNUSED(szHint);
-    return QAquaSizeUnknown;
-#endif
-}
-
-/**
-    Returns the free space awailable for contents inside the
-    button (and not the size of the contents itself)
-*/
-HIRect QMacStylePrivate::pushButtonContentBounds(const QStyleOptionButton *btn,
-                                                 const HIThemeButtonDrawInfo *bdi) const
-{
-    HIRect outerBounds = qt_hirectForQRect(btn->rect);
-    // Adjust the bounds to correct for
-    // carbon not calculating the content bounds fully correct
-    if (bdi->kind == kThemePushButton || bdi->kind == kThemePushButtonSmall){
-        outerBounds.origin.y += QMacStylePrivate::PushButtonTopOffset;
-        outerBounds.size.height -= QMacStylePrivate::PushButtonBottomOffset;
-    } else if (bdi->kind == kThemePushButtonMini) {
-        outerBounds.origin.y += QMacStylePrivate::PushButtonTopOffset;
-    }
-
-    HIRect contentBounds;
-    HIThemeGetButtonContentBounds(&outerBounds, bdi, &contentBounds);
-    return contentBounds;
-}
-
-/**
-    Calculates the size of the button contents.
-    This includes both the text and the icon.
-*/
-QSize QMacStylePrivate::pushButtonSizeFromContents(const QStyleOptionButton *btn) const
-{
-    QSize csz(0, 0);
-    QSize iconSize = btn->icon.isNull() ? QSize(0, 0)
-                : (btn->iconSize + QSize(QMacStylePrivate::PushButtonContentPadding, 0));
-    QRect textRect = btn->text.isEmpty() ? QRect(0, 0, 1, 1)
-                : btn->fontMetrics.boundingRect(QRect(), Qt::AlignCenter, btn->text);
-    csz.setWidth(iconSize.width() + textRect.width()
-             + ((btn->features & QStyleOptionButton::HasMenu)
-                            ? q->proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator, btn, 0) : 0));
-    csz.setHeight(qMax(iconSize.height(), textRect.height()));
-    return csz;
-}
-
-/**
-    Checks if the actual contents of btn fits inside the free content bounds of
-    'buttonKindToCheck'. Meant as a helper function for 'initHIThemePushButton'
-    for determining which button kind to use for drawing.
-*/
-bool QMacStylePrivate::contentFitsInPushButton(const QStyleOptionButton *btn,
-                                               HIThemeButtonDrawInfo *bdi,
-                                               ThemeButtonKind buttonKindToCheck) const
-{
-    ThemeButtonKind tmp = bdi->kind;
-    bdi->kind = buttonKindToCheck;
-    QSize contentSize = pushButtonSizeFromContents(btn);
-    QRect freeContentRect = qt_qrectForHIRect(pushButtonContentBounds(btn, bdi));
-    bdi->kind = tmp;
-    return freeContentRect.contains(QRect(freeContentRect.x(), freeContentRect.y(),
-                                    contentSize.width(), contentSize.height()));
-}
-
-/**
-    Creates a HIThemeButtonDrawInfo structure that specifies the correct button
-    kind and other details to use for drawing the given push button. Which
-    button kind depends on the size of the button, the size of the contents,
-    explicit user style settings, etc.
-*/
-void QMacStylePrivate::initHIThemePushButton(const QStyleOptionButton *btn,
-                                             const QWidget *widget,
-                                             const ThemeDrawState tds,
-                                             HIThemeButtonDrawInfo *bdi) const
-{
-    bool drawColorless = btn->palette.currentColorGroup() == QPalette::Active;
-    ThemeDrawState tdsModified = tds;
-    if (btn->state & QStyle::State_On)
-        tdsModified = kThemeStatePressed;
-    bdi->version = qt_mac_hitheme_version;
-    bdi->state = tdsModified;
-    bdi->value = kThemeButtonOff;
-
-    if (drawColorless && tdsModified == kThemeStateInactive)
-        bdi->state = kThemeStateActive;
-    if (btn->state & QStyle::State_HasFocus)
-        bdi->adornment = kThemeAdornmentFocus;
-    else
-        bdi->adornment = kThemeAdornmentNone;
-
-
-    if (btn->features & (QStyleOptionButton::Flat)) {
-        bdi->kind = kThemeBevelButton;
-    } else {
-        switch (aquaSizeConstrain(btn, widget)) {
-        case QAquaSizeSmall:
-            bdi->kind = kThemePushButtonSmall;
-            break;
-        case QAquaSizeMini:
-            bdi->kind = kThemePushButtonMini;
-            break;
-        case QAquaSizeLarge:
-            // ... We should honor if the user is explicit about using the
-            // large button. But right now Qt will specify the large button
-            // as default rather than QAquaSizeUnknown.
-            // So we treat it like QAquaSizeUnknown
-            // to get the dynamic choosing of button kind.
-        case QAquaSizeUnknown:
-            // Choose the button kind that closest match the button rect, but at the
-            // same time displays the button contents without clipping.
-            bdi->kind = kThemeBevelButton;
-            if (btn->rect.width() >= QMacStylePrivate::BevelButtonW && btn->rect.height() >= QMacStylePrivate::BevelButtonH){
-                if (widget && widget->testAttribute(Qt::WA_MacVariableSize)) {
-                    if (btn->rect.height() <= QMacStylePrivate::MiniButtonH){
-                        if (contentFitsInPushButton(btn, bdi, kThemePushButtonMini))
-                            bdi->kind = kThemePushButtonMini;
-                    } else if (btn->rect.height() <= QMacStylePrivate::SmallButtonH){
-                        if (contentFitsInPushButton(btn, bdi, kThemePushButtonSmall))
-                            bdi->kind = kThemePushButtonSmall;
-                    } else if (contentFitsInPushButton(btn, bdi, kThemePushButton)) {
-                        bdi->kind = kThemePushButton;
-                    }
-                } else {
-                    bdi->kind = kThemePushButton;
-                }
-            }
-        }
-    }
-}
-
-bool qt_mac_buttonIsRenderedFlat(const QPushButton *pushButton, const QStyleOptionButton *option)
-{
-    QMacStyle *macStyle = qobject_cast<QMacStyle *>(pushButton->style());
-    if (!macStyle)
-        return true;    // revert to 'flat' behavior if not Mac style
-    HIThemeButtonDrawInfo bdi;
-    macStyle->d->initHIThemePushButton(option, pushButton, kThemeStateActive, &bdi);
-    return bdi.kind == kThemeBevelButton;
-}
-
-/**
-    Creates a HIThemeButtonDrawInfo structure that specifies the correct button
-    kind and other details to use for drawing the given combobox. Which button
-    kind depends on the size of the combo, wether or not it is editable,
-    explicit user style settings, etc.
-*/
-void QMacStylePrivate::initComboboxBdi(const QStyleOptionComboBox *combo, HIThemeButtonDrawInfo *bdi,
-                                    const QWidget *widget, const ThemeDrawState &tds)
-{
-    bdi->version = qt_mac_hitheme_version;
-    bdi->adornment = kThemeAdornmentArrowLeftArrow;
-    bdi->value = kThemeButtonOff;
-    if (combo->state & QStyle::State_HasFocus)
-        bdi->adornment = kThemeAdornmentFocus;
-    bool drawColorless = combo->palette.currentColorGroup() == QPalette::Active && tds == kThemeStateInactive;
-    if (combo->activeSubControls & QStyle::SC_ComboBoxArrow)
-        bdi->state = kThemeStatePressed;
-    else if (drawColorless)
-        bdi->state = kThemeStateActive;
-    else
-        bdi->state = tds;
-
-    QAquaWidgetSize aSize = aquaSizeConstrain(combo, widget);
-    switch (aSize) {
-    case QAquaSizeMini:
-        bdi->kind = combo->editable ? ThemeButtonKind(kThemeComboBoxMini)
-            : ThemeButtonKind(kThemePopupButtonMini);
-        break;
-    case QAquaSizeSmall:
-        bdi->kind = combo->editable ? ThemeButtonKind(kThemeComboBoxSmall)
-            : ThemeButtonKind(kThemePopupButtonSmall);
-        break;
-    case QAquaSizeUnknown:
-    case QAquaSizeLarge:
-        // Unless the user explicitly specified large buttons, determine the
-        // kind by looking at the combox size.
-        // ... specifying small and mini-buttons it not a current feature of
-        // Qt (e.g. QWidget::getAttribute(WA_ButtonSize)). But when it is, add
-        // an extra check here before using the mini and small buttons.
-        int h = combo->rect.size().height();
-        if (combo->editable){
-            if (h < 21)
-                bdi->kind = kThemeComboBoxMini;
-            else if (h < 26)
-                bdi->kind = kThemeComboBoxSmall;
-            else
-                bdi->kind = kThemeComboBox;
-        } else {
-            // Even if we specify that we want the kThemePopupButton, Carbon
-            // will use the kThemePopupButtonSmall if the size matches. So we
-            // do the same size check explicit to have the size of the inner
-            // text field be correct. Therefore, do this even if the user specifies
-            // the use of LargeButtons explicit.
-            if (h < 21)
-                bdi->kind = kThemePopupButtonMini;
-            else if (h < 26)
-                bdi->kind = kThemePopupButtonSmall;
-            else
-                bdi->kind = kThemePopupButton;
-        }
-        break;
-    }
-}
-
-/**
-    Carbon draws comboboxes (and other views) outside the rect given as argument. Use this function to obtain
-    the corresponding inner rect for drawing the same combobox so that it stays inside the given outerBounds.
-*/
-HIRect QMacStylePrivate::comboboxInnerBounds(const HIRect &outerBounds, int buttonKind)
-{
-    HIRect innerBounds = outerBounds;
-    // Carbon draw parts of the view outside the rect.
-    // So make the rect a bit smaller to compensate
-    // (I wish HIThemeGetButtonBackgroundBounds worked)
-    switch (buttonKind){
-    case kThemePopupButton:
-        innerBounds.origin.x += 2;
-        innerBounds.origin.y += 2;
-        innerBounds.size.width -= 5;
-        innerBounds.size.height -= 6;
-        break;
-    case kThemePopupButtonSmall:
-        innerBounds.origin.x += 3;
-        innerBounds.origin.y += 3;
-        innerBounds.size.width -= 6;
-        innerBounds.size.height -= 7;
-        break;
-    case kThemePopupButtonMini:
-        innerBounds.origin.x += 2;
-        innerBounds.origin.y += 2;
-        innerBounds.size.width -= 5;
-        innerBounds.size.height -= 6;
-        break;
-    case kThemeComboBox:
-        innerBounds.origin.x += 3;
-        innerBounds.origin.y += 2;
-        innerBounds.size.width -= 6;
-        innerBounds.size.height -= 8;
-        break;
-    case kThemeComboBoxSmall:
-        innerBounds.origin.x += 3;
-        innerBounds.origin.y += 3;
-        innerBounds.size.width -= 7;
-        innerBounds.size.height -= 8;
-        break;
-    case kThemeComboBoxMini:
-        innerBounds.origin.x += 3;
-        innerBounds.origin.y += 3;
-        innerBounds.size.width -= 4;
-        innerBounds.size.height -= 8;
-        break;
-    default:
-        break;
-    }
-    return innerBounds;
-}
-
-/**
-    Inside a combobox Qt places a line edit widget. The size of this widget should depend on the kind
-    of combobox we choose to draw. This function calculates and returns this size.
-*/
-QRect QMacStylePrivate::comboboxEditBounds(const QRect &outerBounds, const HIThemeButtonDrawInfo &bdi)
-{
-    QRect ret = outerBounds;
-    switch (bdi.kind){
-    case kThemeComboBox:
-        ret.adjust(5, 5, -22, -5);
-        break;
-    case kThemeComboBoxSmall:
-        ret.adjust(4, 6, -20, 0);
-        ret.setHeight(14);
-        break;
-    case kThemeComboBoxMini:
-        ret.adjust(4, 5, -18, -1);
-        ret.setHeight(12);
-        break;
-    case kThemePopupButton:
-        ret.adjust(10, 2, -23, -4);
-        break;
-    case kThemePopupButtonSmall:
-        ret.adjust(9, 3, -20, -3);
-        break;
-    case kThemePopupButtonMini:
-        ret.adjust(8, 3, -19, 0);
-        ret.setHeight(13);
-        break;
-    }
-    return ret;
-}
-
-/**
-    Carbon comboboxes don't scale (sight). If the size of the combo suggest a scaled version,
-    create it manually by drawing a small Carbon combo onto a pixmap (use pixmap cache), chop
-    it up, and copy it back onto the widget. Othervise, draw the combobox supplied by Carbon directly.
-*/
-void QMacStylePrivate::drawCombobox(const HIRect &outerBounds, const HIThemeButtonDrawInfo &bdi, QPainter *p)
-{
-    if (!(bdi.kind == kThemeComboBox && outerBounds.size.height > 28)){
-        // We have an unscaled combobox, or popup-button; use Carbon directly.
-        HIRect innerBounds = QMacStylePrivate::comboboxInnerBounds(outerBounds, bdi.kind);
-        HIThemeDrawButton(&innerBounds, &bdi, QMacCGContext(p), kHIThemeOrientationNormal, 0);
-    } else {
-        QPixmap buffer;
-        QString key = QString(QLatin1String("$qt_cbox%1-%2")).arg(int(bdi.state)).arg(int(bdi.adornment));
-        if (!QPixmapCache::find(key, buffer)) {
-            HIRect innerBoundsSmallCombo = {{3, 3}, {29, 25}};
-            buffer = QPixmap(35, 28);
-            buffer.fill(Qt::transparent);
-            QPainter buffPainter(&buffer);
-            HIThemeDrawButton(&innerBoundsSmallCombo, &bdi, QMacCGContext(&buffPainter), kHIThemeOrientationNormal, 0);
-            buffPainter.end();
-            QPixmapCache::insert(key, buffer);
-        }
-
-        const int bwidth = 20;
-        const int fwidth = 10;
-        const int fheight = 10;
-        int w = qRound(outerBounds.size.width);
-        int h = qRound(outerBounds.size.height);
-        int bstart = w - bwidth;
-        int blower = fheight + 1;
-        int flower = h - fheight;
-        int sheight = flower - fheight;
-        int center = qRound(outerBounds.size.height + outerBounds.origin.y) / 2;
-
-        // Draw upper and lower gap
-        p->drawPixmap(fwidth, 0, bstart - fwidth, fheight, buffer, fwidth, 0, 1, fheight);
-        p->drawPixmap(fwidth, flower, bstart - fwidth, fheight, buffer, fwidth, buffer.height() - fheight, 1, fheight);
-        // Draw left and right gap. Right gap is drawn top and bottom separatly
-        p->drawPixmap(0, fheight, fwidth, sheight, buffer, 0, fheight, fwidth, 1);
-        p->drawPixmap(bstart, fheight, bwidth, center - fheight, buffer, buffer.width() - bwidth, fheight - 1, bwidth, 1);
-        p->drawPixmap(bstart, center, bwidth, sheight / 2, buffer, buffer.width() - bwidth, fheight + 6, bwidth, 1);
-        // Draw arrow
-        p->drawPixmap(bstart, center - 4, bwidth - 3, 6, buffer, buffer.width() - bwidth, fheight, bwidth - 3, 6);
-        // Draw corners
-        p->drawPixmap(0, 0, fwidth, fheight, buffer, 0, 0, fwidth, fheight);
-        p->drawPixmap(bstart, 0, bwidth, fheight, buffer, buffer.width() - bwidth, 0, bwidth, fheight);
-        p->drawPixmap(0, flower, fwidth, fheight, buffer, 0, buffer.height() - fheight, fwidth, fheight);
-        p->drawPixmap(bstart, h - blower, bwidth, blower, buffer, buffer.width() - bwidth, buffer.height() - blower, bwidth, blower);
-    }
-}
-
-/**
-    Carbon tableheaders don't scale (sight). So create it manually by drawing a small Carbon header
-    onto a pixmap (use pixmap cache), chop it up, and copy it back onto the widget.
-*/
-void QMacStylePrivate::drawTableHeader(const HIRect &outerBounds,
-    bool drawTopBorder, bool drawLeftBorder, const HIThemeButtonDrawInfo &bdi, QPainter *p)
-{
-    static SInt32 headerHeight = 0;
-    static OSStatus err = GetThemeMetric(kThemeMetricListHeaderHeight, &headerHeight);
-    Q_UNUSED(err);
-
-    QPixmap buffer;
-    QString key = QString(QLatin1String("$qt_tableh%1-%2-%3")).arg(int(bdi.state)).arg(int(bdi.adornment)).arg(int(bdi.value));
-    if (!QPixmapCache::find(key, buffer)) {
-        HIRect headerNormalRect = {{0., 0.}, {16., CGFloat(headerHeight)}};
-        buffer = QPixmap(headerNormalRect.size.width, headerNormalRect.size.height);
-        buffer.fill(Qt::transparent);
-        QPainter buffPainter(&buffer);
-        HIThemeDrawButton(&headerNormalRect, &bdi, QMacCGContext(&buffPainter), kHIThemeOrientationNormal, 0);
-        buffPainter.end();
-        QPixmapCache::insert(key, buffer);
-    }
-    const int buttonw = qRound(outerBounds.size.width);
-    const int buttonh = qRound(outerBounds.size.height);
-    const int framew = 1;
-    const int frameh_n = 4;
-    const int frameh_s = 3;
-    const int transh = buffer.height() - frameh_n - frameh_s;
-    int center = buttonh - frameh_s - int(transh / 2.0f) + 1; // Align bottom;
-
-    int skipTopBorder = 0;
-    if (!drawTopBorder)
-        skipTopBorder = 1;
-
-    p->translate(outerBounds.origin.x, outerBounds.origin.y);
-
-    p->drawPixmap(QRect(QRect(0, -skipTopBorder, buttonw - framew , frameh_n)), buffer, QRect(framew, 0, 1, frameh_n));
-    p->drawPixmap(QRect(0, buttonh - frameh_s, buttonw - framew, frameh_s), buffer, QRect(framew, buffer.height() - frameh_s, 1, frameh_s));
-    // Draw upper and lower center blocks
-    p->drawPixmap(QRect(0, frameh_n - skipTopBorder, buttonw - framew, center - frameh_n + skipTopBorder), buffer, QRect(framew, frameh_n, 1, 1));
-    p->drawPixmap(QRect(0, center, buttonw - framew, buttonh - center - frameh_s), buffer, QRect(framew, buffer.height() - frameh_s, 1, 1));
-    // Draw right center block borders
-    p->drawPixmap(QRect(buttonw - framew, frameh_n - skipTopBorder, framew, center - frameh_n), buffer, QRect(buffer.width() - framew, frameh_n, framew, 1));
-    p->drawPixmap(QRect(buttonw - framew, center, framew, buttonh - center - 1), buffer, QRect(buffer.width() - framew, buffer.height() - frameh_s, framew, 1));
-    // Draw right corners
-    p->drawPixmap(QRect(buttonw - framew, -skipTopBorder, framew, frameh_n), buffer, QRect(buffer.width() - framew, 0, framew, frameh_n));
-    p->drawPixmap(QRect(buttonw - framew, buttonh - frameh_s, framew, frameh_s), buffer, QRect(buffer.width() - framew, buffer.height() - frameh_s, framew, frameh_s));
-    // Draw center transition block
-    p->drawPixmap(QRect(0, center - qRound(transh / 2.0f), buttonw - framew, buffer.height() - frameh_n - frameh_s), buffer, QRect(framew, frameh_n + 1, 1, transh));
-    // Draw right center transition block border
-    p->drawPixmap(QRect(buttonw - framew, center - qRound(transh / 2.0f), framew, buffer.height() - frameh_n - frameh_s), buffer, QRect(buffer.width() - framew, frameh_n + 1, framew, transh));
-    if (drawLeftBorder){
-        // Draw left center block borders
-        p->drawPixmap(QRect(0, frameh_n - skipTopBorder, framew, center - frameh_n + skipTopBorder), buffer, QRect(0, frameh_n, framew, 1));
-        p->drawPixmap(QRect(0, center, framew, buttonh - center - 1), buffer, QRect(0, buffer.height() - frameh_s, framew, 1));
-        // Draw left corners
-        p->drawPixmap(QRect(0, -skipTopBorder, framew, frameh_n), buffer, QRect(0, 0, framew, frameh_n));
-        p->drawPixmap(QRect(0, buttonh - frameh_s, framew, frameh_s), buffer, QRect(0, buffer.height() - frameh_s, framew, frameh_s));
-        // Draw left center transition block border
-        p->drawPixmap(QRect(0, center - qRound(transh / 2.0f), framew, buffer.height() - frameh_n - frameh_s), buffer, QRect(0, frameh_n + 1, framew, transh));
-    }
-
-    p->translate(-outerBounds.origin.x, -outerBounds.origin.y);
-}
-
-/*
-    Returns cutoff sizes for scroll bars.
-    thumbIndicatorCutoff is the smallest size where the thumb indicator is drawn.
-    scrollButtonsCutoff is the smallest size where the up/down buttons is drawn.
-*/
-enum ScrollBarCutoffType { thumbIndicatorCutoff = 0, scrollButtonsCutoff = 1 };
-static int scrollButtonsCutoffSize(ScrollBarCutoffType cutoffType, QMacStyle::WidgetSizePolicy widgetSize)
-{
-    // Mini scroll bars do not exist as of version 10.4.
-    if (widgetSize ==  QMacStyle::SizeMini)
-        return 0;
-
-    const int sizeIndex = (widgetSize == QMacStyle::SizeSmall) ? 1 : 0;
-    static const int sizeTable[2][2] = { { 61, 56 }, { 49, 44 } };
-    return sizeTable[sizeIndex][cutoffType];
-}
-
-void QMacStylePrivate::getSliderInfo(QStyle::ComplexControl cc, const QStyleOptionSlider *slider,
-                          HIThemeTrackDrawInfo *tdi, const QWidget *needToRemoveMe)
-{
-    memset(tdi, 0, sizeof(HIThemeTrackDrawInfo)); // We don't get it all for some reason or another...
-    tdi->version = qt_mac_hitheme_version;
-    tdi->reserved = 0;
-    tdi->filler1 = 0;
-    bool isScrollbar = (cc == QStyle::CC_ScrollBar);
-    switch (aquaSizeConstrain(0, needToRemoveMe)) {
-    case QAquaSizeUnknown:
-    case QAquaSizeLarge:
-        if (isScrollbar)
-            tdi->kind = kThemeMediumScrollBar;
-        else
-            tdi->kind = kThemeMediumSlider;
-        break;
-    case QAquaSizeMini:
-        if (isScrollbar)
-            tdi->kind = kThemeSmallScrollBar; // should be kThemeMiniScrollBar, but not implemented
-        else
-            tdi->kind = kThemeMiniSlider;
-        break;
-    case QAquaSizeSmall:
-        if (isScrollbar)
-            tdi->kind = kThemeSmallScrollBar;
-        else
-            tdi->kind = kThemeSmallSlider;
-        break;
-    }
-    tdi->bounds = qt_hirectForQRect(slider->rect);
-    tdi->min = slider->minimum;
-    tdi->max = slider->maximum;
-    tdi->value = slider->sliderPosition;
-    tdi->attributes = kThemeTrackShowThumb;
-    if (slider->upsideDown)
-        tdi->attributes |= kThemeTrackRightToLeft;
-    if (slider->orientation == Qt::Horizontal) {
-        tdi->attributes |= kThemeTrackHorizontal;
-        if (isScrollbar && slider->direction == Qt::RightToLeft) {
-            if (!slider->upsideDown)
-                tdi->attributes |= kThemeTrackRightToLeft;
-            else
-                tdi->attributes &= ~kThemeTrackRightToLeft;
-        }
-    }
-
-    // Tiger broke reverse scroll bars so put them back and "fake it"
-    if (isScrollbar && (tdi->attributes & kThemeTrackRightToLeft)) {
-        tdi->attributes &= ~kThemeTrackRightToLeft;
-        tdi->value = tdi->max - slider->sliderPosition;
-    }
-
-    tdi->enableState = (slider->state & QStyle::State_Enabled) ? kThemeTrackActive
-                                                             : kThemeTrackDisabled;
-    if (!(slider->state & QStyle::State_Active))
-        tdi->enableState = kThemeTrackInactive;
-    if (!isScrollbar) {
-        if (slider->state & QStyle::QStyle::State_HasFocus)
-            tdi->attributes |= kThemeTrackHasFocus;
-        if (slider->tickPosition == QSlider::NoTicks || slider->tickPosition == QSlider::TicksBothSides)
-            tdi->trackInfo.slider.thumbDir = kThemeThumbPlain;
-        else if (slider->tickPosition == QSlider::TicksAbove)
-            tdi->trackInfo.slider.thumbDir = kThemeThumbUpward;
-        else
-            tdi->trackInfo.slider.thumbDir = kThemeThumbDownward;
-    } else {
-        tdi->trackInfo.scrollbar.viewsize = slider->pageStep;
-    }
-}
-#endif
-
-QMacStylePrivate::QMacStylePrivate(QMacStyle *style)
-    : timerID(-1), progressFrame(0), q(style), mouseDown(false)
-{
-    defaultButtonStart = CFAbsoluteTimeGetCurrent();
-    memset(&buttonState, 0, sizeof(ButtonState));
-
-    if (ptrHIShapeGetBounds == 0) {
-        QLibrary library(QLatin1String("/System/Library/Frameworks/Carbon.framework/Carbon"));
-        library.setLoadHints(QLibrary::ExportExternalSymbolsHint);
-               ptrHIShapeGetBounds = reinterpret_cast<PtrHIShapeGetBounds>(library.resolve("HIShapeGetBounds"));
-    }
-
-}
-
-bool QMacStylePrivate::animatable(QMacStylePrivate::Animates as, const QWidget *w) const
-{
-    if (!w)
-        return false;
-
-    if (as == AquaPushButton) {
-        QPushButton *pb = const_cast<QPushButton *>(static_cast<const QPushButton *>(w));
-        if (w->window()->isActiveWindow() && pb && !mouseDown) {
-            if (static_cast<const QPushButton *>(w) != defaultButton) {
-                // Changed on its own, update the value.
-                const_cast<QMacStylePrivate *>(this)->stopAnimate(as, defaultButton);
-                const_cast<QMacStylePrivate *>(this)->startAnimate(as, pb);
-            }
-            return true;
-        }
-    } else if (as == AquaProgressBar) {
-        if (progressBars.contains((const_cast<QWidget *>(w))))
-            return true;
-    }
-    return false;
-}
-
-void QMacStylePrivate::stopAnimate(QMacStylePrivate::Animates as, QWidget *w)
-{
-    if (as == AquaPushButton && defaultButton) {
-        QPushButton *tmp = defaultButton;
-        defaultButton = 0;
-        tmp->update();
-    } else if (as == AquaProgressBar) {
-        progressBars.removeAll(w);
-    }
-}
-
-void QMacStylePrivate::startAnimate(QMacStylePrivate::Animates as, QWidget *w)
-{
-    if (as == AquaPushButton)
-        defaultButton = static_cast<QPushButton *>(w);
-    else if (as == AquaProgressBar)
-        progressBars.append(w);
-    startAnimationTimer();
-}
-
-void QMacStylePrivate::startAnimationTimer()
-{
-    if ((defaultButton || !progressBars.isEmpty()) && timerID <= -1)
-        timerID = startTimer(animateSpeed(AquaListViewItemOpen));
-}
-
-bool QMacStylePrivate::addWidget(QWidget *w)
-{
-    //already knew of it
-    if (static_cast<QPushButton*>(w) == defaultButton
-            || progressBars.contains(static_cast<QProgressBar*>(w)))
-        return false;
-
-    if (QPushButton *btn = qobject_cast<QPushButton *>(w)) {
-        btn->installEventFilter(this);
-        if (btn->isDefault() || (btn->autoDefault() && btn->hasFocus()))
-            startAnimate(AquaPushButton, btn);
-        return true;
-    } else {
-        bool isProgressBar = (qobject_cast<QProgressBar *>(w));
-        if (isProgressBar) {
-            w->installEventFilter(this);
-            startAnimate(AquaProgressBar, w);
-            return true;
-        }
-    }
-    if (w->isWindow()) {
-        w->installEventFilter(this);
-        return true;
-    }
-    return false;
-}
-
-void QMacStylePrivate::removeWidget(QWidget *w)
-{
-    QPushButton *btn = qobject_cast<QPushButton *>(w);
-    if (btn && btn == defaultButton) {
-        stopAnimate(AquaPushButton, btn);
-    } else if (qobject_cast<QProgressBar *>(w)) {
-        stopAnimate(AquaProgressBar, w);
-    }
-}
-
-ThemeDrawState QMacStylePrivate::getDrawState(QStyle::State flags)
-{
-    ThemeDrawState tds = kThemeStateActive;
-    if (flags & QStyle::State_Sunken) {
-        tds = kThemeStatePressed;
-    } else if (flags & QStyle::State_Active) {
-        if (!(flags & QStyle::State_Enabled))
-            tds = kThemeStateUnavailable;
-    } else {
-        if (flags & QStyle::State_Enabled)
-            tds = kThemeStateInactive;
-        else
-            tds = kThemeStateUnavailableInactive;
-    }
-    return tds;
-}
-
-void QMacStylePrivate::timerEvent(QTimerEvent *)
-{
-    int animated = 0;
-    if (defaultButton && defaultButton->isEnabled() && defaultButton->window()->isActiveWindow()
-        && defaultButton->isVisibleTo(0) && (defaultButton->isDefault()
-        || (defaultButton->autoDefault() && defaultButton->hasFocus()))
-        && doAnimate(AquaPushButton)) {
-        ++animated;
-        defaultButton->update();
-    }
-    if (!progressBars.isEmpty()) {
-        int i = 0;
-        while (i < progressBars.size()) {
-            QWidget *maybeProgress = progressBars.at(i);
-            if (!maybeProgress) {
-                progressBars.removeAt(i);
-            } else {
-                if (QProgressBar *pb = qobject_cast<QProgressBar *>(maybeProgress)) {
-                    if (pb->maximum() == 0 || (pb->value() > 0 && pb->value() < pb->maximum())) {
-                        if (doAnimate(AquaProgressBar))
-                            pb->update();
-                    }
-                }
-                ++i;
-            }
-        }
-        if (i > 0) {
-            ++progressFrame;
-            animated += i;
-        }
-    }
-    if (animated <= 0) {
-        killTimer(timerID);
-        timerID = -1;
-    }
-}
-
-bool QMacStylePrivate::eventFilter(QObject *o, QEvent *e)
-{
-    //animate
-    if (QProgressBar *pb = qobject_cast<QProgressBar *>(o)) {
-        switch (e->type()) {
-        default:
-            break;
-        case QEvent::Show:
-            if (!progressBars.contains(pb))
-                startAnimate(AquaProgressBar, pb);
-            break;
-        case QEvent::Destroy:
-        case QEvent::Hide:
-            progressBars.removeAll(pb);
-        }
-    } else if (QPushButton *btn = qobject_cast<QPushButton *>(o)) {
-        switch (e->type()) {
-        default:
-            break;
-        case QEvent::FocusIn:
-            if (btn->autoDefault())
-                startAnimate(AquaPushButton, btn);
-            break;
-        case QEvent::Destroy:
-        case QEvent::Hide:
-            if (btn == defaultButton)
-                stopAnimate(AquaPushButton, btn);
-            break;
-        case QEvent::MouseButtonPress:
-            // It is very confusing to keep the button pulsing, so just stop the animation.
-            if (static_cast<QMouseEvent *>(e)->button() == Qt::LeftButton)
-                mouseDown = true;
-            stopAnimate(AquaPushButton, btn);
-            break;
-        case QEvent::MouseButtonRelease:
-            if (static_cast<QMouseEvent *>(e)->button() == Qt::LeftButton)
-                mouseDown = false;
-            // fall through
-        case QEvent::FocusOut:
-        case QEvent::Show:
-        case QEvent::WindowActivate: {
-            QList<QPushButton *> list = btn->window()->findChildren<QPushButton *>();
-            for (int i = 0; i < list.size(); ++i) {
-                QPushButton *pBtn = list.at(i);
-                if ((e->type() == QEvent::FocusOut
-                     && (pBtn->isDefault() || (pBtn->autoDefault() && pBtn->hasFocus()))
-                     && pBtn != btn)
-                    || ((e->type() == QEvent::Show || e->type() == QEvent::MouseButtonRelease
-                         || e->type() == QEvent::WindowActivate)
-                        && pBtn->isDefault())) {
-                    if (pBtn->window()->isActiveWindow()) {
-                        startAnimate(AquaPushButton, pBtn);
-                    }
-                    break;
-                }
-            }
-            break; }
-        }
-    }
-    return false;
-}
-
-bool QMacStylePrivate::doAnimate(QMacStylePrivate::Animates as)
-{
-    if (as == AquaPushButton) {
-    } else if (as == AquaProgressBar) {
-        // something for later...
-    } else if (as == AquaListViewItemOpen) {
-        // To be revived later...
-    }
-    return true;
-}
-
-void QMacStylePrivate::drawColorlessButton(const HIRect &macRect, HIThemeButtonDrawInfo *bdi,
-                                           QPainter *p, const QStyleOption *opt) const
-{
-    int xoff = 0,
-        yoff = 0,
-        extraWidth = 0,
-        extraHeight = 0,
-        finalyoff = 0;
-
-    const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt);
-    int width = int(macRect.size.width) + extraWidth;
-    int height = int(macRect.size.height) + extraHeight;
-
-    if (width <= 0 || height <= 0)
-        return;   // nothing to draw
-
-    QString key = QLatin1String("$qt_mac_style_ctb_") + QString::number(bdi->kind) + QLatin1Char('_')
-                  + QString::number(bdi->value) + QLatin1Char('_') + QString::number(width)
-                  + QLatin1Char('_') + QString::number(height);
-    QPixmap pm;
-    if (!QPixmapCache::find(key, pm)) {
-        QPixmap activePixmap(width, height);
-        activePixmap.fill(Qt::transparent);
-        {
-            if (combo){
-                // Carbon combos don't scale. Therefore we draw it
-                // ourselves, if a scaled version is needed.
-                QPainter tmpPainter(&activePixmap);
-                QMacStylePrivate::drawCombobox(macRect, *bdi, &tmpPainter);
-            }
-            else {
-                QMacCGContext cg(&activePixmap);
-                HIRect newRect = CGRectMake(xoff, yoff, macRect.size.width, macRect.size.height);
-                HIThemeDrawButton(&newRect, bdi, cg, kHIThemeOrientationNormal, 0);
-            }
-        }
-
-        if (!combo && bdi->value == kThemeButtonOff) {
-            pm = activePixmap;
-        } else if (combo) {
-            QImage image = activePixmap.toImage();
-
-            for (int y = 0; y < height; ++y) {
-                QRgb *scanLine = reinterpret_cast<QRgb *>(image.scanLine(y));
-
-                for (int x = 0; x < width; ++x) {
-                    QRgb &pixel = scanLine[x];
-
-                    int darkest = qRed(pixel);
-                    int mid = qGreen(pixel);
-                    int lightest = qBlue(pixel);
-
-                    if (darkest > mid)
-                        qSwap(darkest, mid);
-                    if (mid > lightest)
-                        qSwap(mid, lightest);
-                    if (darkest > mid)
-                        qSwap(darkest, mid);
-
-                    int gray = (mid + 2 * lightest) / 3;
-                    pixel = qRgba(gray, gray, gray, qAlpha(pixel));
-                }
-            }
-            pm = QPixmap::fromImage(image);
-        } else {
-            QImage activeImage = activePixmap.toImage();
-            QImage colorlessImage;
-            {
-                QPixmap colorlessPixmap(width, height);
-                colorlessPixmap.fill(Qt::transparent);
-
-                QMacCGContext cg(&colorlessPixmap);
-                HIRect newRect = CGRectMake(xoff, yoff, macRect.size.width, macRect.size.height);
-                int oldValue = bdi->value;
-                bdi->value = kThemeButtonOff;
-                HIThemeDrawButton(&newRect, bdi, cg, kHIThemeOrientationNormal, 0);
-                bdi->value = oldValue;
-                colorlessImage = colorlessPixmap.toImage();
-            }
-
-            for (int y = 0; y < height; ++y) {
-                QRgb *colorlessScanLine = reinterpret_cast<QRgb *>(colorlessImage.scanLine(y));
-                const QRgb *activeScanLine = reinterpret_cast<const QRgb *>(activeImage.scanLine(y));
-
-                for (int x = 0; x < width; ++x) {
-                    QRgb &colorlessPixel = colorlessScanLine[x];
-                    QRgb activePixel = activeScanLine[x];
-
-                    if (activePixel != colorlessPixel) {
-                        int max = qMax(qMax(qRed(activePixel), qGreen(activePixel)),
-                                       qBlue(activePixel));
-                        QRgb newPixel = qRgba(max, max, max, qAlpha(activePixel));
-                        if (qGray(newPixel) < qGray(colorlessPixel)
-                                || qAlpha(newPixel) > qAlpha(colorlessPixel))
-                            colorlessPixel = newPixel;
-                    }
-                }
-            }
-            pm = QPixmap::fromImage(colorlessImage);
-        }
-        QPixmapCache::insert(key, pm);
-    }
-    p->drawPixmap(int(macRect.origin.x), int(macRect.origin.y) + finalyoff, width, height, pm);
-}
-
-QMacStyle::QMacStyle()
-    : QWindowsStyle()
-{
-    d = new QMacStylePrivate(this);
-}
-
-QMacStyle::~QMacStyle()
-{
-    delete qt_mac_backgroundPattern;
-    qt_mac_backgroundPattern = 0;
-    delete d;
-}
-
-/*! \internal
-    Generates the standard widget background pattern.
-*/
-QPixmap QMacStylePrivate::generateBackgroundPattern() const
-{
-    QPixmap px(4, 4);
-    QMacCGContext cg(&px);
-    HIThemeSetFill(kThemeBrushDialogBackgroundActive, 0, cg, kHIThemeOrientationNormal);
-    const CGRect cgRect = CGRectMake(0, 0, px.width(), px.height());
-    CGContextFillRect(cg, cgRect);
-    return px;
-}
-
-/*! \internal
-    Fills the given \a rect with the pattern stored in \a brush. As an optimization,
-    HIThemeSetFill us used directly if we are filling with the standard background.
-*/
-void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush)
-{
-    QPoint dummy;
-    const QPaintDevice *target = painter->device();
-    const QPaintDevice *redirected = QPainter::redirected(target, &dummy);
-    const bool usePainter = redirected && redirected != target;
-
-    if (!usePainter && qt_mac_backgroundPattern
-        && qt_mac_backgroundPattern->cacheKey() == brush.texture().cacheKey()) {
-
-        painter->setClipRegion(rgn);
-
-        QCFType<CGContextRef> cg = qt_mac_cg_context(target);
-        CGContextSaveGState(cg);
-        HIThemeSetFill(kThemeBrushDialogBackgroundActive, 0, cg, kHIThemeOrientationInverted);
-
-        const QVector<QRect> &rects = rgn.rects();
-        for (int i = 0; i < rects.size(); ++i) {
-            const QRect rect(rects.at(i));
-            // Anchor the pattern to the top so it stays put when the window is resized.
-            CGContextSetPatternPhase(cg, CGSizeMake(rect.width(), rect.height()));
-            CGRect mac_rect = CGRectMake(rect.x(), rect.y(), rect.width(), rect.height());
-            CGContextFillRect(cg, mac_rect);
-        }
-
-        CGContextRestoreGState(cg);
-    } else {
-        const QRect rect(rgn.boundingRect());
-        painter->setClipRegion(rgn);
-        painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
-    }
-}
-
-void QMacStyle::polish(QPalette &pal)
-{
-    if (!qt_mac_backgroundPattern) {
-        if (!qApp)
-            return;
-        qt_mac_backgroundPattern = new QPixmap(d->generateBackgroundPattern());
-    }
-
-    QColor pc(Qt::black);
-    pc = qcolorForTheme(kThemeBrushDialogBackgroundActive);
-    QBrush background(pc, *qt_mac_backgroundPattern);
-    pal.setBrush(QPalette::All, QPalette::Window, background);
-    pal.setBrush(QPalette::All, QPalette::Button, background);
-
-    QCFString theme;
-    const OSErr err = CopyThemeIdentifier(&theme);
-    if (err == noErr && CFStringCompare(theme, kThemeAppearanceAquaGraphite, 0) == kCFCompareEqualTo) {
-        pal.setBrush(QPalette::All, QPalette::AlternateBase, QColor(240, 240, 240));
-    } else {
-        pal.setBrush(QPalette::All, QPalette::AlternateBase, QColor(237, 243, 254));
-    }
-}
-
-void QMacStyle::polish(QApplication *)
-{
-}
-
-void QMacStyle::unpolish(QApplication *)
-{
-}
-
-void QMacStyle::polish(QWidget* w)
-{
-    d->addWidget(w);
-    if (qt_mac_is_metal(w) && !w->testAttribute(Qt::WA_SetPalette)) {
-        // Set a clear brush so that the metal shines through.
-        QPalette pal = w->palette();
-        QBrush background(Qt::transparent);
-        pal.setBrush(QPalette::All, QPalette::Window, background);
-        pal.setBrush(QPalette::All, QPalette::Button, background);
-        w->setPalette(pal);
-        w->setAttribute(Qt::WA_SetPalette, false);
-    }
-
-    if (qobject_cast<QMenu*>(w) || qobject_cast<QComboBoxPrivateContainer *>(w)) {
-        w->setWindowOpacity(QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5 ? 0.985 : 0.94);
-        if (!w->testAttribute(Qt::WA_SetPalette)) {
-            QPixmap px(64, 64);
-            px.fill(Qt::white);
-            HIThemeMenuDrawInfo mtinfo;
-            mtinfo.version = qt_mac_hitheme_version;
-            mtinfo.menuType = kThemeMenuTypePopUp;
-            HIRect rect = CGRectMake(0, 0, px.width(), px.height());
-            HIThemeDrawMenuBackground(&rect, &mtinfo, QCFType<CGContextRef>(qt_mac_cg_context(&px)),
-                                      kHIThemeOrientationNormal);
-            QPalette pal = w->palette();
-            QBrush background(px);
-            pal.setBrush(QPalette::All, QPalette::Window, background);
-            pal.setBrush(QPalette::All, QPalette::Button, background);
-            w->setPalette(pal);
-            w->setAttribute(Qt::WA_SetPalette, false);
-        }
-    }
-
-    if (QTabBar *tb = qobject_cast<QTabBar*>(w)) {
-        if (tb->documentMode()) {
-            w->setAttribute(Qt::WA_Hover);
-            w->setFont(qt_app_fonts_hash()->value("QSmallFont", QFont()));
-            QPalette p = w->palette();
-            p.setColor(QPalette::WindowText, QColor(17, 17, 17));
-            w->setPalette(p);
-        }
-    }
-
-    QWindowsStyle::polish(w);
-
-    if (QRubberBand *rubber = qobject_cast<QRubberBand*>(w)) {
-        rubber->setWindowOpacity(0.25);
-        rubber->setAttribute(Qt::WA_PaintOnScreen, false);
-        rubber->setAttribute(Qt::WA_NoSystemBackground, false);
-    }
-}
-
-void QMacStyle::unpolish(QWidget* w)
-{
-    d->removeWidget(w);
-    if ((qobject_cast<QMenu*>(w) || qt_mac_is_metal(w)) && !w->testAttribute(Qt::WA_SetPalette)) {
-        QPalette pal = qApp->palette(w);
-        w->setPalette(pal);
-        w->setAttribute(Qt::WA_SetPalette, false);
-        w->setWindowOpacity(1.0);
-    }
-
-    if (QComboBox *combo = qobject_cast<QComboBox *>(w)) {
-        if (!combo->isEditable()) {
-            if (QWidget *widget = combo->findChild<QComboBoxPrivateContainer *>())
-                widget->setWindowOpacity(1.0);
-        }
-    }
-
-    if (QRubberBand *rubber = ::qobject_cast<QRubberBand*>(w)) {
-        rubber->setWindowOpacity(1.0);
-        rubber->setAttribute(Qt::WA_PaintOnScreen, true);
-        rubber->setAttribute(Qt::WA_NoSystemBackground, true);
-    }
-
-    if (QFocusFrame *frame = qobject_cast<QFocusFrame *>(w))
-        frame->setAttribute(Qt::WA_NoSystemBackground, true);
-
-    QWindowsStyle::unpolish(w);
-}
-
-int QMacStyle::pixelMetric(PixelMetric metric, const QStyleOption *opt, const QWidget *widget) const
-{
-    int controlSize = getControlSize(opt, widget);
-    SInt32 ret = 0;
-
-    switch (metric) {
-    case PM_TabCloseIndicatorWidth:
-    case PM_TabCloseIndicatorHeight:
-        ret = closeButtonSize;
-        break;
-    case PM_ToolBarIconSize:
-        ret = proxy()->pixelMetric(PM_LargeIconSize);
-        break;
-    case PM_FocusFrameVMargin:
-    case PM_FocusFrameHMargin:
-        GetThemeMetric(kThemeMetricFocusRectOutset, &ret);
-        break;
-    case PM_DialogButtonsSeparator:
-        ret = -5;
-        break;
-    case PM_DialogButtonsButtonHeight: {
-        QSize sz;
-        ret = d->aquaSizeConstrain(opt, 0, QStyle::CT_PushButton, QSize(-1, -1), &sz);
-        if (sz == QSize(-1, -1))
-            ret = 32;
-        else
-            ret = sz.height();
-        break; }
-    case PM_DialogButtonsButtonWidth: {
-        QSize sz;
-        ret = d->aquaSizeConstrain(opt, 0, QStyle::CT_PushButton, QSize(-1, -1), &sz);
-        if (sz == QSize(-1, -1))
-            ret = 70;
-        else
-            ret = sz.width();
-        break; }
-
-    case PM_MenuBarHMargin:
-        ret = 8;
-        break;
-
-    case PM_MenuBarVMargin:
-        ret = 0;
-        break;
-
-    case QStyle::PM_MenuDesktopFrameWidth:
-        ret = 5;
-        break;
-
-    case PM_CheckBoxLabelSpacing:
-    case PM_RadioButtonLabelSpacing:
-        ret = 2;
-        break;
-    case PM_MenuScrollerHeight:
-#if 0
-        SInt16 ash, asw;
-        GetThemeMenuItemExtra(kThemeMenuItemScrollUpArrow, &ash, &asw);
-        ret = ash;
-#else
-        ret = 15; // I hate having magic numbers in here...
-#endif
-        break;
-    case PM_DefaultFrameWidth:
-#ifndef QT_NO_MAINWINDOW
-        if (widget && (widget->isWindow() || !widget->parentWidget()
-                || (qobject_cast<const QMainWindow*>(widget->parentWidget())
-                   && static_cast<QMainWindow *>(widget->parentWidget())->centralWidget() == widget))
-                && (qobject_cast<const QAbstractScrollArea *>(widget)
-                    || widget->inherits("QWorkspaceChild")))
-            ret = 0;
-        else
-#endif
-        // The combo box popup has no frame.
-        if (qstyleoption_cast<const QStyleOptionComboBox *>(opt) != 0)
-            ret = 0;
-        // Frame of mac style line edits is two pixels on top and one on the bottom
-        else if (qobject_cast<const QLineEdit *>(widget) != 0)
-            ret = 2;
-        else
-            ret = 1;
-        break;
-    case PM_MaximumDragDistance:
-        ret = -1;
-        break;
-    case PM_ScrollBarSliderMin:
-        ret = 24;
-        break;
-    case PM_SpinBoxFrameWidth:
-        GetThemeMetric(kThemeMetricEditTextFrameOutset, &ret);
-        switch (d->aquaSizeConstrain(opt, widget)) {
-        default:
-            ret += 2;
-            break;
-        case QAquaSizeMini:
-            ret += 1;
-            break;
-        }
-        break;
-    case PM_ButtonShiftHorizontal:
-    case PM_ButtonShiftVertical:
-        ret = 0;
-        break;
-    case PM_SliderLength:
-        ret = 17;
-        break;
-    case PM_ButtonDefaultIndicator:
-        ret = 0;
-        break;
-    case PM_TitleBarHeight:
-        if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
-            HIThemeWindowDrawInfo wdi;
-            wdi.version = qt_mac_hitheme_version;
-            wdi.state = kThemeStateActive;
-            wdi.windowType = QtWinType;
-            if (tb->titleBarState)
-                wdi.attributes = kThemeWindowHasFullZoom | kThemeWindowHasCloseBox
-                                  | kThemeWindowHasCollapseBox;
-            else if (tb->titleBarFlags & Qt::WindowSystemMenuHint)
-                wdi.attributes = kThemeWindowHasCloseBox;
-            else
-                wdi.attributes = 0;
-            wdi.titleHeight = tb->rect.height();
-            wdi.titleWidth = tb->rect.width();
-            QCFType<HIShapeRef> region;
-            HIRect hirect = qt_hirectForQRect(tb->rect);
-            if (hirect.size.width <= 0)
-                hirect.size.width = 100;
-            if (hirect.size.height <= 0)
-                hirect.size.height = 30;
-
-            HIThemeGetWindowShape(&hirect, &wdi, kWindowTitleBarRgn, &region);
-            HIRect rect;
-            ptrHIShapeGetBounds(region, &rect);
-            ret = int(rect.size.height);
-            ret += 4;
-        }
-        break;
-    case PM_TabBarTabVSpace:
-        ret = 4;
-        break;
-    case PM_TabBarTabShiftHorizontal:
-    case PM_TabBarTabShiftVertical:
-        ret = 0;
-        break;
-    case PM_TabBarBaseHeight:
-        ret = 0;
-        break;
-    case PM_TabBarTabOverlap:
-        ret = 0;
-        break;
-    case PM_TabBarBaseOverlap:
-        switch (d->aquaSizeConstrain(opt, widget)) {
-        case QAquaSizeUnknown:
-        case QAquaSizeLarge:
-            ret = 11;
-            break;
-        case QAquaSizeSmall:
-            ret = 8;
-            break;
-        case QAquaSizeMini:
-            ret = 7;
-            break;
-        }
-        break;
-    case PM_ScrollBarExtent: {
-        switch (d->aquaSizeConstrain(opt, widget)) {
-        case QAquaSizeUnknown:
-        case QAquaSizeLarge:
-            GetThemeMetric(kThemeMetricScrollBarWidth, &ret);
-            break;
-        case QAquaSizeMini:
-        case QAquaSizeSmall:
-            GetThemeMetric(kThemeMetricSmallScrollBarWidth, &ret);
-            break;
-        }
-        break; }
-    case PM_IndicatorHeight: {
-        switch (d->aquaSizeConstrain(opt, widget)) {
-        case QAquaSizeUnknown:
-        case QAquaSizeLarge:
-            GetThemeMetric(kThemeMetricCheckBoxHeight, &ret);
-            break;
-        case QAquaSizeMini:
-            GetThemeMetric(kThemeMetricMiniCheckBoxHeight, &ret);
-            break;
-        case QAquaSizeSmall:
-            GetThemeMetric(kThemeMetricSmallCheckBoxHeight, &ret);
-            break;
-        }
-        break; }
-    case PM_IndicatorWidth: {
-        switch (d->aquaSizeConstrain(opt, widget)) {
-        case QAquaSizeUnknown:
-        case QAquaSizeLarge:
-            GetThemeMetric(kThemeMetricCheckBoxWidth, &ret);
-            break;
-        case QAquaSizeMini:
-            GetThemeMetric(kThemeMetricMiniCheckBoxWidth, &ret);
-            break;
-        case QAquaSizeSmall:
-            GetThemeMetric(kThemeMetricSmallCheckBoxWidth, &ret);
-            break;
-        }
-        ++ret;
-        break; }
-    case PM_ExclusiveIndicatorHeight: {
-        switch (d->aquaSizeConstrain(opt, widget)) {
-        case QAquaSizeUnknown:
-        case QAquaSizeLarge:
-            GetThemeMetric(kThemeMetricRadioButtonHeight, &ret);
-            break;
-        case QAquaSizeMini:
-            GetThemeMetric(kThemeMetricMiniRadioButtonHeight, &ret);
-            break;
-        case QAquaSizeSmall:
-            GetThemeMetric(kThemeMetricSmallRadioButtonHeight, &ret);
-            break;
-        }
-        break; }
-    case PM_ExclusiveIndicatorWidth: {
-        switch (d->aquaSizeConstrain(opt, widget)) {
-        case QAquaSizeUnknown:
-        case QAquaSizeLarge:
-            GetThemeMetric(kThemeMetricRadioButtonWidth, &ret);
-            break;
-        case QAquaSizeMini:
-            GetThemeMetric(kThemeMetricMiniRadioButtonWidth, &ret);
-            break;
-        case QAquaSizeSmall:
-            GetThemeMetric(kThemeMetricSmallRadioButtonWidth, &ret);
-            break;
-        }
-        ++ret;
-        break; }
-    case PM_MenuVMargin:
-        ret = 4;
-        break;
-    case PM_MenuPanelWidth:
-        ret = 0;
-        break;
-    case PM_ToolTipLabelFrameWidth:
-        ret = 0;
-        break;
-    case PM_SizeGripSize: {
-        QAquaWidgetSize aSize;
-        if (widget && widget->window()->windowType() == Qt::Tool)
-            aSize = QAquaSizeSmall;
-        else
-            aSize = QAquaSizeLarge;
-        const QSize size = qt_aqua_get_known_size(CT_SizeGrip, widget, QSize(), aSize);
-        ret = size.width();
-        break; }
-    case PM_MdiSubWindowFrameWidth:
-        ret = 1;
-        break;
-    case PM_DockWidgetFrameWidth:
-        ret = 2;
-        break;
-    case PM_DockWidgetTitleMargin:
-        ret = 0;
-        break;
-    case PM_DockWidgetSeparatorExtent:
-        ret = 1;
-        break;
-    case PM_ToolBarHandleExtent:
-        ret = 11;
-        break;
-    case PM_ToolBarItemMargin:
-        ret = 0;
-        break;
-    case PM_ToolBarItemSpacing:
-        ret = 4;
-        break;
-    case PM_SplitterWidth:
-        ret = qMax(7, QApplication::globalStrut().width());
-        break;
-    case PM_LayoutLeftMargin:
-    case PM_LayoutTopMargin:
-    case PM_LayoutRightMargin:
-    case PM_LayoutBottomMargin:
-        {
-            bool isWindow = false;
-            if (opt) {
-                isWindow = (opt->state & State_Window);
-            } else if (widget) {
-                isWindow = widget->isWindow();
-            }
-
-            if (isWindow) {
-                bool isMetal = widget && widget->testAttribute(Qt::WA_MacBrushedMetal);
-                if (isMetal) {
-                    if (metric == PM_LayoutTopMargin) {
-                        return_SIZE(9 /* AHIG */, 6 /* guess */, 6 /* guess */);
-                    } else if (metric == PM_LayoutBottomMargin) {
-                        return_SIZE(18 /* AHIG */, 15 /* guess */, 13 /* guess */);
-                    } else {
-                        return_SIZE(14 /* AHIG */, 11 /* guess */, 9 /* guess */);
-                    }
-                } else {
-                    /*
-                        AHIG would have (20, 8, 10) here but that makes
-                        no sense. It would also have 14 for the top margin
-                        but this contradicts both Builder and most
-                        applications.
-                    */
-                    return_SIZE(20, 10, 10);    // AHIG
-                }
-            } else {
-                // hack to detect QTabWidget
-                if (widget && widget->parentWidget()
-                        && widget->parentWidget()->sizePolicy().controlType() == QSizePolicy::TabWidget) {
-                    if (metric == PM_LayoutTopMargin) {
-                        /*
-                            Builder would have 14 (= 20 - 6) instead of 12,
-                            but that makes the tab look disproportionate.
-                        */
-                        return_SIZE(12, 6, 6);  // guess
-                    } else {
-                        return_SIZE(20 /* Builder */, 8 /* guess */, 8 /* guess */);
-                    }
-                } else {
-                    /*
-                        Child margins are highly inconsistent in AHIG and Builder.
-                    */
-                    return_SIZE(12, 8, 6);    // guess
-                }
-            }
-        }
-    case PM_LayoutHorizontalSpacing:
-    case PM_LayoutVerticalSpacing:
-        return -1;
-    case QStyle::PM_TabBarTabHSpace:
-        switch (d->aquaSizeConstrain(opt, widget)) {
-        case QAquaSizeLarge:
-        case QAquaSizeUnknown:
-            ret = QWindowsStyle::pixelMetric(metric, opt, widget);
-            break;
-        case QAquaSizeSmall:
-            ret = 20;
-            break;
-        case QAquaSizeMini:
-            ret = 16;
-            break;
-        }
-        break;
-    case PM_MenuHMargin:
-        ret = 0;
-        break;
-    case PM_ToolBarFrameWidth:
-        ret = 1;
-        if (widget) {
-            if (QMainWindow * mainWindow = qobject_cast<QMainWindow *>(widget->parent()))
-                if (mainWindow->unifiedTitleAndToolBarOnMac())
-                    ret = 0;
-        }
-        break;
-    default:
-        ret = QWindowsStyle::pixelMetric(metric, opt, widget);
-        break;
-    }
-    return ret;
-}
-
-QPalette QMacStyle::standardPalette() const
-{
-    QPalette pal = QWindowsStyle::standardPalette();
-    pal.setColor(QPalette::Disabled, QPalette::Dark, QColor(191, 191, 191));
-    pal.setColor(QPalette::Active, QPalette::Dark, QColor(191, 191, 191));
-    pal.setColor(QPalette::Inactive, QPalette::Dark, QColor(191, 191, 191));
-    return pal;
-}
-
-int QMacStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w,
-                         QStyleHintReturn *hret) const
-{
-    SInt32 ret = 0;
-    switch (sh) {
-    case SH_Menu_SelectionWrap:
-        ret = false;
-        break;
-    case SH_Menu_KeyboardSearch:
-        ret = true;
-        break;
-    case SH_Menu_SpaceActivatesItem:
-        ret = true;
-        break;
-    case SH_Slider_AbsoluteSetButtons:
-        ret = Qt::LeftButton|Qt::MidButton;
-        break;
-    case SH_Slider_PageSetButtons:
-        ret = 0;
-        break;
-    case SH_ScrollBar_ContextMenu:
-        ret = false;
-        break;
-    case SH_TitleBar_AutoRaise:
-        ret = true;
-        break;
-    case SH_Menu_AllowActiveAndDisabled:
-        ret = false;
-        break;
-    case SH_Menu_SubMenuPopupDelay:
-        ret = 100;
-        break;
-    case SH_ScrollBar_LeftClickAbsolutePosition: {
-        extern bool qt_scrollbar_jump_to_pos; //qapplication_mac.cpp
-        if(QApplication::keyboardModifiers() & Qt::AltModifier)
-            ret = !qt_scrollbar_jump_to_pos;
-        else
-            ret = qt_scrollbar_jump_to_pos;
-        break; }
-    case SH_TabBar_PreferNoArrows:
-        ret = true;
-        break;
-    case SH_LineEdit_PasswordCharacter:
-        ret = kBulletUnicode;
-        break;
-        /*
-    case SH_DialogButtons_DefaultButton:
-        ret = QDialogButtons::Reject;
-        break;
-        */
-    case SH_GroupBox_TextLabelVerticalAlignment:
-        ret = Qt::AlignTop;
-        break;
-    case SH_ScrollView_FrameOnlyAroundContents:
-        if (w && (w->isWindow() || !w->parentWidget() || w->parentWidget()->isWindow())
-                && (w->inherits("QWorkspaceChild")))
-            ret = true;
-        else
-            ret = QWindowsStyle::styleHint(sh, opt, w, hret);
-        break;
-    case SH_Menu_FillScreenWithScroll:
-        ret = false;
-        break;
-    case SH_Menu_Scrollable:
-        ret = true;
-        break;
-    case SH_RichText_FullWidthSelection:
-        ret = true;
-        break;
-    case SH_BlinkCursorWhenTextSelected:
-        ret = false;
-        break;
-    case SH_ScrollBar_StopMouseOverSlider:
-        ret = true;
-        break;
-    case SH_ListViewExpand_SelectMouseType:
-        ret = QEvent::MouseButtonRelease;
-        break;
-    case SH_TabBar_SelectMouseType:
-        if (const QStyleOptionTabBarBaseV2 *opt2 = qstyleoption_cast<const QStyleOptionTabBarBaseV2 *>(opt)) {
-            ret = opt2->documentMode ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease;
-        } else {
-            ret = QEvent::MouseButtonRelease;
-        }
-        break;
-    case SH_ComboBox_Popup:
-        if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt))
-            ret = !cmb->editable;
-        else
-            ret = 0;
-        break;
-    case SH_Workspace_FillSpaceOnMaximize:
-        ret = true;
-        break;
-    case SH_Widget_ShareActivation:
-        ret = true;
-        break;
-    case SH_Header_ArrowAlignment:
-        ret = Qt::AlignRight;
-        break;
-    case SH_TabBar_Alignment: {
-        if (const QTabWidget *tab = qobject_cast<const QTabWidget*>(w)) {
-            if (tab->documentMode()) {
-                ret = Qt::AlignLeft;
-                break;
-            }
-        }
-        if (const QTabBar *tab = qobject_cast<const QTabBar*>(w)) {
-            if (tab->documentMode()) {
-                ret = Qt::AlignLeft;
-                break;
-            }
-        }
-        ret = Qt::AlignCenter;
-        } break;
-    case SH_UnderlineShortcut:
-        ret = false;
-        break;
-    case SH_ToolTipLabel_Opacity:
-        ret = 242; // About 95%
-        break;
-    case SH_Button_FocusPolicy:
-        ret = Qt::TabFocus;
-        break;
-    case SH_EtchDisabledText:
-        ret = false;
-        break;
-    case SH_FocusFrame_Mask: {
-        ret = true;
-        if(QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
-            const uchar fillR = 192, fillG = 191, fillB = 190;
-            QImage img;
-
-            QSize pixmapSize = opt->rect.size();
-            if (pixmapSize.isValid()) {
-                QPixmap pix(pixmapSize);
-                pix.fill(QColor(fillR, fillG, fillB));
-                QPainter pix_paint(&pix);
-                proxy()->drawControl(CE_FocusFrame, opt, &pix_paint, w);
-                pix_paint.end();
-                img = pix.toImage();
-            }
-
-            const QRgb *sptr = (QRgb*)img.bits(), *srow;
-            const int sbpl = img.bytesPerLine();
-            const int w = sbpl/4, h = img.height();
-
-            QImage img_mask(img.width(), img.height(), QImage::Format_ARGB32);
-            QRgb *dptr = (QRgb*)img_mask.bits(), *drow;
-            const int dbpl = img_mask.bytesPerLine();
-
-            for (int y = 0; y < h; ++y) {
-                srow = sptr+((y*sbpl)/4);
-                drow = dptr+((y*dbpl)/4);
-                for (int x = 0; x < w; ++x) {
-                    const int diff = (((qRed(*srow)-fillR)*(qRed(*srow)-fillR)) +
-                                      ((qGreen(*srow)-fillG)*((qGreen(*srow)-fillG))) +
-                                      ((qBlue(*srow)-fillB)*((qBlue(*srow)-fillB))));
-                    (*drow++) = (diff < 100) ? 0xffffffff : 0xff000000;
-                    ++srow;
-                }
-            }
-            QBitmap qmask = QBitmap::fromImage(img_mask);
-            mask->region = QRegion(qmask);
-        }
-        break; }
-    case SH_TitleBar_NoBorder:
-        ret = 1;
-        break;
-    case SH_RubberBand_Mask:
-        ret = 0;
-        break;
-    case SH_ComboBox_LayoutDirection:
-        ret = Qt::LeftToRight;
-        break;
-    case SH_ItemView_EllipsisLocation:
-        ret = Qt::AlignHCenter;
-        break;
-    case SH_ItemView_ShowDecorationSelected:
-        ret = true;
-        break;
-    case SH_TitleBar_ModifyNotification:
-        ret = false;
-        break;
-    case SH_ScrollBar_RollBetweenButtons:
-        ret = true;
-        break;
-    case SH_WindowFrame_Mask:
-        ret = 1;
-        if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask *>(hret)) {
-            mask->region = opt->rect;
-            mask->region -= QRect(opt->rect.left(), opt->rect.top(), 5, 1);
-            mask->region -= QRect(opt->rect.left(), opt->rect.top() + 1, 3, 1);
-            mask->region -= QRect(opt->rect.left(), opt->rect.top() + 2, 2, 1);
-            mask->region -= QRect(opt->rect.left(), opt->rect.top() + 3, 1, 2);
-
-            mask->region -= QRect(opt->rect.right() - 4, opt->rect.top(), 5, 1);
-            mask->region -= QRect(opt->rect.right() - 2, opt->rect.top() + 1, 3, 1);
-            mask->region -= QRect(opt->rect.right() - 1, opt->rect.top() + 2, 2, 1);
-            mask->region -= QRect(opt->rect.right() , opt->rect.top() + 3, 1, 2);
-        }
-        break;
-    case SH_TabBar_ElideMode:
-        ret = Qt::ElideRight;
-        break;
-    case SH_DialogButtonLayout:
-        ret = QDialogButtonBox::MacLayout;
-        break;
-    case SH_FormLayoutWrapPolicy:
-        ret = QFormLayout::DontWrapRows;
-        break;
-    case SH_FormLayoutFieldGrowthPolicy:
-        ret = QFormLayout::FieldsStayAtSizeHint;
-        break;
-    case SH_FormLayoutFormAlignment:
-        ret = Qt::AlignHCenter | Qt::AlignTop;
-        break;
-    case SH_FormLayoutLabelAlignment:
-        ret = Qt::AlignRight;
-        break;
-    case SH_ComboBox_PopupFrameStyle:
-        ret = QFrame::NoFrame | QFrame::Plain;
-        break;
-    case SH_MessageBox_TextInteractionFlags:
-        ret = Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse | Qt::TextSelectableByKeyboard;
-        break;
-    case SH_SpellCheckUnderlineStyle:
-        ret = QTextCharFormat::DashUnderline;
-        break;
-    case SH_MessageBox_CenterButtons:
-        ret = false;
-        break;
-    case SH_MenuBar_AltKeyNavigation:
-        ret = false;
-        break;
-    case SH_ItemView_MovementWithoutUpdatingSelection:
-        ret = false;
-        break;
-    case SH_FocusFrame_AboveWidget:
-        ret = true;
-        break;
-    case SH_WizardStyle:
-        ret = QWizard::MacStyle;
-        break;
-    case SH_ItemView_ArrowKeysNavigateIntoChildren:
-        ret = false;
-        break;
-    case SH_Menu_FlashTriggeredItem:
-        ret = true;
-        break;
-    case SH_Menu_FadeOutOnHide:
-        ret = true;
-        break;
-    case SH_Menu_Mask:
-        if (opt) {
-            if (QStyleHintReturnMask *mask = qstyleoption_cast<QStyleHintReturnMask*>(hret)) {
-                ret = true;
-                HIRect menuRect = CGRectMake(opt->rect.x(), opt->rect.y() + 4,
-                                             opt->rect.width(), opt->rect.height() - 8);
-                HIThemeMenuDrawInfo mdi;
-                mdi.version = 0;
-                if (w && qobject_cast<QMenu *>(w->parentWidget()))
-                    mdi.menuType = kThemeMenuTypeHierarchical;
-                else
-                    mdi.menuType = kThemeMenuTypePopUp;
-                QCFType<HIShapeRef> shape;
-                HIThemeGetMenuBackgroundShape(&menuRect, &mdi, &shape);
-                mask->region = QRegion::fromHIShapeRef(shape);
-            }
-        }
-        break;
-    case SH_ItemView_PaintAlternatingRowColorsForEmptyArea:
-        ret = true;
-        break;
-    case SH_TabBar_CloseButtonPosition:
-        ret = QTabBar::LeftSide;
-        break;
-    case SH_DockWidget_ButtonsHaveFrame:
-        ret = false;
-        break;
-    default:
-        ret = QWindowsStyle::styleHint(sh, opt, w, hret);
-        break;
-    }
-    return ret;
-}
-
-QPixmap QMacStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap,
-                                       const QStyleOption *opt) const
-{
-    switch (iconMode) {
-    case QIcon::Disabled: {
-        QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
-        int imgh = img.height();
-        int imgw = img.width();
-        QRgb pixel;
-        for (int y = 0; y < imgh; ++y) {
-            for (int x = 0; x < imgw; ++x) {
-                pixel = img.pixel(x, y);
-                img.setPixel(x, y, qRgba(qRed(pixel), qGreen(pixel), qBlue(pixel),
-                                         qAlpha(pixel) / 2));
-            }
-        }
-        return QPixmap::fromImage(img);
-    }
-    default:
-        ;
-    }
-    return QWindowsStyle::generatedIconPixmap(iconMode, pixmap, opt);
-}
-
-
-QPixmap QMacStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
-                                  const QWidget *widget) const
-{
-    // The default implementation of QStyle::standardIconImplementation() is to call standardPixmap()
-    // I don't want infinite recursion so if we do get in that situation, just return the Window's
-    // standard pixmap instead (since there is no mac-specific icon then). This should be fine until
-    // someone changes how Windows standard
-    // pixmap works.
-    static bool recursionGuard = false;
-
-    if (recursionGuard)
-        return QWindowsStyle::standardPixmap(standardPixmap, opt, widget);
-
-    recursionGuard = true;
-    QIcon icon = standardIconImplementation(standardPixmap, opt, widget);
-    recursionGuard = false;
-    int size;
-    switch (standardPixmap) {
-        default:
-            size = 32;
-            break;
-        case SP_MessageBoxCritical:
-        case SP_MessageBoxQuestion:
-        case SP_MessageBoxInformation:
-        case SP_MessageBoxWarning:
-            size = 64;
-            break;
-    }
-    return icon.pixmap(size, size);
-}
-
-void QMacStyle::setFocusRectPolicy(QWidget *w, FocusRectPolicy policy)
-{
-    switch (policy) {
-    case FocusDefault:
-        break;
-    case FocusEnabled:
-    case FocusDisabled:
-        w->setAttribute(Qt::WA_MacShowFocusRect, policy == FocusEnabled);
-        break;
-    }
-}
-
-QMacStyle::FocusRectPolicy QMacStyle::focusRectPolicy(const QWidget *w)
-{
-    return w->testAttribute(Qt::WA_MacShowFocusRect) ? FocusEnabled : FocusDisabled;
-}
-
-void QMacStyle::setWidgetSizePolicy(const QWidget *widget, WidgetSizePolicy policy)
-{
-    QWidget *wadget = const_cast<QWidget *>(widget);
-    wadget->setAttribute(Qt::WA_MacNormalSize, policy == SizeLarge);
-    wadget->setAttribute(Qt::WA_MacSmallSize, policy == SizeSmall);
-    wadget->setAttribute(Qt::WA_MacMiniSize, policy == SizeMini);
-}
-
-QMacStyle::WidgetSizePolicy QMacStyle::widgetSizePolicy(const QWidget *widget)
-{
-    while (widget) {
-        if (widget->testAttribute(Qt::WA_MacMiniSize)) {
-            return SizeMini;
-        } else if (widget->testAttribute(Qt::WA_MacSmallSize)) {
-            return SizeSmall;
-        } else if (widget->testAttribute(Qt::WA_MacNormalSize)) {
-            return SizeLarge;
-        }
-        widget = widget->parentWidget();
-    }
-    return SizeDefault;
-}
-
-void QMacStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
-                              const QWidget *w) const
-{
-    ThemeDrawState tds = d->getDrawState(opt->state);
-    QMacCGContext cg(p);
-    switch (pe) {
-    case PE_IndicatorArrowUp:
-    case PE_IndicatorArrowDown:
-    case PE_IndicatorArrowRight:
-    case PE_IndicatorArrowLeft: {
-        p->save();
-        int xOffset = opt->direction == Qt::LeftToRight ? 2 : -1;
-        QMatrix matrix;
-        matrix.translate(opt->rect.center().x() + xOffset, opt->rect.center().y() + 2);
-        QPainterPath path;
-        switch(pe) {
-        default:
-        case PE_IndicatorArrowDown:
-            break;
-        case PE_IndicatorArrowUp:
-            matrix.rotate(180);
-            break;
-        case PE_IndicatorArrowLeft:
-            matrix.rotate(90);
-            break;
-        case PE_IndicatorArrowRight:
-            matrix.rotate(-90);
-            break;
-        }
-        path.moveTo(0, 5);
-        path.lineTo(-4, -3);
-        path.lineTo(4, -3);
-        p->setMatrix(matrix);
-        p->setPen(Qt::NoPen);
-        p->setBrush(QColor(0, 0, 0, 135));
-        p->drawPath(path);
-        p->restore();
-        break; }
-    case PE_FrameTabBarBase:
-        if (const QStyleOptionTabBarBaseV2 *tbb
-                = qstyleoption_cast<const QStyleOptionTabBarBaseV2 *>(opt)) {
-            if (tbb->documentMode) {
-                p->save();
-                drawTabBase(p, tbb, w);
-                p->restore();
-                return;
-            }
-
-            QRegion region(tbb->rect);
-            region -= tbb->tabBarRect;
-            p->save();
-            p->setClipRegion(region);
-            QStyleOptionTabWidgetFrame twf;
-            twf.QStyleOption::operator=(*tbb);
-            twf.shape  = tbb->shape;
-            switch (getTabDirection(twf.shape)) {
-            case kThemeTabNorth:
-                twf.rect = twf.rect.adjusted(0, 0, 0, 10);
-                break;
-            case kThemeTabSouth:
-                twf.rect = twf.rect.adjusted(0, -10, 0, 0);
-                break;
-            case kThemeTabWest:
-                twf.rect = twf.rect.adjusted(0, 0, 10, 0);
-                break;
-            case kThemeTabEast:
-                twf.rect = twf.rect.adjusted(0, -10, 0, 0);
-                break;
-            }
-            proxy()->drawPrimitive(PE_FrameTabWidget, &twf, p, w);
-            p->restore();
-        }
-        break;
-    case PE_PanelTipLabel:
-        p->fillRect(opt->rect, opt->palette.brush(QPalette::ToolTipBase));
-        break;
-    case PE_FrameGroupBox:
-        if (const QStyleOptionFrame *groupBox = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
-            const QStyleOptionFrameV2 *frame2 = qstyleoption_cast<const QStyleOptionFrameV2 *>(opt);
-            if (frame2 && frame2->features & QStyleOptionFrameV2::Flat) {
-                QWindowsStyle::drawPrimitive(pe, groupBox, p, w);
-            } else {
-                HIThemeGroupBoxDrawInfo gdi;
-                gdi.version = qt_mac_hitheme_version;
-                gdi.state = tds;
-                if (w && qobject_cast<QGroupBox *>(w->parentWidget()))
-                    gdi.kind = kHIThemeGroupBoxKindSecondary;
-                else
-                    gdi.kind = kHIThemeGroupBoxKindPrimary;
-                HIRect hirect = qt_hirectForQRect(opt->rect);
-                HIThemeDrawGroupBox(&hirect, &gdi, cg, kHIThemeOrientationNormal);
-            }
-        }
-        break;
-    case PE_IndicatorToolBarSeparator: {
-            QPainterPath path;
-            if (opt->state & State_Horizontal) {
-                int xpoint = opt->rect.center().x();
-                path.moveTo(xpoint + 0.5, opt->rect.top() + 1);
-                path.lineTo(xpoint + 0.5, opt->rect.bottom());
-            } else {
-                int ypoint = opt->rect.center().y();
-                path.moveTo(opt->rect.left() + 2 , ypoint + 0.5);
-                path.lineTo(opt->rect.right() + 1, ypoint + 0.5);
-            }
-            QPainterPathStroker theStroker;
-            theStroker.setCapStyle(Qt::FlatCap);
-            theStroker.setDashPattern(QVector<qreal>() << 1 << 2);
-            path = theStroker.createStroke(path);
-            p->fillPath(path, QColor(0, 0, 0, 119));
-        }
-        break;
-    case PE_FrameWindow:
-        break;
-    case PE_IndicatorDockWidgetResizeHandle: {
-            // The docwidget resize handle is drawn as a one-pixel wide line.
-            p->save();
-            if (opt->state & State_Horizontal) {
-                p->setPen(QColor(160, 160, 160));
-                p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
-            } else {
-                p->setPen(QColor(145, 145, 145));
-                p->drawLine(opt->rect.topRight(), opt->rect.bottomRight());
-            }
-            p->restore();
-        } break;
-    case PE_IndicatorToolBarHandle: {
-            p->save();
-            QPainterPath path;
-            int x = opt->rect.x() + 6;
-            int y = opt->rect.y() + 5;
-            static const int RectHeight = 2;
-            if (opt->state & State_Horizontal) {
-                while (y < opt->rect.height() - RectHeight - 6) {
-                    path.moveTo(x, y);
-                    path.addRect(x, y, RectHeight, RectHeight);
-                    y += 6;
-                }
-            } else {
-                while (x < opt->rect.width() - RectHeight - 6) {
-                    path.moveTo(x, y);
-                    path.addRect(x, y, RectHeight, RectHeight);
-                    x += 6;
-                }
-            }
-            p->setPen(Qt::NoPen);
-            QColor dark = opt->palette.dark().color();
-            dark.setAlphaF(0.75);
-            QColor light = opt->palette.light().color();
-            light.setAlphaF(0.6);
-            p->fillPath(path, light);
-            p->save();
-            p->translate(1, 1);
-            p->fillPath(path, dark);
-            p->restore();
-            p->translate(3, 3);
-            p->fillPath(path, light);
-            p->translate(1, 1);
-            p->fillPath(path, dark);
-            p->restore();
-
-            break;
-        }
-    case PE_IndicatorHeaderArrow:
-        if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
-            // In HITheme, up is down, down is up and hamburgers eat people.
-            if (header->sortIndicator != QStyleOptionHeader::None)
-                proxy()->drawPrimitive(
-                    (header->sortIndicator == QStyleOptionHeader::SortDown) ?
-                    PE_IndicatorArrowUp : PE_IndicatorArrowDown, header, p, w);
-        }
-        break;
-    case PE_IndicatorMenuCheckMark: {
-        const int checkw = 8;
-        const int checkh = 8;
-        const int xoff = qMax(0, (opt->rect.width() - checkw) / 2);
-        const int yoff = qMax(0, (opt->rect.width() - checkh) / 2);
-        const int x1 = xoff + opt->rect.x();
-        const int y1 = yoff + opt->rect.y() + checkw/2;
-        const int x2 = xoff + opt->rect.x() + checkw/4;
-        const int y2 = yoff + opt->rect.y() + checkh;
-        const int x3 = xoff + opt->rect.x() + checkw;
-        const int y3 = yoff + opt->rect.y();
-
-        QVector<QLineF> a(2);
-        a << QLineF(x1, y1, x2, y2);
-        a << QLineF(x2, y2, x3, y3);
-        if (opt->palette.currentColorGroup() == QPalette::Active) {
-            if (opt->state & State_On)
-                p->setPen(QPen(opt->palette.highlightedText().color(), 3));
-            else
-                p->setPen(QPen(opt->palette.text().color(), 3));
-        } else {
-            p->setPen(QPen(QColor(100, 100, 100), 3));
-        }
-        p->save();
-        p->drawLines(a);
-        p->restore();
-        break; }
-    case PE_IndicatorViewItemCheck:
-    case PE_IndicatorRadioButton:
-    case PE_IndicatorCheckBox: {
-        bool drawColorless = (!(opt->state & State_Active))
-                              && opt->palette.currentColorGroup() == QPalette::Active;
-        HIThemeButtonDrawInfo bdi;
-        bdi.version = qt_mac_hitheme_version;
-        bdi.state = tds;
-        if (drawColorless && tds == kThemeStateInactive)
-            bdi.state = kThemeStateActive;
-        bdi.adornment = kThemeDrawIndicatorOnly;
-        if (opt->state & State_HasFocus)
-            bdi.adornment |= kThemeAdornmentFocus;
-        bool isRadioButton = (pe == PE_IndicatorRadioButton);
-        switch (d->aquaSizeConstrain(opt, w)) {
-        case QAquaSizeUnknown:
-        case QAquaSizeLarge:
-            if (isRadioButton)
-                bdi.kind = kThemeRadioButton;
-            else
-                bdi.kind = kThemeCheckBox;
-            break;
-        case QAquaSizeMini:
-            if (isRadioButton)
-                bdi.kind = kThemeMiniRadioButton;
-            else
-                bdi.kind = kThemeMiniCheckBox;
-            break;
-        case QAquaSizeSmall:
-            if (isRadioButton)
-                bdi.kind = kThemeSmallRadioButton;
-            else
-                bdi.kind = kThemeSmallCheckBox;
-            break;
-        }
-        if (opt->state & State_NoChange)
-            bdi.value = kThemeButtonMixed;
-        else if (opt->state & State_On)
-            bdi.value = kThemeButtonOn;
-        else
-            bdi.value = kThemeButtonOff;
-        HIRect macRect = qt_hirectForQRect(opt->rect);
-        if (!drawColorless)
-            HIThemeDrawButton(&macRect, &bdi, cg, kHIThemeOrientationNormal, 0);
-        else
-            d->drawColorlessButton(macRect, &bdi, p, opt);
-        break; }
-    case PE_FrameFocusRect:
-        // Use the our own focus widget stuff.
-        break;
-    case PE_IndicatorBranch: {
-        if (!(opt->state & State_Children))
-            break;
-        HIThemeButtonDrawInfo bi;
-        bi.version = qt_mac_hitheme_version;
-        bi.state = tds;
-        if (tds == kThemeStateInactive && opt->palette.currentColorGroup() == QPalette::Active)
-            bi.state = kThemeStateActive;
-        if (opt->state & State_Sunken)
-            bi.state |= kThemeStatePressed;
-        bi.kind = kThemeDisclosureButton;
-        if (opt->state & State_Open)
-            bi.value = kThemeDisclosureDown;
-        else
-            bi.value = opt->direction == Qt::LeftToRight ? kThemeDisclosureRight : kThemeDisclosureLeft;
-        bi.adornment = kThemeAdornmentNone;
-        HIRect hirect = qt_hirectForQRect(opt->rect.adjusted(DisclosureOffset,0,-DisclosureOffset,0));
-        HIThemeDrawButton(&hirect, &bi, cg, kHIThemeOrientationNormal, 0);
-        break; }
-
-    case PE_Frame: {
-        QPen oldPen = p->pen();
-        p->setPen(opt->palette.base().color().darker(140));
-        p->drawRect(opt->rect.adjusted(0, 0, -1, -1));
-        p->setPen(opt->palette.base().color().darker(180));
-        p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
-        p->setPen(oldPen);
-        break; }
-
-    case PE_FrameLineEdit:
-        if (const QStyleOptionFrame *frame = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
-            if (frame->state & State_Sunken) {
-                QColor baseColor(frame->palette.background().color());
-                HIThemeFrameDrawInfo fdi;
-                fdi.version = qt_mac_hitheme_version;
-                fdi.state = tds;
-                SInt32 frame_size;
-                fdi.kind = kHIThemeFrameTextFieldSquare;
-                GetThemeMetric(kThemeMetricEditTextFrameOutset, &frame_size);
-                if ((frame->state & State_ReadOnly) || !(frame->state & State_Enabled))
-                    fdi.state = kThemeStateInactive;
-                else if (fdi.state == kThemeStatePressed)
-                    // This pressed state doesn't make sense for a line edit frame.
-                    // And Yosemite agrees with us. Otherwise it starts showing yellow pixels.
-                    fdi.state = kThemeStateActive;
-                fdi.isFocused = (frame->state & State_HasFocus);
-                int lw = frame->lineWidth;
-                if (lw <= 0)
-                    lw = proxy()->pixelMetric(PM_DefaultFrameWidth, frame, w);
-                { //clear to base color
-                    p->save();
-                    p->setPen(QPen(baseColor, lw));
-                    p->setBrush(Qt::NoBrush);
-                    p->drawRect(frame->rect);
-                    p->restore();
-                }
-                HIRect hirect = qt_hirectForQRect(frame->rect,
-                                                  QRect(frame_size, frame_size,
-                                                        frame_size * 2, frame_size * 2));
-
-                HIThemeDrawFrame(&hirect, &fdi, cg, kHIThemeOrientationNormal);
-            } else {
-                QWindowsStyle::drawPrimitive(pe, opt, p, w);
-            }
-        }
-        break;
-    case PE_PanelLineEdit:
-        QWindowsStyle::drawPrimitive(pe, opt, p, w);
-        // Draw the focus frame for widgets other than QLineEdit (e.g. for line edits in Webkit).
-        // Focus frame is drawn outside the rectangle passed in the option-rect.
-        if (const QStyleOptionFrame *panel = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
-            if ((opt->state & State_HasFocus) && !qobject_cast<const QLineEdit*>(w)) {
-                int vmargin = pixelMetric(QStyle::PM_FocusFrameVMargin);
-                int hmargin = pixelMetric(QStyle::PM_FocusFrameHMargin);
-                QStyleOptionFrame focusFrame = *panel;
-                focusFrame.rect = panel->rect.adjusted(-hmargin, -vmargin, hmargin, vmargin);
-                drawControl(CE_FocusFrame, &focusFrame, p, w);
-            }
-        }
-
-        break;
-    case PE_FrameTabWidget:
-        if (const QStyleOptionTabWidgetFrame *twf
-                = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
-            HIRect hirect = qt_hirectForQRect(twf->rect);
-            HIThemeTabPaneDrawInfo tpdi;
-            tpdi.version = qt_mac_hitheme_tab_version();
-            tpdi.state = tds;
-            tpdi.direction = getTabDirection(twf->shape);
-            tpdi.size = kHIThemeTabSizeNormal;
-            tpdi.kind = kHIThemeTabKindNormal;
-            tpdi.adornment = kHIThemeTabPaneAdornmentNormal;
-            HIThemeDrawTabPane(&hirect, &tpdi, cg, kHIThemeOrientationNormal);
-        }
-        break;
-    case PE_PanelScrollAreaCorner: {
-        const QBrush brush(opt->palette.brush(QPalette::Base));
-        p->fillRect(opt->rect, brush);
-        p->setPen(QPen(QColor(217, 217, 217)));
-        p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
-        p->drawLine(opt->rect.topLeft(), opt->rect.bottomLeft());
-        } break;
-    case PE_FrameStatusBarItem:
-        break;
-    case PE_IndicatorTabClose: {
-        bool hover = (opt->state & State_MouseOver);
-        bool selected = (opt->state & State_Selected);
-        bool active = (opt->state & State_Active);
-        drawTabCloseButton(p, hover, active, selected);
-        } break;
-    case PE_PanelStatusBar: {
-        if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_4) {
-            QWindowsStyle::drawPrimitive(pe, opt, p, w);
-            break;
-        }
-        // Use the Leopard style only if the status bar is the status bar for a
-        // QMainWindow with a unifed toolbar.
-        if (w == 0 || w->parent() == 0 || qobject_cast<QMainWindow *>(w->parent()) == 0 ||
-            qobject_cast<QMainWindow *>(w->parent())->unifiedTitleAndToolBarOnMac() == false ) {
-            QWindowsStyle::drawPrimitive(pe, opt, p, w);
-            break;
-        }
-
-        // Fill the status bar with the titlebar gradient.
-        QLinearGradient linearGrad(0, opt->rect.top(), 0, opt->rect.bottom());
-        if (opt->state & QStyle::State_Active) {
-            linearGrad.setColorAt(0, titlebarGradientActiveBegin);
-            linearGrad.setColorAt(1, titlebarGradientActiveEnd);
-        } else {
-            linearGrad.setColorAt(0, titlebarGradientInactiveBegin);
-            linearGrad.setColorAt(1, titlebarGradientInactiveEnd);
-        }
-        p->fillRect(opt->rect, linearGrad);
-
-        // Draw the black separator line at the top of the status bar.
-        if (opt->state & QStyle::State_Active)
-            p->setPen(titlebarSeparatorLineActive);
-        else
-            p->setPen(titlebarSeparatorLineInactive);
-        p->drawLine(opt->rect.left(), opt->rect.top(), opt->rect.right(), opt->rect.top());
-
-        break;
-    }
-
-    default:
-        QWindowsStyle::drawPrimitive(pe, opt, p, w);
-        break;
-    }
-}
-
-static inline QPixmap darkenPixmap(const QPixmap &pixmap)
-{
-    QImage img = pixmap.toImage().convertToFormat(QImage::Format_ARGB32);
-    int imgh = img.height();
-    int imgw = img.width();
-    int h, s, v, a;
-    QRgb pixel;
-    for (int y = 0; y < imgh; ++y) {
-        for (int x = 0; x < imgw; ++x) {
-            pixel = img.pixel(x, y);
-            a = qAlpha(pixel);
-            QColor hsvColor(pixel);
-            hsvColor.getHsv(&h, &s, &v);
-            s = qMin(100, s * 2);
-            v = v / 2;
-            hsvColor.setHsv(h, s, v);
-            pixel = hsvColor.rgb();
-            img.setPixel(x, y, qRgba(qRed(pixel), qGreen(pixel), qBlue(pixel), a));
-        }
-    }
-    return QPixmap::fromImage(img);
-}
-
-
-
-void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p,
-                            const QWidget *w) const
-{
-    ThemeDrawState tds = d->getDrawState(opt->state);
-    QMacCGContext cg(p);
-    switch (ce) {
-    case CE_HeaderSection:
-        if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
-            HIThemeButtonDrawInfo bdi;
-            bdi.version = qt_mac_hitheme_version;
-            State flags = header->state;
-            QRect ir = header->rect;
-            bdi.kind = kThemeListHeaderButton;
-            bdi.adornment = kThemeAdornmentNone;
-            bdi.state = kThemeStateActive;
-
-            if (flags & State_On)
-                bdi.value = kThemeButtonOn;
-            else
-                bdi.value = kThemeButtonOff;
-
-            if (header->orientation == Qt::Horizontal){
-                switch (header->position) {
-                case QStyleOptionHeader::Beginning:
-                    ir.adjust(-1, -1, 0, 0);
-                    break;
-                case QStyleOptionHeader::Middle:
-                    ir.adjust(-1, -1, 0, 0);
-                    break;
-                case QStyleOptionHeader::OnlyOneSection:
-                case QStyleOptionHeader::End:
-                    ir.adjust(-1, -1, 1, 0);
-                    break;
-                default:
-                    break;
-                }
-
-                if (header->position != QStyleOptionHeader::Beginning
-                    && header->position != QStyleOptionHeader::OnlyOneSection) {
-                    bdi.adornment = header->direction == Qt::LeftToRight
-                        ? kThemeAdornmentHeaderButtonLeftNeighborSelected
-                        : kThemeAdornmentHeaderButtonRightNeighborSelected;
-                }
-            }
-
-            if (flags & State_Active) {
-                if (!(flags & State_Enabled))
-                    bdi.state = kThemeStateUnavailable;
-                else if (flags & State_Sunken)
-                    bdi.state = kThemeStatePressed;
-            } else {
-                if (flags & State_Enabled)
-                    bdi.state = kThemeStateInactive;
-                else
-                    bdi.state = kThemeStateUnavailableInactive;
-            }
-
-            if (header->sortIndicator != QStyleOptionHeader::None) {
-                bdi.value = kThemeButtonOn;
-                if (header->sortIndicator == QStyleOptionHeader::SortDown)
-                    bdi.adornment = kThemeAdornmentHeaderButtonSortUp;
-            }
-            if (flags & State_HasFocus)
-                bdi.adornment = kThemeAdornmentFocus;
-
-            ir = visualRect(header->direction, header->rect, ir);
-            HIRect bounds = qt_hirectForQRect(ir);
-
-            bool noVerticalHeader = true;
-            if (w)
-                if (const QTableView *table = qobject_cast<const QTableView *>(w->parentWidget()))
-                    noVerticalHeader = !table->verticalHeader()->isVisible();
-
-            bool drawTopBorder = header->orientation == Qt::Horizontal;
-            bool drawLeftBorder = header->orientation == Qt::Vertical
-                || header->position == QStyleOptionHeader::OnlyOneSection
-                || (header->position == QStyleOptionHeader::Beginning && noVerticalHeader);
-            d->drawTableHeader(bounds, drawTopBorder, drawLeftBorder, bdi, p);
-        }
-        break;
-    case CE_HeaderLabel:
-        if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
-            QRect textr = header->rect;
-            if (!header->icon.isNull()) {
-                QIcon::Mode mode = QIcon::Disabled;
-                if (opt->state & State_Enabled)
-                    mode = QIcon::Normal;
-                QPixmap pixmap = header->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize), mode);
-
-                QRect pixr = header->rect;
-                pixr.setY(header->rect.center().y() - (pixmap.height() - 1) / 2);
-                proxy()->drawItemPixmap(p, pixr, Qt::AlignVCenter, pixmap);
-                textr.translate(pixmap.width() + 2, 0);
-            }
-
-            proxy()->drawItemText(p, textr, header->textAlignment | Qt::AlignVCenter, header->palette,
-                                       header->state & State_Enabled, header->text, QPalette::ButtonText);
-        }
-        break;
-    case CE_ToolButtonLabel:
-        if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
-            QStyleOptionToolButton myTb = *tb;
-            myTb.state &= ~State_AutoRaise;
-            if (w && qobject_cast<QToolBar *>(w->parentWidget())) {
-                QRect cr = tb->rect;
-                int shiftX = 0;
-                int shiftY = 0;
-                bool needText = false;
-                int alignment = 0;
-                bool down = tb->state & (State_Sunken | State_On);
-                if (down) {
-                    shiftX = proxy()->pixelMetric(PM_ButtonShiftHorizontal, tb, w);
-                    shiftY = proxy()->pixelMetric(PM_ButtonShiftVertical, tb, w);
-                }
-                // The down state is special for QToolButtons in a toolbar on the Mac
-                // The text is a bit bolder and gets a drop shadow and the icons are also darkened.
-                // This doesn't really fit into any particular case in QIcon, so we
-                // do the majority of the work ourselves.
-                if (!(tb->features & QStyleOptionToolButton::Arrow)) {
-                    Qt::ToolButtonStyle tbstyle = tb->toolButtonStyle;
-                    if (tb->icon.isNull() && !tb->text.isEmpty())
-                        tbstyle = Qt::ToolButtonTextOnly;
-
-                    switch (tbstyle) {
-                    case Qt::ToolButtonTextOnly: {
-                        needText = true;
-                        alignment = Qt::AlignCenter;
-                        break; }
-                    case Qt::ToolButtonIconOnly:
-                    case Qt::ToolButtonTextBesideIcon:
-                    case Qt::ToolButtonTextUnderIcon: {
-                        QRect pr = cr;
-                        QIcon::Mode iconMode = (tb->state & State_Enabled) ? QIcon::Normal
-                                                                            : QIcon::Disabled;
-                        QIcon::State iconState = (tb->state & State_On) ? QIcon::On
-                                                                         : QIcon::Off;
-                        QPixmap pixmap = tb->icon.pixmap(tb->rect.size().boundedTo(tb->iconSize), iconMode, iconState);
-
-                        // Draw the text if it's needed.
-                        if (tb->toolButtonStyle != Qt::ToolButtonIconOnly) {
-                            needText = true;
-                            if (tb->toolButtonStyle == Qt::ToolButtonTextUnderIcon) {
-                                QMainWindow *mw = qobject_cast<QMainWindow *>(w->window());
-                                if (mw && mw->unifiedTitleAndToolBarOnMac()) {
-                                    pr.setHeight(pixmap.size().height());
-                                    cr.adjust(0, pr.bottom() + 1, 0, 1);
-                                } else {
-                                    pr.setHeight(pixmap.size().height() + 6);
-                                    cr.adjust(0, pr.bottom(), 0, -3);
-                                }       
-                                alignment |= Qt::AlignCenter;
-                            } else {
-                                pr.setWidth(pixmap.width() + 8);
-                                cr.adjust(pr.right(), 0, 0, 0);
-                                alignment |= Qt::AlignLeft | Qt::AlignVCenter;
-                            }
-                        }
-                        if (opt->state & State_Sunken) {
-                            pr.translate(shiftX, shiftY);
-                            pixmap = darkenPixmap(pixmap);
-                        }
-                        proxy()->drawItemPixmap(p, pr, Qt::AlignCenter, pixmap);
-                        break; }
-                    default:
-                        Q_ASSERT(false);
-                        break;
-                    }
-
-                    if (needText) {
-                        QPalette pal = tb->palette;
-                        QPalette::ColorRole role = QPalette::NoRole;
-                        if (!proxy()->styleHint(SH_UnderlineShortcut, tb, w))
-                            alignment |= Qt::TextHideMnemonic;
-                        if (down)
-                            cr.translate(shiftX, shiftY);
-                        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5
-                            && (tbstyle == Qt::ToolButtonTextOnly
-                                || (tbstyle != Qt::ToolButtonTextOnly && !down))) {
-                            QPen pen = p->pen();
-                            QColor light = down ? Qt::black : Qt::white;
-                            light.setAlphaF(0.375f);
-                            p->setPen(light);
-                            p->drawText(cr.adjusted(0, 1, 0, 1), alignment, tb->text);
-                            p->setPen(pen);
-                            if (down && tbstyle == Qt::ToolButtonTextOnly) {
-                                pal = QApplication::palette("QMenu");
-                                pal.setCurrentColorGroup(tb->palette.currentColorGroup());
-                                role = QPalette::HighlightedText;
-                            }
-                        }
-                        proxy()->drawItemText(p, cr, alignment, pal,
-                                              tb->state & State_Enabled, tb->text, role);
-                        if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5 &&
-                            (tb->state & State_Sunken)) {
-                            // Draw a "drop shadow" in earlier versions.
-                            proxy()->drawItemText(p, cr.adjusted(0, 1, 0, 1), alignment,
-                                                  tb->palette, tb->state & State_Enabled, tb->text);
-                        }
-                    }
-                } else {
-                    QWindowsStyle::drawControl(ce, &myTb, p, w);
-                }
-            } else {
-                QWindowsStyle::drawControl(ce, &myTb, p, w);
-            }
-        }
-        break;
-    case CE_ToolBoxTabShape:
-        QCommonStyle::drawControl(ce, opt, p, w);
-        break;
-    case CE_PushButtonBevel:
-        if (const QStyleOptionButton *btn = ::qstyleoption_cast<const QStyleOptionButton *>(opt)) {
-            if (!(btn->state & (State_Raised | State_Sunken | State_On)))
-                break;
-
-            if (btn->features & QStyleOptionButton::CommandLinkButton) {
-                QWindowsStyle::drawControl(ce, opt, p, w);
-                break;
-            }
-
-            HIThemeButtonDrawInfo bdi;
-            d->initHIThemePushButton(btn, w, tds, &bdi);
-            if (btn->features & QStyleOptionButton::DefaultButton
-                    && d->animatable(QMacStylePrivate::AquaPushButton, w)) {
-                bdi.adornment |= kThemeAdornmentDefault;
-                bdi.animation.time.start = d->defaultButtonStart;
-                bdi.animation.time.current = CFAbsoluteTimeGetCurrent();
-                if (d->timerID <= -1)
-                    QMetaObject::invokeMethod(d, "startAnimationTimer", Qt::QueuedConnection);
-            }
-            // Unlike Carbon, we want the button to always be drawn inside its bounds.
-            // Therefore, make the button a bit smaller, so that even if it got focus,
-            // the focus 'shadow' will be inside.
-            HIRect newRect = qt_hirectForQRect(btn->rect);
-            if (bdi.kind == kThemePushButton || bdi.kind == kThemePushButtonSmall) {
-                newRect.origin.x += QMacStylePrivate::PushButtonLeftOffset;
-                newRect.origin.y += QMacStylePrivate::PushButtonTopOffset;
-                newRect.size.width -= QMacStylePrivate::PushButtonRightOffset;
-                newRect.size.height -= QMacStylePrivate::PushButtonBottomOffset;
-            } else if (bdi.kind == kThemePushButtonMini) {
-                newRect.origin.x += QMacStylePrivate::PushButtonLeftOffset - 2;
-                newRect.origin.y += QMacStylePrivate::PushButtonTopOffset;
-                newRect.size.width -= QMacStylePrivate::PushButtonRightOffset - 4;
-            }
-            HIThemeDrawButton(&newRect, &bdi, cg, kHIThemeOrientationNormal, 0);
-
-            if (btn->features & QStyleOptionButton::HasMenu) {
-                int mbi = proxy()->pixelMetric(QStyle::PM_MenuButtonIndicator, btn, w);
-                QRect ir = btn->rect;
-                HIRect arrowRect = CGRectMake(ir.right() - mbi - QMacStylePrivate::PushButtonRightOffset,
-                                              ir.height() / 2 - 4, mbi, ir.height() / 2);
-                bool drawColorless = btn->palette.currentColorGroup() == QPalette::Active;
-                if (drawColorless && tds == kThemeStateInactive)
-                    tds = kThemeStateActive;
-
-                HIThemePopupArrowDrawInfo pdi;
-                pdi.version = qt_mac_hitheme_version;
-                pdi.state = tds;
-                pdi.orientation = kThemeArrowDown;
-                if (arrowRect.size.width < 8.)
-                    pdi.size = kThemeArrow5pt;
-                else
-                    pdi.size = kThemeArrow9pt;
-                HIThemeDrawPopupArrow(&arrowRect, &pdi, cg, kHIThemeOrientationNormal);
-            }
-        }
-        break;
-    case CE_PushButtonLabel:
-        if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
-            // We really don't want the label to be drawn the same as on
-            // windows style if it has an icon and text, then it should be more like a
-            // tab. So, cheat a little here. However, if it *is* only an icon
-            // the windows style works great, so just use that implementation.
-            bool hasMenu = btn->features & QStyleOptionButton::HasMenu;
-            bool hasIcon = !btn->icon.isNull();
-            bool hasText = !btn->text.isEmpty();
-            if (!hasIcon && !hasMenu) {
-                // ### this is really overly difficult, simplify.
-                // It basically tries to get the right font for "small" and "mini" icons.
-                QFont oldFont = p->font();
-                QFont newFont = qt_app_fonts_hash()->value("QPushButton", QFont());
-                ThemeFontID themeId = kThemePushButtonFont;
-                if (oldFont == newFont) {  // Yes, use HITheme to draw the text for small sizes.
-                    switch (d->aquaSizeConstrain(opt, w)) {
-                    default:
-                        break;
-                    case QAquaSizeSmall:
-                        themeId = kThemeSmallSystemFont;
-                        break;
-                    case QAquaSizeMini:
-                        themeId = kThemeMiniSystemFont;
-                        break;
-                    }
-                }
-                if (themeId == kThemePushButtonFont) {
-                    QWindowsStyle::drawControl(ce, btn, p, w);
-                } else {
-                    p->save();
-                    CGContextSetShouldAntialias(cg, true);
-                    CGContextSetShouldSmoothFonts(cg, true);
-                    HIThemeTextInfo tti;
-                    tti.version = qt_mac_hitheme_version;
-                    tti.state = tds;
-                    QColor textColor = btn->palette.buttonText().color();
-                    CGFloat colorComp[] = { textColor.redF(), textColor.greenF(),
-                                          textColor.blueF(), textColor.alphaF() };
-                    CGContextSetFillColorSpace(cg, QCoreGraphicsPaintEngine::macGenericColorSpace());
-                    CGContextSetFillColor(cg, colorComp);
-                    tti.fontID = themeId;
-                    tti.horizontalFlushness = kHIThemeTextHorizontalFlushCenter;
-                    tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
-                    tti.options = kHIThemeTextBoxOptionNone;
-                    tti.truncationPosition = kHIThemeTextTruncationNone;
-                    tti.truncationMaxLines = 1 + btn->text.count(QLatin1Char('\n'));
-                    QCFString buttonText = qt_mac_removeMnemonics(btn->text);
-                    QRect r = btn->rect;
-                    HIRect bounds = qt_hirectForQRect(r);
-                    HIThemeDrawTextBox(buttonText, &bounds, &tti,
-                                       cg, kHIThemeOrientationNormal);
-                    p->restore();
-                }
-            } else {
-                if (hasIcon && !hasText) {
-                    QWindowsStyle::drawControl(ce, btn, p, w);
-                } else {
-                    QRect freeContentRect = btn->rect;
-                    QRect textRect = itemTextRect(
-                        btn->fontMetrics, freeContentRect, Qt::AlignCenter, btn->state & State_Enabled, btn->text);
-                    if (hasMenu)
-                        textRect.adjust(-1, 0, -1, 0);
-                    // Draw the icon:
-                    if (hasIcon) {
-                        int contentW = textRect.width();
-                        if (hasMenu)
-                            contentW += proxy()->pixelMetric(PM_MenuButtonIndicator) + 4;
-                        QIcon::Mode mode = btn->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
-                        if (mode == QIcon::Normal && btn->state & State_HasFocus)
-                            mode = QIcon::Active;
-                        // Decide if the icon is should be on or off:
-                        QIcon::State state = QIcon::Off;
-                        if (btn->state & State_On)
-                            state = QIcon::On;
-                        QPixmap pixmap = btn->icon.pixmap(btn->iconSize, mode, state);
-                        contentW += pixmap.width() + QMacStylePrivate::PushButtonContentPadding;
-                        int iconLeftOffset = freeContentRect.x() + (freeContentRect.width() - contentW) / 2;
-                        int iconTopOffset = freeContentRect.y() + (freeContentRect.height() - pixmap.height()) / 2;
-                        QRect iconDestRect(iconLeftOffset, iconTopOffset, pixmap.width(), pixmap.height());
-                        QRect visualIconDestRect = visualRect(btn->direction, freeContentRect, iconDestRect);
-                        proxy()->drawItemPixmap(p, visualIconDestRect, Qt::AlignLeft | Qt::AlignVCenter, pixmap);
-                        int newOffset = iconDestRect.x() + iconDestRect.width()
-                                        + QMacStylePrivate::PushButtonContentPadding - textRect.x();
-                        textRect.adjust(newOffset, 0, newOffset, 0);
-                    }
-                    // Draw the text:
-                    if (hasText) {
-                        textRect = visualRect(btn->direction, freeContentRect, textRect);
-                        proxy()->drawItemText(p, textRect, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic, btn->palette,
-                                                   (btn->state & State_Enabled), btn->text, QPalette::ButtonText);
-                    }
-                }
-            }
-        }
-        break;
-    case CE_ComboBoxLabel:
-        if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
-            QStyleOptionComboBox comboCopy = *cb;
-            comboCopy.direction = Qt::LeftToRight;
-            QWindowsStyle::drawControl(CE_ComboBoxLabel, &comboCopy, p, w);
-        }
-        break;
-    case CE_TabBarTabShape:
-        if (const QStyleOptionTab *tabOpt = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
-
-            if (const QStyleOptionTabV3 *tabOptV3 = qstyleoption_cast<const QStyleOptionTabV3 *>(opt)) {
-                if (tabOptV3->documentMode) {
-                    p->save();
-                    QRect tabRect = tabOptV3->rect;
-                    drawTabShape(p, tabOptV3);
-                    p->restore();
-                    return;
-                }
-            }
-
-            bool usingYosemiteOrLater = QSysInfo::MacintoshVersion > QSysInfo::MV_10_9;
-
-            HIThemeTabDrawInfo tdi;
-            tdi.version = 1;
-            tdi.style = kThemeTabNonFront;
-            tdi.direction = getTabDirection(tabOpt->shape);
-            switch (d->aquaSizeConstrain(opt, w)) {
-            default:
-            case QAquaSizeUnknown:
-            case QAquaSizeLarge:
-                tdi.size = kHIThemeTabSizeNormal;
-                break;
-            case QAquaSizeSmall:
-                tdi.size = kHIThemeTabSizeSmall;
-                break;
-            case QAquaSizeMini:
-                tdi.size = kHIThemeTabSizeMini;
-                break;
-            }
-            bool verticalTabs = tdi.direction == kThemeTabWest || tdi.direction == kThemeTabEast;
-            QRect tabRect = tabOpt->rect;
-
-            bool selected = tabOpt->state & State_Selected;
-            if (selected) {
-                if (!(tabOpt->state & State_Active))
-                    tdi.style = kThemeTabFrontUnavailable;
-                else if (!(tabOpt->state & State_Enabled))
-                    tdi.style = kThemeTabFrontInactive;
-                else
-                    tdi.style = kThemeTabFront;
-            } else if (!(tabOpt->state & State_Active)) {
-                tdi.style = kThemeTabNonFrontUnavailable;
-            } else if (!(tabOpt->state & State_Enabled)) {
-                tdi.style = kThemeTabNonFrontInactive;
-            } else if (tabOpt->state & State_Sunken) {
-                tdi.style = kThemeTabFrontInactive; // (should be kThemeTabNonFrontPressed)
-            }
-            if (tabOpt->state & State_HasFocus)
-                tdi.adornment = kHIThemeTabAdornmentFocus;
-            else
-                tdi.adornment = kHIThemeTabAdornmentNone;
-            tdi.kind = kHIThemeTabKindNormal;
-
-            if (!usingYosemiteOrLater) {
-                if (!verticalTabs)
-                    tabRect.setY(tabRect.y() - 1);
-                else
-                    tabRect.setX(tabRect.x() - 1);
-            }
-            QStyleOptionTab::TabPosition tp = tabOpt->position;
-            QStyleOptionTab::SelectedPosition sp = tabOpt->selectedPosition;
-            if (tabOpt->direction == Qt::RightToLeft && !verticalTabs) {
-                if (sp == QStyleOptionTab::NextIsSelected)
-                    sp = QStyleOptionTab::PreviousIsSelected;
-                else if (sp == QStyleOptionTab::PreviousIsSelected)
-                    sp = QStyleOptionTab::NextIsSelected;
-                switch (tp) {
-                case QStyleOptionTab::Beginning:
-                    tp = QStyleOptionTab::End;
-                    break;
-                case QStyleOptionTab::End:
-                    tp = QStyleOptionTab::Beginning;
-                    break;
-                default:
-                    break;
-                }
-            }
-            bool stretchTabs = (!verticalTabs && tabRect.height() > 22) || (verticalTabs && tabRect.width() > 22);
-
-            switch (tp) {
-            case QStyleOptionTab::Beginning:
-                tdi.position = kHIThemeTabPositionFirst;
-                if (sp != QStyleOptionTab::NextIsSelected || stretchTabs)
-                    tdi.adornment |= kHIThemeTabAdornmentTrailingSeparator;
-                break;
-            case QStyleOptionTab::Middle:
-                tdi.position = kHIThemeTabPositionMiddle;
-                if (selected)
-                    tdi.adornment |= kHIThemeTabAdornmentLeadingSeparator;
-                if (sp != QStyleOptionTab::NextIsSelected || stretchTabs)  // Also when we're selected.
-                    tdi.adornment |= kHIThemeTabAdornmentTrailingSeparator;
-                break;
-            case QStyleOptionTab::End:
-                tdi.position = kHIThemeTabPositionLast;
-                if (selected)
-                    tdi.adornment |= kHIThemeTabAdornmentLeadingSeparator;
-                break;
-            case QStyleOptionTab::OnlyOneTab:
-                tdi.position = kHIThemeTabPositionOnly;
-                break;
-            }
-            // HITheme doesn't stretch its tabs. Therefore we have to cheat and do the job ourselves.
-            if (stretchTabs) {
-                HIRect hirect = CGRectMake(0, 0, 23, 23);
-                QPixmap pm(23, 23);
-                pm.fill(Qt::transparent);
-                {
-                    QMacCGContext pmcg(&pm);
-                    HIThemeDrawTab(&hirect, &tdi, pmcg, kHIThemeOrientationNormal, 0);
-                }
-                QStyleHelper::drawBorderPixmap(pm, p, tabRect, 7, 7, 7, 7);
-            } else {
-                HIRect hirect = qt_hirectForQRect(tabRect);
-                HIThemeDrawTab(&hirect, &tdi, cg, kHIThemeOrientationNormal, 0);
-            }
-        }
-        break;
-    case CE_TabBarTabLabel:
-        if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
-            QStyleOptionTabV3 myTab = *tab;
-            ThemeTabDirection ttd = getTabDirection(myTab.shape);
-            bool verticalTabs = ttd == kThemeTabWest || ttd == kThemeTabEast;
-            bool selected = (myTab.state & QStyle::State_Selected);
-            bool usingLionOrLater = QSysInfo::MacintoshVersion > QSysInfo::MV_10_6;
-            bool usingYosemiteOrLater = QSysInfo::MacintoshVersion > QSysInfo::MV_10_9;
-
-            if (usingLionOrLater && selected && !myTab.documentMode
-                && (!usingYosemiteOrLater || myTab.state & State_Active))
-                myTab.palette.setColor(QPalette::WindowText, Qt::white);
-
-            // Check to see if we use have the same as the system font
-            // (QComboMenuItem is internal and should never be seen by the
-            // outside world, unless they read the source, in which case, it's
-            // their own fault).
-            bool nonDefaultFont = p->font() != qt_app_fonts_hash()->value("QComboMenuItem");
-            bool isSelectedAndNeedsShadow = selected && usingLionOrLater && !usingYosemiteOrLater;
-            if (isSelectedAndNeedsShadow || verticalTabs || nonDefaultFont || !tab->icon.isNull()
-                || !myTab.leftButtonSize.isEmpty() || !myTab.rightButtonSize.isEmpty()) {
-                int heightOffset = 0;
-                if (verticalTabs) {
-                    heightOffset = -1;
-                } else if (nonDefaultFont) {
-                    if (p->fontMetrics().height() == myTab.rect.height())
-                        heightOffset = 2;
-                }
-                myTab.rect.setHeight(myTab.rect.height() + heightOffset);
-
-                if (myTab.documentMode || isSelectedAndNeedsShadow) {
-                    p->save();
-                    rotateTabPainter(p, myTab.shape, myTab.rect);
-
-                    QColor shadowColor = QColor(myTab.documentMode ? Qt::white : Qt::black);
-                    shadowColor.setAlpha(75);
-                    QPalette np = tab->palette;
-                    np.setColor(QPalette::WindowText, shadowColor);
-
-                    QRect nr = subElementRect(SE_TabBarTabText, opt, w);
-                    nr.moveTop(-1);
-                    int alignment = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextHideMnemonic;
-                    proxy()->drawItemText(p, nr, alignment, np, tab->state & State_Enabled,
-                                               tab->text, QPalette::WindowText);
-                    p->restore();
-                }
-
-                QCommonStyle::drawControl(ce, &myTab, p, w);
-            } else {
-                p->save();
-                CGContextSetShouldAntialias(cg, true);
-                CGContextSetShouldSmoothFonts(cg, true);
-                HIThemeTextInfo tti;
-                tti.version = qt_mac_hitheme_version;
-                tti.state = tds;
-                QColor textColor = myTab.palette.windowText().color();
-                CGFloat colorComp[] = { textColor.redF(), textColor.greenF(),
-                                        textColor.blueF(), textColor.alphaF() };
-                CGContextSetFillColorSpace(cg, QCoreGraphicsPaintEngine::macGenericColorSpace());
-                CGContextSetFillColor(cg, colorComp);
-                switch (d->aquaSizeConstrain(opt, w)) {
-                default:
-                case QAquaSizeUnknown:
-                case QAquaSizeLarge:
-                    tti.fontID = kThemeSystemFont;
-                    break;
-                case QAquaSizeSmall:
-                    tti.fontID = kThemeSmallSystemFont;
-                    break;
-                case QAquaSizeMini:
-                    tti.fontID = kThemeMiniSystemFont;
-                    break;
-                }
-                tti.horizontalFlushness = kHIThemeTextHorizontalFlushCenter;
-                tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
-                tti.options = verticalTabs ? kHIThemeTextBoxOptionStronglyVertical : kHIThemeTextBoxOptionNone;
-                tti.truncationPosition = kHIThemeTextTruncationNone;
-                tti.truncationMaxLines = 1 + myTab.text.count(QLatin1Char('\n'));
-                QCFString tabText = qt_mac_removeMnemonics(myTab.text);
-                QRect r = myTab.rect.adjusted(0, 0, 0, -1);
-                HIRect bounds = qt_hirectForQRect(r);
-                HIThemeDrawTextBox(tabText, &bounds, &tti, cg, kHIThemeOrientationNormal);
-                p->restore();
-            }
-        }
-        break;
-    case CE_DockWidgetTitle:
-        if (const QDockWidget *dockWidget = qobject_cast<const QDockWidget *>(w)) {
-            bool floating = dockWidget->isFloating();
-            if (floating) {
-                ThemeDrawState tds = d->getDrawState(opt->state);
-                HIThemeWindowDrawInfo wdi;
-                wdi.version = qt_mac_hitheme_version;
-                wdi.state = tds;
-                wdi.windowType = kThemeMovableDialogWindow;
-                wdi.titleHeight = opt->rect.height();
-                wdi.titleWidth = opt->rect.width();
-                wdi.attributes = 0;
-
-                HIRect titleBarRect;
-                HIRect tmpRect = qt_hirectForQRect(opt->rect);
-                {
-                    QCFType<HIShapeRef> titleRegion;
-                    QRect newr = opt->rect.adjusted(0, 0, 2, 0);
-                    HIThemeGetWindowShape(&tmpRect, &wdi, kWindowTitleBarRgn, &titleRegion);
-                    ptrHIShapeGetBounds(titleRegion, &tmpRect);
-                    newr.translate(newr.x() - int(tmpRect.origin.x), newr.y() - int(tmpRect.origin.y));
-                    titleBarRect = qt_hirectForQRect(newr);
-                }
-                QMacCGContext cg(p);
-                HIThemeDrawWindowFrame(&titleBarRect, &wdi, cg, kHIThemeOrientationNormal, 0);
-            } else {
-                // fill title bar background
-                QLinearGradient linearGrad(0, opt->rect.top(), 0, opt->rect.bottom());
-                linearGrad.setColorAt(0, mainWindowGradientBegin);
-                linearGrad.setColorAt(1, mainWindowGradientEnd);
-                p->fillRect(opt->rect, linearGrad);
-
-                // draw horizontal lines at top and bottom
-                p->save();
-                p->setPen(mainWindowGradientBegin.lighter(114));
-                p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
-                p->setPen(mainWindowGradientEnd.darker(114));
-                p->drawLine(opt->rect.bottomLeft(), opt->rect.bottomRight());
-                p->restore();
-            }
-        }
-
-        // Draw the text...
-        if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
-            if (!dwOpt->title.isEmpty()) {
-                const QStyleOptionDockWidgetV2 *v2
-                    = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(dwOpt);
-                bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
-                QRect titleRect = subElementRect(SE_DockWidgetTitleBarText, opt, w);
-                if (verticalTitleBar) {
-                    QRect rect = dwOpt->rect;
-                    QRect r = rect;
-                    QSize s = r.size();
-                    s.transpose();
-                    r.setSize(s);
-
-                    titleRect = QRect(r.left() + rect.bottom()
-                                        - titleRect.bottom(),
-                                    r.top() + titleRect.left() - rect.left(),
-                                    titleRect.height(), titleRect.width());
-
-                    p->translate(r.left(), r.top() + r.width());
-                    p->rotate(-90);
-                    p->translate(-r.left(), -r.top());
-                }
-
-                QFont oldFont = p->font();
-                p->setFont(qt_app_fonts_hash()->value("QToolButton", p->font()));
-                QString text = p->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight,
-                    titleRect.width());
-                drawItemText(p, titleRect,
-                              Qt::AlignCenter | Qt::TextShowMnemonic, dwOpt->palette,
-                              dwOpt->state & State_Enabled, text,
-                              QPalette::WindowText);
-                p->setFont(oldFont);
-            }
-        }
-        break;
-    case CE_FocusFrame: {
-        int xOff = proxy()->pixelMetric(PM_FocusFrameHMargin, opt, w);
-        int yOff = proxy()->pixelMetric(PM_FocusFrameVMargin, opt, w);
-        NSRect rect = NSMakeRect(xOff+opt->rect.x(), yOff+opt->rect.y(), opt->rect.width() - 2 * xOff,
-                                 opt->rect.height() - 2 * yOff);
-        CGContextSaveGState(cg);
-        [NSGraphicsContext setCurrentContext:[NSGraphicsContext
-             graphicsContextWithGraphicsPort:(CGContextRef)cg flipped:NO]];
-        [NSGraphicsContext saveGraphicsState];
-        NSSetFocusRingStyle(NSFocusRingOnly);
-        NSBezierPath *focusFramePath = [NSBezierPath bezierPathWithRect:rect];
-        [focusFramePath setClip]; // Clear clip path to avoid artifacts when rendering the cursor at zero pos
-        [focusFramePath fill];
-        [NSGraphicsContext restoreGraphicsState];
-        CGContextRestoreGState(cg);
-        break; }
-    case CE_MenuItem:
-    case CE_MenuEmptyArea:
-        if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
-            p->fillRect(mi->rect, opt->palette.background());
-            QAquaWidgetSize widgetSize = d->aquaSizeConstrain(opt, w);
-            int tabwidth = mi->tabWidth;
-            int maxpmw = mi->maxIconWidth;
-            bool active = mi->state & State_Selected;
-            bool enabled = mi->state & State_Enabled;
-            HIRect menuRect = qt_hirectForQRect(mi->menuRect);
-            HIRect itemRect = qt_hirectForQRect(mi->rect);
-            HIThemeMenuItemDrawInfo mdi;
-            mdi.version = qt_mac_hitheme_version;
-            mdi.itemType = kThemeMenuItemPlain;
-            if (!mi->icon.isNull())
-                mdi.itemType |= kThemeMenuItemHasIcon;
-            if (mi->menuItemType == QStyleOptionMenuItem::SubMenu)
-                mdi.itemType |= kThemeMenuItemHierarchical | kThemeMenuItemHierBackground;
-            else
-                mdi.itemType |= kThemeMenuItemPopUpBackground;
-            if (enabled)
-                mdi.state = kThemeMenuActive;
-            else
-                mdi.state = kThemeMenuDisabled;
-            if (active)
-                mdi.state |= kThemeMenuSelected;
-            QRect contentRect;
-            if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
-                // First arg should be &menurect, but wacky stuff happens then.
-                HIThemeDrawMenuSeparator(&itemRect, &itemRect, &mdi,
-                                         cg, kHIThemeOrientationNormal);
-                break;
-            } else {
-                HIRect cr;
-                bool needAlpha = mi->palette.color(QPalette::Button) == Qt::transparent;
-                if (needAlpha) {
-                    needAlpha = true;
-                    CGContextSaveGState(cg);
-                    CGContextSetAlpha(cg, 0.0);
-                }
-                HIThemeDrawMenuItem(&menuRect, &itemRect, &mdi,
-                                    cg, kHIThemeOrientationNormal, &cr);
-                if (needAlpha)
-                    CGContextRestoreGState(cg);
-                if (ce == CE_MenuEmptyArea)
-                    break;
-                contentRect = qt_qrectForHIRect(cr);
-            }
-            int xpos = contentRect.x() + 18;
-            int checkcol = maxpmw;
-            if (!enabled)
-                p->setPen(mi->palette.text().color());
-            else if (active)
-                p->setPen(mi->palette.highlightedText().color());
-            else
-                p->setPen(mi->palette.buttonText().color());
-
-            if (mi->checked) {
-                // Use the HIThemeTextInfo foo to draw the check mark correctly, if we do it,
-                // we somehow need to use a special encoding as it doesn't look right with our
-                // drawText().
-                p->save();
-                CGContextSetShouldAntialias(cg, true);
-                CGContextSetShouldSmoothFonts(cg, true);
-                QColor textColor = p->pen().color();
-                CGFloat colorComp[] = { textColor.redF(), textColor.greenF(),
-                                      textColor.blueF(), textColor.alphaF() };
-                CGContextSetFillColorSpace(cg, QCoreGraphicsPaintEngine::macGenericColorSpace());
-                CGContextSetFillColor(cg, colorComp);
-                HIThemeTextInfo tti;
-                tti.version = qt_mac_hitheme_version;
-                tti.state = tds;
-                if (active && enabled)
-                    tti.state = kThemeStatePressed;
-                switch (widgetSize) {
-                case QAquaSizeUnknown:
-                case QAquaSizeLarge:
-                    tti.fontID = kThemeMenuItemMarkFont;
-                    break;
-                case QAquaSizeSmall:
-                    tti.fontID = kThemeSmallSystemFont;
-                    break;
-                case QAquaSizeMini:
-                    tti.fontID = kThemeMiniSystemFont;
-                    break;
-                }
-                tti.horizontalFlushness = kHIThemeTextHorizontalFlushLeft;
-                tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
-                tti.options = kHIThemeTextBoxOptionNone;
-                tti.truncationPosition = kHIThemeTextTruncationNone;
-                tti.truncationMaxLines = 1;
-                QCFString checkmark;
-#if 0
-                if (mi->checkType == QStyleOptionMenuItem::Exclusive)
-                    checkmark = QString(QChar(kDiamondUnicode));
-                else
-#endif
-                    checkmark = QString(QChar(kCheckUnicode));
-                int mw = checkcol + macItemFrame;
-                int mh = contentRect.height() - 2 * macItemFrame;
-                int xp = contentRect.x();
-                xp += macItemFrame;
-                CGFloat outWidth, outHeight, outBaseline;
-                HIThemeGetTextDimensions(checkmark, 0, &tti, &outWidth, &outHeight,
-                                         &outBaseline);
-                if (widgetSize == QAquaSizeMini)
-                    outBaseline += 1;
-                QRect r(xp, contentRect.y(), mw, mh);
-                r.translate(0, p->fontMetrics().ascent() - int(outBaseline) + 1);
-                HIRect bounds = qt_hirectForQRect(r);
-                HIThemeDrawTextBox(checkmark, &bounds, &tti,
-                                   cg, kHIThemeOrientationNormal);
-                p->restore();
-            }
-            if (!mi->icon.isNull()) {
-                QIcon::Mode mode = (mi->state & State_Enabled) ? QIcon::Normal
-                                                               : QIcon::Disabled;
-                // Always be normal or disabled to follow the Mac style.
-                int smallIconSize = proxy()->pixelMetric(PM_SmallIconSize);
-                QSize iconSize(smallIconSize, smallIconSize);
-                if (const QComboBox *comboBox = qobject_cast<const QComboBox *>(w)) {
-                    iconSize = comboBox->iconSize();
-                }
-                QPixmap pixmap = mi->icon.pixmap(iconSize, mode);
-                int pixw = pixmap.width();
-                int pixh = pixmap.height();
-                QRect cr(xpos, contentRect.y(), checkcol, contentRect.height());
-                QRect pmr(0, 0, pixw, pixh);
-                pmr.moveCenter(cr.center());
-                p->drawPixmap(pmr.topLeft(), pixmap);
-                xpos += pixw + 6;
-            }
-
-            QString s = mi->text;
-            if (!s.isEmpty()) {
-                int t = s.indexOf(QLatin1Char('\t'));
-                int text_flags = Qt::AlignRight | Qt::AlignVCenter | Qt::TextHideMnemonic
-                                 | Qt::TextSingleLine | Qt::AlignAbsolute;
-                int yPos = contentRect.y();
-                if (widgetSize == QAquaSizeMini)
-                    yPos += 1;
-                p->save();
-                if (t >= 0) {
-                    p->setFont(qt_app_fonts_hash()->value("QMenuItem", p->font()));
-                    int xp = contentRect.right() - tabwidth - macRightBorder
-                             - macItemHMargin - macItemFrame + 1;
-                    p->drawText(xp, yPos, tabwidth, contentRect.height(), text_flags,
-                                s.mid(t + 1));
-                    s = s.left(t);
-                }
-
-                const int xm = macItemFrame + maxpmw + macItemHMargin;
-                QFont myFont = mi->font;
-                // myFont may not have any "hard" flags set. We override
-                // the point size so that when it is resolved against the device, this font will win.
-                // This is mainly to handle cases where someone sets the font on the window
-                // and then the combo inherits it and passes it onward. At that point the resolve mask
-                // is very, very weak. This makes it stonger.
-                myFont.setPointSizeF(QFontInfo(mi->font).pointSizeF());
-                p->setFont(myFont);
-                p->drawText(xpos, yPos, contentRect.width() - xm - tabwidth + 1,
-                            contentRect.height(), text_flags ^ Qt::AlignRight, s);
-                p->restore();
-            }
-        }
-        break;
-    case CE_MenuHMargin:
-    case CE_MenuVMargin:
-    case CE_MenuTearoff:
-    case CE_MenuScroller:
-        if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
-            p->fillRect(mi->rect, opt->palette.background());
-
-            HIRect menuRect = qt_hirectForQRect(mi->menuRect);
-            HIRect itemRect = qt_hirectForQRect(mi->rect);
-            HIThemeMenuItemDrawInfo mdi;
-            mdi.version = qt_mac_hitheme_version;
-            if (!(opt->state & State_Enabled))
-                mdi.state = kThemeMenuDisabled;
-            else if (opt->state & State_Selected)
-                mdi.state = kThemeMenuSelected;
-            else
-                mdi.state = kThemeMenuActive;
-            if (ce == CE_MenuScroller) {
-                if (opt->state & State_DownArrow)
-                    mdi.itemType = kThemeMenuItemScrollDownArrow;
-                else
-                    mdi.itemType = kThemeMenuItemScrollUpArrow;
-            } else {
-                mdi.itemType = kThemeMenuItemPlain;
-            }
-            HIThemeDrawMenuItem(&menuRect, &itemRect, &mdi,
-                                cg,
-                                kHIThemeOrientationNormal, 0);
-            if (ce == CE_MenuTearoff) {
-                p->setPen(QPen(mi->palette.dark().color(), 1, Qt::DashLine));
-                p->drawLine(mi->rect.x() + 2, mi->rect.y() + mi->rect.height() / 2 - 1,
-                            mi->rect.x() + mi->rect.width() - 4,
-                            mi->rect.y() + mi->rect.height() / 2 - 1);
-                p->setPen(QPen(mi->palette.light().color(), 1, Qt::DashLine));
-                p->drawLine(mi->rect.x() + 2, mi->rect.y() + mi->rect.height() / 2,
-                            mi->rect.x() + mi->rect.width() - 4,
-                            mi->rect.y() + mi->rect.height() / 2);
-            }
-        }
-        break;
-    case CE_MenuBarItem:
-        if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
-            HIRect menuRect = qt_hirectForQRect(mi->menuRect);
-            HIRect itemRect = qt_hirectForQRect(mi->rect);
-
-            if ((opt->state & State_Selected) && (opt->state & State_Enabled) && (opt->state & State_Sunken)){
-                // Draw a selected menu item background:
-                HIThemeMenuItemDrawInfo mdi;
-                mdi.version = qt_mac_hitheme_version;
-                mdi.state = kThemeMenuSelected;
-                mdi.itemType = kThemeMenuItemPlain;
-                HIThemeDrawMenuItem(&menuRect, &itemRect, &mdi, cg, kHIThemeOrientationNormal, 0);
-            } else {
-                // Draw the toolbar background:
-                HIThemeMenuBarDrawInfo bdi;
-                bdi.version = qt_mac_hitheme_version;
-                bdi.state = kThemeMenuBarNormal;
-                bdi.attributes = 0;
-                HIThemeDrawMenuBarBackground(&menuRect, &bdi, cg, kHIThemeOrientationNormal);
-            }
-
-            if (!mi->icon.isNull()) {
-                drawItemPixmap(p, mi->rect,
-                                  Qt::AlignCenter | Qt::TextHideMnemonic | Qt::TextDontClip
-                                  | Qt::TextSingleLine,
-                                  mi->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize),
-                          (mi->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled));
-            } else {
-                drawItemText(p, mi->rect,
-                                Qt::AlignCenter | Qt::TextHideMnemonic | Qt::TextDontClip
-                                | Qt::TextSingleLine,
-                                mi->palette, mi->state & State_Enabled,
-                                mi->text, QPalette::ButtonText);
-            }
-        }
-        break;
-    case CE_MenuBarEmptyArea:
-        if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
-            HIThemeMenuBarDrawInfo bdi;
-            bdi.version = qt_mac_hitheme_version;
-            bdi.state = kThemeMenuBarNormal;
-            bdi.attributes = 0;
-            HIRect hirect = qt_hirectForQRect(mi->rect);
-            HIThemeDrawMenuBarBackground(&hirect, &bdi, cg,
-                                         kHIThemeOrientationNormal);
-            break;
-        }
-    case CE_ProgressBarContents:
-        if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
-            HIThemeTrackDrawInfo tdi;
-            tdi.version = qt_mac_hitheme_version;
-            tdi.reserved = 0;
-            bool isIndeterminate = (pb->minimum == 0 && pb->maximum == 0);
-            bool vertical = false;
-            bool inverted = false;
-            if (const QStyleOptionProgressBarV2 *pb2 = qstyleoption_cast<const QStyleOptionProgressBarV2 *>(opt)) {
-                vertical = (pb2->orientation == Qt::Vertical);
-                inverted = pb2->invertedAppearance;
-            }
-            bool reverse = (!vertical && (pb->direction == Qt::RightToLeft));
-            if (inverted)
-                reverse = !reverse;
-            switch (d->aquaSizeConstrain(opt, w)) {
-            case QAquaSizeUnknown:
-            case QAquaSizeLarge:
-                tdi.kind = !isIndeterminate ? kThemeLargeProgressBar
-                                            : kThemeLargeIndeterminateBar;
-                break;
-            case QAquaSizeMini:
-            case QAquaSizeSmall:
-                tdi.kind = !isIndeterminate ? kThemeProgressBar : kThemeIndeterminateBar;
-                break;
-            }
-            tdi.bounds = qt_hirectForQRect(pb->rect);
-            tdi.max = pb->maximum;
-            tdi.min = pb->minimum;
-            tdi.value = pb->progress;
-            tdi.attributes = vertical ? 0 : kThemeTrackHorizontal;
-            tdi.trackInfo.progress.phase = d->progressFrame;
-            if (!(pb->state & State_Active))
-                tdi.enableState = kThemeTrackInactive;
-            else if (!(pb->state & State_Enabled))
-                tdi.enableState = kThemeTrackDisabled;
-            else
-                tdi.enableState = kThemeTrackActive;
-            HIThemeOrientation drawOrientation = kHIThemeOrientationNormal;
-            if (reverse) {
-                if (vertical) {
-                    drawOrientation = kHIThemeOrientationInverted;
-                } else {
-                    CGContextSaveGState(cg);
-                    CGContextTranslateCTM(cg, pb->rect.width(), 0);
-                    CGContextScaleCTM(cg, -1, 1);
-                }
-            }
-            HIThemeDrawTrack(&tdi, 0, cg, drawOrientation);
-            if (reverse && !vertical)
-                CGContextRestoreGState(cg);
-        }
-        break;
-    case CE_ProgressBarLabel:
-    case CE_ProgressBarGroove:
-        break;
-    case CE_SizeGrip: {
-        if (w && w->testAttribute(Qt::WA_MacOpaqueSizeGrip)) {
-            HIThemeGrowBoxDrawInfo gdi;
-            gdi.version = qt_mac_hitheme_version;
-            gdi.state = tds;
-            gdi.kind = kHIThemeGrowBoxKindNormal;
-            gdi.direction = kThemeGrowRight | kThemeGrowDown;
-            gdi.size = kHIThemeGrowBoxSizeNormal;
-            HIPoint pt = CGPointMake(opt->rect.x(), opt->rect.y());
-            HIThemeDrawGrowBox(&pt, &gdi, cg, kHIThemeOrientationNormal);
-        } else {
-            // It isn't possible to draw a transparent size grip with the
-            // native API, so we do it ourselves here.
-            const bool metal = qt_mac_is_metal(w);
-            QPen lineColor = metal ? QColor(236, 236, 236) : QColor(82, 82, 82, 192);
-            QPen metalHighlight = QColor(5, 5, 5, 192);
-            lineColor.setWidth(1);
-            p->save();
-            p->setPen(lineColor);
-            const Qt::LayoutDirection layoutDirection = w ? w->layoutDirection() : qApp->layoutDirection();
-            const int NumLines = metal ? 4 : 3;
-            for (int l = 0; l < NumLines; ++l) {
-                const int offset = (l * 4 + (metal ? 2 : 3));
-                QPoint start, end;
-                if (layoutDirection == Qt::LeftToRight) {
-                    start = QPoint(opt->rect.width() - offset, opt->rect.height() - 1);
-                    end = QPoint(opt->rect.width() - 1, opt->rect.height() - offset);
-                } else {
-                    start = QPoint(offset, opt->rect.height() - 1);
-                    end = QPoint(1, opt->rect.height() - offset);
-                }
-                p->drawLine(start, end);
-                if (metal) {
-                    p->setPen(metalHighlight);
-                    p->drawLine(start + QPoint(0, -1), end + QPoint(0, -1));
-                    p->setPen(lineColor);
-                }
-            }
-            p->restore();
-        }
-        break;
-        }
-    case CE_Splitter: {
-        HIThemeSplitterDrawInfo sdi;
-        sdi.version = qt_mac_hitheme_version;
-        sdi.state = tds;
-        sdi.adornment = qt_mac_is_metal(w) ? kHIThemeSplitterAdornmentMetal
-                                           : kHIThemeSplitterAdornmentNone;
-        HIRect hirect = qt_hirectForQRect(opt->rect);
-        HIThemeDrawPaneSplitter(&hirect, &sdi, cg, kHIThemeOrientationNormal);
-        break; }
-    case CE_RubberBand:
-        if (const QStyleOptionRubberBand *rubber = qstyleoption_cast<const QStyleOptionRubberBand *>(opt)) {
-            QColor fillColor(opt->palette.color(QPalette::Disabled, QPalette::Highlight));
-            if (!rubber->opaque) {
-                QColor strokeColor;
-                // I retrieved these colors from the Carbon-Dev mailing list
-                strokeColor.setHsvF(0, 0, 0.86, 1.0);
-                fillColor.setHsvF(0, 0, 0.53, 0.25);
-                if (opt->rect.width() * opt->rect.height() <= 3) {
-                    p->fillRect(opt->rect, strokeColor);
-                } else {
-                    QPen oldPen = p->pen();
-                    QBrush oldBrush = p->brush();
-                    QPen pen(strokeColor);
-                    p->setPen(pen);
-                    p->setBrush(fillColor);
-                    p->drawRect(opt->rect.adjusted(0, 0, -1, -1));
-                    p->setPen(oldPen);
-                    p->setBrush(oldBrush);
-                }
-            } else {
-                p->fillRect(opt->rect, fillColor);
-            }
-        }
-        break;
-    case CE_ToolBar: {
-        // For unified tool bars, draw nothing.
-        if (w) {
-            if (QMainWindow * mainWindow = qobject_cast<QMainWindow *>(w->window())) {
-                if (mainWindow->unifiedTitleAndToolBarOnMac())
-                    break;
-                }
-        }
-
-        // draw background gradient
-        QLinearGradient linearGrad;
-        if (opt->state & State_Horizontal)
-            linearGrad = QLinearGradient(0, opt->rect.top(), 0, opt->rect.bottom());
-        else
-            linearGrad = QLinearGradient(opt->rect.left(), 0,  opt->rect.right(), 0);
-
-        linearGrad.setColorAt(0, mainWindowGradientBegin);
-        linearGrad.setColorAt(1, mainWindowGradientEnd);
-        p->fillRect(opt->rect, linearGrad);
-
-        p->save();
-        if (opt->state & State_Horizontal) {
-            p->setPen(mainWindowGradientBegin.lighter(114));
-            p->drawLine(opt->rect.topLeft(), opt->rect.topRight());
-            p->setPen(mainWindowGradientEnd.darker(114));
-            p->drawLine(opt->rect.bottomLeft(), opt->rect.bottomRight());
-
-        } else {
-            p->setPen(mainWindowGradientBegin.lighter(114));
-            p->drawLine(opt->rect.topLeft(), opt->rect.bottomLeft());
-            p->setPen(mainWindowGradientEnd.darker(114));
-            p->drawLine(opt->rect.topRight(), opt->rect.bottomRight());
-        }
-        p->restore();
-
-
-        } break;
-    default:
-        QWindowsStyle::drawControl(ce, opt, p, w);
-        break;
-    }
-}
-
-static void setLayoutItemMargins(int left, int top, int right, int bottom, QRect *rect, Qt::LayoutDirection dir)
-{
-    if (dir == Qt::RightToLeft) {
-        rect->adjust(-right, top, -left, bottom);
-    } else {
-        rect->adjust(left, top, right, bottom);
-    }
-}
-
-QRect QMacStyle::subElementRect(SubElement sr, const QStyleOption *opt,
-                                const QWidget *widget) const
-{
-    QRect rect;
-    int controlSize = getControlSize(opt, widget);
-
-    switch (sr) {
-    case SE_ItemViewItemText:
-        if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
-            int fw = proxy()->pixelMetric(PM_FocusFrameHMargin, opt, widget);
-            // We add the focusframeargin between icon and text in commonstyle
-            rect = QCommonStyle::subElementRect(sr, opt, widget);
-            if (vopt->features & QStyleOptionViewItemV2::HasDecoration)
-                rect.adjust(-fw, 0, 0, 0);
-        }
-        break;
-    case SE_ToolBoxTabContents:
-        rect = QCommonStyle::subElementRect(sr, opt, widget);
-        break;
-    case SE_PushButtonContents:
-        if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
-            // Unlike Carbon, we want the button to always be drawn inside its bounds.
-            // Therefore, the button is a bit smaller, so that even if it got focus,
-            // the focus 'shadow' will be inside. Adjust the content rect likewise.
-            HIThemeButtonDrawInfo bdi;
-            d->initHIThemePushButton(btn, widget, d->getDrawState(opt->state), &bdi);
-            HIRect contentRect = d->pushButtonContentBounds(btn, &bdi);
-            rect = qt_qrectForHIRect(contentRect);
-        }
-        break;
-    case SE_HeaderLabel:
-        if (qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
-            rect = QWindowsStyle::subElementRect(sr, opt, widget);
-            if (widget && widget->height() <= 22){
-                // We need to allow the text a bit more space when the header is
-                // small, otherwise it gets clipped:
-                rect.setY(0);
-                rect.setHeight(widget->height());
-            }
-        }
-        break;
-    case SE_ProgressBarGroove:
-    case SE_ProgressBarLabel:
-        break;
-    case SE_ProgressBarContents:
-        rect = opt->rect;
-        break;
-    case SE_TreeViewDisclosureItem: {
-        HIRect inRect = CGRectMake(opt->rect.x(), opt->rect.y(),
-                                   opt->rect.width(), opt->rect.height());
-        HIThemeButtonDrawInfo bdi;
-        bdi.version = qt_mac_hitheme_version;
-        bdi.state = kThemeStateActive;
-        bdi.kind = kThemeDisclosureButton;
-        bdi.value = kThemeDisclosureRight;
-        bdi.adornment = kThemeAdornmentNone;
-        HIRect contentRect;
-        HIThemeGetButtonContentBounds(&inRect, &bdi, &contentRect);
-        QCFType<HIShapeRef> shape;
-        HIRect outRect;
-        HIThemeGetButtonShape(&inRect, &bdi, &shape);
-        ptrHIShapeGetBounds(shape, &outRect);
-        rect = QRect(int(outRect.origin.x + DisclosureOffset), int(outRect.origin.y),
-                  int(contentRect.origin.x - outRect.origin.x + DisclosureOffset),
-                  int(outRect.size.height));
-        break;
-    }
-    case SE_TabWidgetLeftCorner:
-        if (const QStyleOptionTabWidgetFrame *twf
-                = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
-            switch (twf->shape) {
-            case QTabBar::RoundedNorth:
-            case QTabBar::TriangularNorth:
-                rect = QRect(QPoint(0, 0), twf->leftCornerWidgetSize);
-                break;
-            case QTabBar::RoundedSouth:
-            case QTabBar::TriangularSouth:
-                rect = QRect(QPoint(0, twf->rect.height() - twf->leftCornerWidgetSize.height()),
-                          twf->leftCornerWidgetSize);
-                break;
-            default:
-                break;
-            }
-            rect = visualRect(twf->direction, twf->rect, rect);
-        }
-        break;
-    case SE_TabWidgetRightCorner:
-        if (const QStyleOptionTabWidgetFrame *twf
-                = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
-            switch (twf->shape) {
-            case QTabBar::RoundedNorth:
-            case QTabBar::TriangularNorth:
-                rect = QRect(QPoint(twf->rect.width() - twf->rightCornerWidgetSize.width(), 0),
-                          twf->rightCornerWidgetSize);
-                break;
-            case QTabBar::RoundedSouth:
-            case QTabBar::TriangularSouth:
-                rect = QRect(QPoint(twf->rect.width() - twf->rightCornerWidgetSize.width(),
-                                 twf->rect.height() - twf->rightCornerWidgetSize.height()),
-                          twf->rightCornerWidgetSize);
-                break;
-            default:
-                break;
-            }
-            rect = visualRect(twf->direction, twf->rect, rect);
-        }
-        break;
-    case SE_TabWidgetTabContents:
-        rect = QWindowsStyle::subElementRect(sr, opt, widget);
-        if (const QStyleOptionTabWidgetFrame *twf
-                = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
-            if (twf->lineWidth != 0) {
-                switch (getTabDirection(twf->shape)) {
-                case kThemeTabNorth:
-                    rect.adjust(+1, +14, -1, -1);
-                    break;
-                case kThemeTabSouth:
-                    rect.adjust(+1, +1, -1, -14);
-                    break;
-                case kThemeTabWest:
-                    rect.adjust(+14, +1, -1, -1);
-                    break;
-                case kThemeTabEast:
-                    rect.adjust(+1, +1, -14, -1);
-                }
-            }
-        }
-        break;
-    case SE_LineEditContents:
-        rect = QWindowsStyle::subElementRect(sr, opt, widget);
-        if(widget->parentWidget() && qobject_cast<const QComboBox*>(widget->parentWidget()))
-            rect.adjust(-1, -2, 0, 0);
-        else
-            rect.adjust(-1, -1, 0, +1);
-        break;
-    case SE_CheckBoxLayoutItem:
-        rect = opt->rect;
-        if (controlSize == QAquaSizeLarge) {
-            setLayoutItemMargins(+2, +3, -9, -4, &rect, opt->direction);
-        } else if (controlSize == QAquaSizeSmall) {
-            setLayoutItemMargins(+1, +5, 0 /* fix */, -6, &rect, opt->direction);
-        } else {
-            setLayoutItemMargins(0, +7, 0 /* fix */, -6, &rect, opt->direction);
-        }
-        break;
-    case SE_ComboBoxLayoutItem:
-        if (widget && qobject_cast<QToolBar *>(widget->parentWidget())) {
-            // Do nothing, because QToolbar needs the entire widget rect.
-            // Otherwise it will be clipped. Equivalent to
-            // widget->setAttribute(Qt::WA_LayoutUsesWidgetRect), but without
-            // all the hassle.
-        } else {
-            rect = opt->rect;
-            if (controlSize == QAquaSizeLarge) {
-                rect.adjust(+3, +2, -3, -4);
-            } else if (controlSize == QAquaSizeSmall) {
-                setLayoutItemMargins(+2, +1, -3, -4, &rect, opt->direction);
-            } else {
-                setLayoutItemMargins(+1, 0, -2, 0, &rect, opt->direction);
-            }
-        }
-        break;
-    case SE_LabelLayoutItem:
-        rect = opt->rect;
-        setLayoutItemMargins(+1, 0 /* SHOULD be -1, done for alignment */, 0, 0 /* SHOULD be -1, done for alignment */, &rect, opt->direction);
-        break;
-    case SE_ProgressBarLayoutItem: {
-        rect = opt->rect;
-        int bottom = SIZE(3, 8, 8);
-        if (opt->state & State_Horizontal) {
-            rect.adjust(0, +1, 0, -bottom);
-        } else {
-            setLayoutItemMargins(+1, 0, -bottom, 0, &rect, opt->direction);
-        }
-        break;
-    }
-    case SE_PushButtonLayoutItem:
-        if (const QStyleOptionButton *buttonOpt
-                = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
-            if ((buttonOpt->features & QStyleOptionButton::Flat))
-                break;  // leave rect alone
-        }
-        rect = opt->rect;
-        if (controlSize == QAquaSizeLarge) {
-            rect.adjust(+6, +4, -6, -8);
-        } else if (controlSize == QAquaSizeSmall) {
-            rect.adjust(+5, +4, -5, -6);
-        } else {
-            rect.adjust(+1, 0, -1, -2);
-        }
-        break;
-    case SE_RadioButtonLayoutItem:
-        rect = opt->rect;
-        if (controlSize == QAquaSizeLarge) {
-            setLayoutItemMargins(+2, +2 /* SHOULD BE +3, done for alignment */,
-                                 0, -4 /* SHOULD BE -3, done for alignment */, &rect, opt->direction);
-        } else if (controlSize == QAquaSizeSmall) {
-            rect.adjust(0, +6, 0 /* fix */, -5);
-        } else {
-            rect.adjust(0, +6, 0 /* fix */, -7);
-        }
-        break;
-    case SE_SliderLayoutItem:
-        if (const QStyleOptionSlider *sliderOpt
-                = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
-            rect = opt->rect;
-            if (sliderOpt->tickPosition == QSlider::NoTicks) {
-                int above = SIZE(3, 0, 2);
-                int below = SIZE(4, 3, 0);
-                if (sliderOpt->orientation == Qt::Horizontal) {
-                    rect.adjust(0, +above, 0, -below);
-                } else {
-                    rect.adjust(+above, 0, -below, 0);  //### Seems that QSlider flip the position of the ticks in reverse mode.
-                }
-            } else if (sliderOpt->tickPosition == QSlider::TicksAbove) {
-                int below = SIZE(3, 2, 0);
-                if (sliderOpt->orientation == Qt::Horizontal) {
-                    rect.setHeight(rect.height() - below);
-                } else {
-                    rect.setWidth(rect.width() - below);
-                }
-            } else if (sliderOpt->tickPosition == QSlider::TicksBelow) {
-                int above = SIZE(3, 2, 0);
-                if (sliderOpt->orientation == Qt::Horizontal) {
-                    rect.setTop(rect.top() + above);
-                } else {
-                    rect.setLeft(rect.left() + above);
-                }
-            }
-        }
-        break;
-    case SE_FrameLayoutItem:
-        // hack because QStyleOptionFrameV2 doesn't have a frameStyle member
-        if (const QFrame *frame = qobject_cast<const QFrame *>(widget)) {
-            rect = opt->rect;
-            switch (frame->frameStyle() & QFrame::Shape_Mask) {
-            case QFrame::HLine:
-                rect.adjust(0, +1, 0, -1);
-                break;
-            case QFrame::VLine:
-                rect.adjust(+1, 0, -1, 0);
-                break;
-            default:
-                ;
-            }
-        }
-        break;
-    case SE_GroupBoxLayoutItem:
-        rect = opt->rect;
-        if (const QStyleOptionGroupBox *groupBoxOpt =
-                qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
-            /*
-                AHIG is very inconsistent when it comes to group boxes.
-                Basically, we make sure that (non-checkable) group boxes
-                and tab widgets look good when laid out side by side.
-            */
-            if (groupBoxOpt->subControls & (QStyle::SC_GroupBoxCheckBox
-                                            | QStyle::SC_GroupBoxLabel)) {
-                int delta;
-                if (groupBoxOpt->subControls & QStyle::SC_GroupBoxCheckBox) {
-                    delta = SIZE(8, 4, 4);       // guess
-                } else {
-                    delta = SIZE(15, 12, 12);    // guess
-                }
-                rect.setTop(rect.top() + delta);
-            }
-        }
-        rect.setBottom(rect.bottom() - 1);
-        break;
-    case SE_TabWidgetLayoutItem:
-        if (const QStyleOptionTabWidgetFrame *tabWidgetOpt =
-                qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
-            /*
-                AHIG specifies "12 or 14" as the distance from the window
-                edge. We choose 14 and since the default top margin is 20,
-                the overlap is 6.
-            */
-            rect = tabWidgetOpt->rect;
-            if (tabWidgetOpt->shape == QTabBar::RoundedNorth)
-                rect.setTop(rect.top() + SIZE(6 /* AHIG */, 3 /* guess */, 2 /* AHIG */));
-        }
-        break;
-#ifndef QT_NO_DOCKWIDGET
-        case SE_DockWidgetCloseButton:
-        case SE_DockWidgetFloatButton:
-        case SE_DockWidgetTitleBarText:
-        case SE_DockWidgetIcon: {
-            int iconSize = proxy()->pixelMetric(PM_SmallIconSize, opt, widget);
-            int buttonMargin = proxy()->pixelMetric(PM_DockWidgetTitleBarButtonMargin, opt, widget);
-            QRect srect = opt->rect;
-
-            const QStyleOptionDockWidget *dwOpt
-                = qstyleoption_cast<const QStyleOptionDockWidget*>(opt);
-            bool canClose = dwOpt == 0 ? true : dwOpt->closable;
-            bool canFloat = dwOpt == 0 ? false : dwOpt->floatable;
-            const QStyleOptionDockWidgetV2 *v2
-                = qstyleoption_cast<const QStyleOptionDockWidgetV2*>(opt);
-            bool verticalTitleBar = v2 == 0 ? false : v2->verticalTitleBar;
-
-            // If this is a vertical titlebar, we transpose and work as if it was
-            // horizontal, then transpose again.
-            if (verticalTitleBar) {
-                QSize size = srect.size();
-                size.transpose();
-                srect.setSize(size);
-            }
-
-            do {
-                int right = srect.right();
-                int left = srect.left();
-
-                QRect closeRect;
-                if (canClose) {
-                    QSize sz = standardIcon(QStyle::SP_TitleBarCloseButton,
-                                            opt, widget).actualSize(QSize(iconSize, iconSize));
-                    sz += QSize(buttonMargin, buttonMargin);
-                    if (verticalTitleBar)
-                        sz.transpose();
-                    closeRect = QRect(left,
-                                      srect.center().y() - sz.height()/2,
-                                      sz.width(), sz.height());
-                    left = closeRect.right() + 1;
-                }
-                if (sr == SE_DockWidgetCloseButton) {
-                    rect = closeRect;
-                    break;
-                }
-
-                QRect floatRect;
-                if (canFloat) {
-                    QSize sz = standardIcon(QStyle::SP_TitleBarNormalButton,
-                                            opt, widget).actualSize(QSize(iconSize, iconSize));
-                    sz += QSize(buttonMargin, buttonMargin);
-                    if (verticalTitleBar)
-                        sz.transpose();
-                    floatRect = QRect(left,
-                                      srect.center().y() - sz.height()/2,
-                                      sz.width(), sz.height());
-                    left = floatRect.right() + 1;
-                }
-                if (sr == SE_DockWidgetFloatButton) {
-                    rect = floatRect;
-                    break;
-                }
-
-                QRect iconRect;
-                if (const QDockWidget *dw = qobject_cast<const QDockWidget*>(widget)) {
-                    QIcon icon;
-                    if (dw->isFloating())
-                        icon = dw->windowIcon();
-                    if (!icon.isNull()
-                        && icon.cacheKey() != QApplication::windowIcon().cacheKey()) {
-                        QSize sz = icon.actualSize(QSize(rect.height(), rect.height()));
-                        if (verticalTitleBar)
-                            sz.transpose();
-                        iconRect = QRect(right - sz.width(), srect.center().y() - sz.height()/2,
-                                         sz.width(), sz.height());
-                        right = iconRect.left() - 1;
-                    }
-                }
-                if (sr == SE_DockWidgetIcon) {
-                    rect = iconRect;
-                    break;
-                }
-
-                QRect textRect = QRect(left, srect.top(),
-                                       right - left, srect.height());
-                if (sr == SE_DockWidgetTitleBarText) {
-                    rect = textRect;
-                    break;
-                }
-            } while (false);
-
-            if (verticalTitleBar) {
-                rect = QRect(srect.left() + rect.top() - srect.top(),
-                          srect.top() + srect.right() - rect.right(),
-                          rect.height(), rect.width());
-            } else {
-                rect = visualRect(opt->direction, srect, rect);
-            }
-            break;
-        }
-#endif
-    default:
-        rect = QWindowsStyle::subElementRect(sr, opt, widget);
-        break;
-    }
-    return rect;
-}
-
-static inline void drawToolbarButtonArrow(const QRect &toolButtonRect, ThemeDrawState tds, CGContextRef cg)
-{
-    QRect arrowRect = QRect(toolButtonRect.right() - 9, toolButtonRect.bottom() - 9, 7, 5);
-    HIThemePopupArrowDrawInfo padi;
-    padi.version = qt_mac_hitheme_version;
-    padi.state = tds;
-    padi.orientation = kThemeArrowDown;
-    padi.size = kThemeArrow7pt;
-    HIRect hirect = qt_hirectForQRect(arrowRect);
-    HIThemeDrawPopupArrow(&hirect, &padi, cg, kHIThemeOrientationNormal);
-}
-
-void QMacStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
-                                   const QWidget *widget) const
-{
-    ThemeDrawState tds = d->getDrawState(opt->state);
-    QMacCGContext cg(p);
-    switch (cc) {
-    case CC_Slider:
-    case CC_ScrollBar:
-        if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
-            HIThemeTrackDrawInfo tdi;
-            d->getSliderInfo(cc, slider, &tdi, widget);
-            if (slider->state & State_Sunken) {
-                if (cc == CC_Slider) {
-                    if (slider->activeSubControls == SC_SliderHandle)
-                        tdi.trackInfo.slider.pressState = kThemeThumbPressed;
-                    else if (slider->activeSubControls == SC_SliderGroove)
-                        tdi.trackInfo.slider.pressState = kThemeLeftTrackPressed;
-                } else {
-                    if (slider->activeSubControls == SC_ScrollBarSubLine
-                        || slider->activeSubControls == SC_ScrollBarAddLine) {
-                        // This test looks complex but it basically boils down
-                        // to the following: The "RTL look" on the mac also
-                        // changed the directions of the controls, that's not
-                        // what people expect (an arrow is an arrow), so we
-                        // kind of fake and say the opposite button is hit.
-                        // This works great, up until 10.4 which broke the
-                        // scroll bars, so I also have actually do something
-                        // similar when I have an upside down scroll bar
-                        // because on Tiger I only "fake" the reverse stuff.
-                        bool reverseHorizontal = (slider->direction == Qt::RightToLeft
-                                                  && slider->orientation == Qt::Horizontal);
-                        if ((reverseHorizontal
-                             && slider->activeSubControls == SC_ScrollBarAddLine)
-                            || (!reverseHorizontal
-                                && slider->activeSubControls == SC_ScrollBarSubLine)) {
-                            tdi.trackInfo.scrollbar.pressState = kThemeRightInsideArrowPressed
-                                                                 | kThemeLeftOutsideArrowPressed;
-                        } else {
-                            tdi.trackInfo.scrollbar.pressState = kThemeLeftInsideArrowPressed
-                                                                 | kThemeRightOutsideArrowPressed;
-                        }
-                    } else if (slider->activeSubControls == SC_ScrollBarAddPage) {
-                        tdi.trackInfo.scrollbar.pressState = kThemeRightTrackPressed;
-                    } else if (slider->activeSubControls == SC_ScrollBarSubPage) {
-                        tdi.trackInfo.scrollbar.pressState = kThemeLeftTrackPressed;
-                    } else if (slider->activeSubControls == SC_ScrollBarSlider) {
-                        tdi.trackInfo.scrollbar.pressState = kThemeThumbPressed;
-                    }
-                }
-            }
-            HIRect macRect;
-            bool tracking = slider->sliderPosition == slider->sliderValue;
-            if (!tracking) {
-                // Small optimization, the same as q->subControlRect
-                QCFType<HIShapeRef> shape;
-                HIThemeGetTrackThumbShape(&tdi, &shape);
-                ptrHIShapeGetBounds(shape, &macRect);
-                tdi.value = slider->sliderValue;
-            }
-
-            // Remove controls from the scroll bar if it is to short to draw them correctly.
-            // This is done in two stages: first the thumb indicator is removed when it is
-            // no longer possible to move it, second the up/down buttons are removed when
-            // there is not enough space for them.
-            if (cc == CC_ScrollBar) {
-                const int scrollBarLength = (slider->orientation == Qt::Horizontal)
-                    ? slider->rect.width() : slider->rect.height();
-                const QMacStyle::WidgetSizePolicy sizePolicy = widgetSizePolicy(widget);
-                if (scrollBarLength < scrollButtonsCutoffSize(thumbIndicatorCutoff, sizePolicy))
-                    tdi.attributes &= ~kThemeTrackShowThumb;
-                if (scrollBarLength < scrollButtonsCutoffSize(scrollButtonsCutoff, sizePolicy))
-                    tdi.enableState = kThemeTrackNothingToScroll;
-            } else {
-                if (!(slider->subControls & SC_SliderHandle))
-                    tdi.attributes &= ~kThemeTrackShowThumb;
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-                if (!(slider->subControls & SC_SliderGroove))
-                    tdi.attributes |= kThemeTrackHideTrack;
-#endif
-            }
-
-            HIThemeDrawTrack(&tdi, tracking ? 0 : &macRect, cg,
-                             kHIThemeOrientationNormal);
-            if (cc == CC_Slider && slider->subControls & SC_SliderTickmarks) {
-                if (qt_mac_is_metal(widget)) {
-                    if (tdi.enableState == kThemeTrackInactive)
-                        tdi.enableState = kThemeTrackActive;  // Looks more Cocoa-like
-                }
-                int interval = slider->tickInterval;
-                if (interval == 0) {
-                    interval = slider->pageStep;
-                    if (interval == 0)
-                        interval = slider->singleStep;
-                    if (interval == 0)
-                        interval = 1;
-                }
-                int numMarks = 1 + ((slider->maximum - slider->minimum) / interval);
-
-                if (tdi.trackInfo.slider.thumbDir == kThemeThumbPlain) {
-                    // They asked for both, so we'll give it to them.
-                    tdi.trackInfo.slider.thumbDir = kThemeThumbDownward;
-                    HIThemeDrawTrackTickMarks(&tdi, numMarks,
-                                              cg,
-                                              kHIThemeOrientationNormal);
-                    tdi.trackInfo.slider.thumbDir = kThemeThumbUpward;
-                    HIThemeDrawTrackTickMarks(&tdi, numMarks,
-                                              cg,
-                                               kHIThemeOrientationNormal);
-                } else {
-                    HIThemeDrawTrackTickMarks(&tdi, numMarks,
-                                              cg,
-                                              kHIThemeOrientationNormal);
-
-                }
-            }
-        }
-        break;
-    case CC_SpinBox:
-        if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
-            QStyleOptionSpinBox newSB = *sb;
-            if (sb->frame && (sb->subControls & SC_SpinBoxFrame)) {
-                SInt32 frame_size;
-                GetThemeMetric(kThemeMetricEditTextFrameOutset, &frame_size);
-
-                QRect lineeditRect = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxEditField, widget);
-                lineeditRect.adjust(-frame_size, -frame_size, +frame_size, +frame_size);
-
-                HIThemeFrameDrawInfo fdi;
-                fdi.version = qt_mac_hitheme_version;
-                fdi.state = ((sb->state & State_ReadOnly) || !(sb->state & State_Enabled)) ? kThemeStateInactive : kThemeStateActive;
-                fdi.kind = kHIThemeFrameTextFieldSquare;
-                fdi.isFocused = false;
-                HIRect hirect = qt_hirectForQRect(lineeditRect);
-                HIThemeDrawFrame(&hirect, &fdi, cg, kHIThemeOrientationNormal);
-            }
-            if (sb->subControls & (SC_SpinBoxUp | SC_SpinBoxDown)) {
-                HIThemeButtonDrawInfo bdi;
-                bdi.version = qt_mac_hitheme_version;
-                QAquaWidgetSize aquaSize = d->aquaSizeConstrain(opt, widget);
-                switch (aquaSize) {
-                    case QAquaSizeUnknown:
-                    case QAquaSizeLarge:
-                        bdi.kind = kThemeIncDecButton;
-                        break;
-                    case QAquaSizeMini:
-                        bdi.kind = kThemeIncDecButtonMini;
-                        break;
-                    case QAquaSizeSmall:
-                        bdi.kind = kThemeIncDecButtonSmall;
-                        break;
-                }
-                if (!(sb->stepEnabled & (QAbstractSpinBox::StepUpEnabled
-                                        | QAbstractSpinBox::StepDownEnabled)))
-                    tds = kThemeStateUnavailable;
-                if (sb->activeSubControls == SC_SpinBoxDown
-                    && (sb->state & State_Sunken))
-                    tds = kThemeStatePressedDown;
-                else if (sb->activeSubControls == SC_SpinBoxUp
-                         && (sb->state & State_Sunken))
-                    tds = kThemeStatePressedUp;
-                bdi.state = tds;
-                if (!(sb->state & State_Active)
-                        && sb->palette.currentColorGroup() == QPalette::Active
-                        && tds == kThemeStateInactive)
-                    bdi.state = kThemeStateActive;
-                bdi.value = kThemeButtonOff;
-                bdi.adornment = kThemeAdornmentNone;
-
-                QRect updown = proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxUp, widget);
-
-                updown |= proxy()->subControlRect(CC_SpinBox, sb, SC_SpinBoxDown, widget);
-                HIRect newRect = qt_hirectForQRect(updown);
-                QRect off_rct;
-                HIRect outRect;
-                HIThemeGetButtonBackgroundBounds(&newRect, &bdi, &outRect);
-                off_rct.setRect(int(newRect.origin.x - outRect.origin.x),
-                                int(newRect.origin.y - outRect.origin.y),
-                                int(outRect.size.width - newRect.size.width),
-                                int(outRect.size.height - newRect.size.height));
-
-                newRect = qt_hirectForQRect(updown, off_rct);
-                HIThemeDrawButton(&newRect, &bdi, cg, kHIThemeOrientationNormal, 0);
-            }
-        }
-        break;
-    case CC_ComboBox:
-        if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)){
-            HIThemeButtonDrawInfo bdi;
-            d->initComboboxBdi(combo, &bdi, widget, d->getDrawState(opt->state));
-            bool drawColorless = combo->palette.currentColorGroup() == QPalette::Active && tds == kThemeStateInactive;
-            if (!drawColorless)
-                QMacStylePrivate::drawCombobox(qt_hirectForQRect(combo->rect), bdi, p);
-            else
-                d->drawColorlessButton(qt_hirectForQRect(combo->rect), &bdi, p, opt);
-        }
-        break;
-    case CC_TitleBar:
-        if (const QStyleOptionTitleBar *titlebar
-                = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
-            if (titlebar->state & State_Active) {
-                if (titlebar->titleBarState & State_Active)
-                    tds = kThemeStateActive;
-                else
-                    tds = kThemeStateInactive;
-            } else {
-                tds = kThemeStateInactive;
-            }
-
-            HIThemeWindowDrawInfo wdi;
-            wdi.version = qt_mac_hitheme_version;
-            wdi.state = tds;
-            wdi.windowType = QtWinType;
-            wdi.titleHeight = titlebar->rect.height();
-            wdi.titleWidth = titlebar->rect.width();
-            wdi.attributes = kThemeWindowHasTitleText;
-            // It seems HIThemeDrawTitleBarWidget is not able to draw a dirty
-            // close button, so use HIThemeDrawWindowFrame instead.
-            if (widget && widget->isWindowModified() && titlebar->subControls & SC_TitleBarCloseButton)
-                wdi.attributes |= kThemeWindowHasCloseBox | kThemeWindowHasDirty;
-
-            HIRect titleBarRect;
-            HIRect tmpRect = qt_hirectForQRect(titlebar->rect);
-            {
-                QCFType<HIShapeRef> titleRegion;
-                QRect newr = titlebar->rect.adjusted(0, 0, 2, 0);
-                HIThemeGetWindowShape(&tmpRect, &wdi, kWindowTitleBarRgn, &titleRegion);
-                ptrHIShapeGetBounds(titleRegion, &tmpRect);
-                newr.translate(newr.x() - int(tmpRect.origin.x), newr.y() - int(tmpRect.origin.y));
-                titleBarRect = qt_hirectForQRect(newr);
-            }
-            HIThemeDrawWindowFrame(&titleBarRect, &wdi, cg, kHIThemeOrientationNormal, 0);
-            if (titlebar->subControls & (SC_TitleBarCloseButton
-                                         | SC_TitleBarMaxButton
-                                         | SC_TitleBarMinButton
-                                         | SC_TitleBarNormalButton)) {
-                HIThemeWindowWidgetDrawInfo wwdi;
-                wwdi.version = qt_mac_hitheme_version;
-                wwdi.widgetState = tds;
-                if (titlebar->state & State_MouseOver)
-                    wwdi.widgetState = kThemeStateRollover;
-                wwdi.windowType = QtWinType;
-                wwdi.attributes = wdi.attributes | kThemeWindowHasFullZoom | kThemeWindowHasCloseBox | kThemeWindowHasCollapseBox;
-                wwdi.windowState = wdi.state;
-                wwdi.titleHeight = wdi.titleHeight;
-                wwdi.titleWidth = wdi.titleWidth;
-                ThemeDrawState savedControlState = wwdi.widgetState;
-                uint sc = SC_TitleBarMinButton;
-                ThemeTitleBarWidget tbw = kThemeWidgetCollapseBox;
-                bool active = titlebar->state & State_Active;
-                if (qMacVersion() < QSysInfo::MV_10_6) {
-                    int border = 2;
-                    titleBarRect.origin.x += border;
-                    titleBarRect.origin.y -= border;
-                }
-
-                while (sc <= SC_TitleBarCloseButton) {
-                    if (sc & titlebar->subControls) {
-                        uint tmp = sc;
-                        wwdi.widgetState = savedControlState;
-                        wwdi.widgetType = tbw;
-                        if (sc == SC_TitleBarMinButton)
-                            tmp |= SC_TitleBarNormalButton;
-                        if (active && (titlebar->activeSubControls & tmp)
-                                && (titlebar->state & State_Sunken))
-                            wwdi.widgetState = kThemeStatePressed;
-                        // Draw all sub controllers except the dirty close button
-                        // (it is already handled by HIThemeDrawWindowFrame).
-                        if (!(widget && widget->isWindowModified() && tbw == kThemeWidgetCloseBox)) {
-                            HIThemeDrawTitleBarWidget(&titleBarRect, &wwdi, cg, kHIThemeOrientationNormal);
-                            p->paintEngine()->syncState();
-                        }
-                    }
-                    sc = sc << 1;
-                    tbw = tbw >> 1;
-                }
-            }
-            p->paintEngine()->syncState();
-            if (titlebar->subControls & SC_TitleBarLabel) {
-                int iw = 0;
-                if (!titlebar->icon.isNull()) {
-                    QCFType<HIShapeRef> titleRegion2;
-                    HIThemeGetWindowShape(&titleBarRect, &wdi, kWindowTitleProxyIconRgn,
-                                          &titleRegion2);
-                    ptrHIShapeGetBounds(titleRegion2, &tmpRect);
-                    if (tmpRect.size.width != 1) {
-                        int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
-                        iw = titlebar->icon.actualSize(QSize(iconExtent, iconExtent)).width();
-                    }
-                }
-                if (!titlebar->text.isEmpty()) {
-                    p->save();
-                    QCFType<HIShapeRef> titleRegion3;
-                    HIThemeGetWindowShape(&titleBarRect, &wdi, kWindowTitleTextRgn, &titleRegion3);
-                    ptrHIShapeGetBounds(titleRegion3, &tmpRect);
-                    p->setClipRect(qt_qrectForHIRect(tmpRect));
-                    QRect br = p->clipRegion().boundingRect();
-                    int x = br.x(),
-                    y = br.y() + (titlebar->rect.height() / 2 - p->fontMetrics().height() / 2);
-                    if (br.width() <= (p->fontMetrics().width(titlebar->text) + iw * 2))
-                        x += iw;
-                    else
-                        x += br.width() / 2 - p->fontMetrics().width(titlebar->text) / 2;
-                    if (iw)
-                        p->drawPixmap(x - iw, y, 
-                                      titlebar->icon.pixmap(proxy()->pixelMetric(PM_SmallIconSize), QIcon::Normal));
-                    drawItemText(p, br, Qt::AlignCenter, opt->palette, tds == kThemeStateActive,
-                                    titlebar->text, QPalette::Text);
-                    p->restore();
-                }
-            }
-        }
-        break;
-    case CC_GroupBox:
-        if (const QStyleOptionGroupBox *groupBox
-                = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
-
-            QStyleOptionGroupBox groupBoxCopy(*groupBox);
-            if ((widget && !widget->testAttribute(Qt::WA_SetFont))
-                    && QApplication::desktopSettingsAware())
-                groupBoxCopy.subControls = groupBoxCopy.subControls & ~SC_GroupBoxLabel;
-            QWindowsStyle::drawComplexControl(cc, &groupBoxCopy, p, widget);
-            if (groupBoxCopy.subControls != groupBox->subControls) {
-                bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
-                p->save();
-                CGContextSetShouldAntialias(cg, true);
-                CGContextSetShouldSmoothFonts(cg, true);
-                HIThemeTextInfo tti;
-                tti.version = qt_mac_hitheme_version;
-                tti.state = tds;
-                QColor textColor = groupBox->palette.windowText().color();
-                CGFloat colorComp[] = { textColor.redF(), textColor.greenF(),
-                                      textColor.blueF(), textColor.alphaF() };
-                CGContextSetFillColorSpace(cg, QCoreGraphicsPaintEngine::macGenericColorSpace());
-                CGContextSetFillColor(cg, colorComp);
-                tti.fontID = checkable ? kThemeSystemFont : kThemeSmallSystemFont;
-                tti.horizontalFlushness = kHIThemeTextHorizontalFlushCenter;
-                tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
-                tti.options = kHIThemeTextBoxOptionNone;
-                tti.truncationPosition = kHIThemeTextTruncationNone;
-                tti.truncationMaxLines = 1 + groupBox->text.count(QLatin1Char('\n'));
-                QCFString groupText = qt_mac_removeMnemonics(groupBox->text);
-                QRect r = proxy()->subControlRect(CC_GroupBox, groupBox, SC_GroupBoxLabel, widget);
-                HIRect bounds = qt_hirectForQRect(r);
-                HIThemeDrawTextBox(groupText, &bounds, &tti, cg, kHIThemeOrientationNormal);
-                p->restore();
-            }
-        }
-        break;
-    case CC_ToolButton:
-        if (const QStyleOptionToolButton *tb
-                = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
-            if (widget && qobject_cast<QToolBar *>(widget->parentWidget())) {
-                if (tb->subControls & SC_ToolButtonMenu) {
-                    QStyleOption arrowOpt(0);
-                    arrowOpt.rect = proxy()->subControlRect(cc, tb, SC_ToolButtonMenu, widget);
-                    arrowOpt.rect.setY(arrowOpt.rect.y() + arrowOpt.rect.height() / 2);
-                    arrowOpt.rect.setHeight(arrowOpt.rect.height() / 2);
-                    arrowOpt.state = tb->state;
-                    arrowOpt.palette = tb->palette;
-                    proxy()->drawPrimitive(PE_IndicatorArrowDown, &arrowOpt, p, widget);
-                } else if ((tb->features & QStyleOptionToolButton::HasMenu)
-                            && (tb->toolButtonStyle != Qt::ToolButtonTextOnly && !tb->icon.isNull())) {
-                    drawToolbarButtonArrow(tb->rect, tds, cg);
-                }
-                if (tb->state & State_On) {
-                    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-                        static QPixmap pm(QLatin1String(":/trolltech/mac/style/images/leopard-unified-toolbar-on.png"));
-                        QStyleHelper::drawBorderPixmap(pm, p, tb->rect, 2, 2, 2, 2);
-                    } else {
-                        QPen oldPen = p->pen();
-                        p->setPen(QColor(0, 0, 0, 0x3a));
-                        p->fillRect(tb->rect.adjusted(1, 1, -1, -1), QColor(0, 0, 0, 0x12));
-                        p->drawLine(tb->rect.left() + 1, tb->rect.top(),
-                                    tb->rect.right() - 1, tb->rect.top());
-                        p->drawLine(tb->rect.left() + 1, tb->rect.bottom(),
-                                    tb->rect.right() - 1, tb->rect.bottom());
-                        p->drawLine(tb->rect.topLeft(), tb->rect.bottomLeft());
-                        p->drawLine(tb->rect.topRight(), tb->rect.bottomRight());
-                        p->setPen(oldPen);
-                    }
-                }
-                proxy()->drawControl(CE_ToolButtonLabel, opt, p, widget);
-            } else {
-                ThemeButtonKind bkind = kThemeBevelButton;
-                switch (d->aquaSizeConstrain(opt, widget)) {
-                case QAquaSizeUnknown:
-                case QAquaSizeLarge:
-                    bkind = kThemeBevelButton;
-                    break;
-                case QAquaSizeMini:
-                case QAquaSizeSmall:
-                    bkind = kThemeSmallBevelButton;
-                    break;
-                }
-
-                QRect button, menuarea;
-                button   = proxy()->subControlRect(cc, tb, SC_ToolButton, widget);
-                menuarea = proxy()->subControlRect(cc, tb, SC_ToolButtonMenu, widget);
-                State bflags = tb->state,
-                mflags = tb->state;
-                if (tb->subControls & SC_ToolButton)
-                    bflags |= State_Sunken;
-                if (tb->subControls & SC_ToolButtonMenu)
-                    mflags |= State_Sunken;
-
-                if (tb->subControls & SC_ToolButton) {
-                    if (bflags & (State_Sunken | State_On | State_Raised)) {
-                        HIThemeButtonDrawInfo bdi;
-                        bdi.version = qt_mac_hitheme_version;
-                        bdi.state = tds;
-                        bdi.adornment = kThemeAdornmentNone;
-                        bdi.kind = bkind;
-                        bdi.value = kThemeButtonOff;
-                        if (tb->state & State_HasFocus)
-                            bdi.adornment = kThemeAdornmentFocus;
-                        if (tb->state & State_Sunken)
-                            bdi.state = kThemeStatePressed;
-                        if (tb->state & State_On)
-                            bdi.value = kThemeButtonOn;
-
-                        QRect off_rct(0, 0, 0, 0);
-                        HIRect myRect, macRect;
-                        myRect = CGRectMake(tb->rect.x(), tb->rect.y(),
-                                            tb->rect.width(), tb->rect.height());
-                        HIThemeGetButtonBackgroundBounds(&myRect, &bdi, &macRect);
-                        off_rct.setRect(int(myRect.origin.x - macRect.origin.x),
-                                        int(myRect.origin.y - macRect.origin.y),
-                                        int(macRect.size.width - myRect.size.width),
-                                        int(macRect.size.height - myRect.size.height));
-
-                        myRect = qt_hirectForQRect(button, off_rct);
-                        HIThemeDrawButton(&myRect, &bdi, cg, kHIThemeOrientationNormal, 0);
-                    }
-                }
-
-                if (tb->subControls & SC_ToolButtonMenu) {
-                    HIThemeButtonDrawInfo bdi;
-                    bdi.version = qt_mac_hitheme_version;
-                    bdi.state = tds;
-                    bdi.value = kThemeButtonOff;
-                    bdi.adornment = kThemeAdornmentNone;
-                    bdi.kind = bkind;
-                    if (tb->state & State_HasFocus)
-                        bdi.adornment = kThemeAdornmentFocus;
-                    if (tb->state & (State_On | State_Sunken)
-                                     || (tb->activeSubControls & SC_ToolButtonMenu))
-                        bdi.state = kThemeStatePressed;
-                    HIRect hirect = qt_hirectForQRect(menuarea);
-                    HIThemeDrawButton(&hirect, &bdi, cg, kHIThemeOrientationNormal, 0);
-                    QRect r(menuarea.x() + ((menuarea.width() / 2) - 3), menuarea.height() - 8, 8, 8);
-                    HIThemePopupArrowDrawInfo padi;
-                    padi.version = qt_mac_hitheme_version;
-                    padi.state = tds;
-                    padi.orientation = kThemeArrowDown;
-                    padi.size = kThemeArrow7pt;
-                    hirect = qt_hirectForQRect(r);
-                    HIThemeDrawPopupArrow(&hirect, &padi, cg, kHIThemeOrientationNormal);
-                } else if (tb->features & QStyleOptionToolButton::HasMenu) {
-                    drawToolbarButtonArrow(tb->rect, tds, cg);
-                }
-                QRect buttonRect = proxy()->subControlRect(CC_ToolButton, tb, SC_ToolButton, widget);
-                int fw = proxy()->pixelMetric(PM_DefaultFrameWidth, opt, widget);
-                QStyleOptionToolButton label = *tb;
-                label.rect = buttonRect.adjusted(fw, fw, -fw, -fw);
-                proxy()->drawControl(CE_ToolButtonLabel, &label, p, widget);
-            }
-        }
-        break;
-    case CC_Dial:
-        if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(opt))
-            QStyleHelper::drawDial(dial, p);
-        break;
-    default:
-        QWindowsStyle::drawComplexControl(cc, opt, p, widget);
-        break;
-    }
-}
-
-QStyle::SubControl QMacStyle::hitTestComplexControl(ComplexControl cc,
-                                                    const QStyleOptionComplex *opt,
-                                                    const QPoint &pt, const QWidget *widget) const
-{
-    SubControl sc = QStyle::SC_None;
-    switch (cc) {
-    case CC_ComboBox:
-        if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
-            sc = QWindowsStyle::hitTestComplexControl(cc, cmb, pt, widget);
-            if (!cmb->editable && sc != QStyle::SC_None)
-                sc = SC_ComboBoxArrow;  // A bit of a lie, but what we want
-        }
-        break;
-    case CC_Slider:
-        if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
-            HIThemeTrackDrawInfo tdi;
-            d->getSliderInfo(cc, slider, &tdi, widget);
-            ControlPartCode part;
-            HIPoint pos = CGPointMake(pt.x(), pt.y());
-            if (HIThemeHitTestTrack(&tdi, &pos, &part)) {
-                if (part == kControlPageUpPart || part == kControlPageDownPart)
-                    sc = SC_SliderGroove;
-                else
-                    sc = SC_SliderHandle;
-            }
-        }
-        break;
-    case CC_ScrollBar:
-        if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
-            HIScrollBarTrackInfo sbi;
-            sbi.version = qt_mac_hitheme_version;
-            if (!(sb->state & State_Active))
-                sbi.enableState = kThemeTrackInactive;
-            else if (sb->state & State_Enabled)
-                sbi.enableState = kThemeTrackActive;
-            else
-                sbi.enableState = kThemeTrackDisabled;
-
-            // The arrow buttons are not drawn if the scroll bar is to short,
-            // exclude them from the hit test.
-            const int scrollBarLength = (sb->orientation == Qt::Horizontal)
-                ? sb->rect.width() : sb->rect.height();
-            if (scrollBarLength < scrollButtonsCutoffSize(scrollButtonsCutoff, widgetSizePolicy(widget)))
-                sbi.enableState = kThemeTrackNothingToScroll;
-
-            sbi.viewsize = sb->pageStep;
-            HIPoint pos = CGPointMake(pt.x(), pt.y());
-
-            HIRect macSBRect = qt_hirectForQRect(sb->rect);
-            ControlPartCode part;
-            bool reverseHorizontal = (sb->direction == Qt::RightToLeft
-                                      && sb->orientation == Qt::Horizontal
-                                      && (!sb->upsideDown ||
-                                          (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4
-                                                      && sb->upsideDown)));
-            if (HIThemeHitTestScrollBarArrows(&macSBRect, &sbi, sb->orientation == Qt::Horizontal,
-                        &pos, 0, &part)) {
-                if (part == kControlUpButtonPart)
-                    sc = reverseHorizontal ? SC_ScrollBarAddLine : SC_ScrollBarSubLine;
-                else if (part == kControlDownButtonPart)
-                    sc = reverseHorizontal ? SC_ScrollBarSubLine : SC_ScrollBarAddLine;
-            } else {
-                HIThemeTrackDrawInfo tdi;
-                d->getSliderInfo(cc, sb, &tdi, widget);
-                if(tdi.enableState == kThemeTrackInactive)
-                    tdi.enableState = kThemeTrackActive;
-                if (HIThemeHitTestTrack(&tdi, &pos, &part)) {
-                    if (part == kControlPageUpPart)
-                        sc = reverseHorizontal ? SC_ScrollBarAddPage
-                                               : SC_ScrollBarSubPage;
-                    else if (part == kControlPageDownPart)
-                        sc = reverseHorizontal ? SC_ScrollBarSubPage
-                                               : SC_ScrollBarAddPage;
-                    else
-                        sc = SC_ScrollBarSlider;
-                }
-            }
-        }
-        break;
-/*
-    I don't know why, but we only get kWindowContentRgn here, which isn't what we want at all.
-    It would be very nice if this would work.
-    case QStyle::CC_TitleBar:
-        if (const QStyleOptionTitleBar *tbar = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
-            HIThemeWindowDrawInfo wdi;
-            memset(&wdi, 0, sizeof(wdi));
-            wdi.version = qt_mac_hitheme_version;
-            wdi.state = kThemeStateActive;
-            wdi.windowType = QtWinType;
-            wdi.titleWidth = tbar->rect.width();
-            wdi.titleHeight = tbar->rect.height();
-            if (tbar->titleBarState)
-                wdi.attributes |= kThemeWindowHasFullZoom | kThemeWindowHasCloseBox
-                                  | kThemeWindowHasCollapseBox;
-            else if (tbar->titleBarFlags & Qt::WindowSystemMenuHint)
-                wdi.attributes |= kThemeWindowHasCloseBox;
-            QRect tmpRect = tbar->rect;
-            tmpRect.setHeight(tmpRect.height() + 100);
-            HIRect hirect = qt_hirectForQRect(tmpRect);
-            WindowRegionCode hit;
-            HIPoint hipt = CGPointMake(pt.x(), pt.y());
-            if (HIThemeGetWindowRegionHit(&hirect, &wdi, &hipt, &hit)) {
-                switch (hit) {
-                case kWindowCloseBoxRgn:
-                    sc = QStyle::SC_TitleBarCloseButton;
-                    break;
-                case kWindowCollapseBoxRgn:
-                    sc = QStyle::SC_TitleBarMinButton;
-                    break;
-                case kWindowZoomBoxRgn:
-                    sc = QStyle::SC_TitleBarMaxButton;
-                    break;
-                case kWindowTitleTextRgn:
-                    sc = QStyle::SC_TitleBarLabel;
-                    break;
-                default:
-                    qDebug("got something else %d", hit);
-                    break;
-                }
-            }
-        }
-        break;
-*/
-    default:
-        sc = QWindowsStyle::hitTestComplexControl(cc, opt, pt, widget);
-        break;
-    }
-    return sc;
-}
-
-QRect QMacStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
-                                const QWidget *widget) const
-{
-    QRect ret;
-    switch (cc) {
-    case CC_Slider:
-    case CC_ScrollBar:
-        if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
-            HIThemeTrackDrawInfo tdi;
-            d->getSliderInfo(cc, slider, &tdi, widget);
-            HIRect macRect;
-            QCFType<HIShapeRef> shape;
-            bool scrollBar = cc == CC_ScrollBar;
-            if ((scrollBar && sc == SC_ScrollBarSlider)
-                || (!scrollBar && sc == SC_SliderHandle)) {
-                HIThemeGetTrackThumbShape(&tdi, &shape);
-                ptrHIShapeGetBounds(shape, &macRect);
-            } else if (!scrollBar && sc == SC_SliderGroove) {
-                HIThemeGetTrackBounds(&tdi, &macRect);
-            } else if (sc == SC_ScrollBarGroove) { // Only scroll bar parts available...
-                HIThemeGetTrackDragRect(&tdi, &macRect);
-            } else {
-                ControlPartCode cpc;
-                if (sc == SC_ScrollBarSubPage || sc == SC_ScrollBarAddPage) {
-                    cpc = sc == SC_ScrollBarSubPage ? kControlPageDownPart
-                                                            : kControlPageUpPart;
-                } else {
-                    cpc = sc == SC_ScrollBarSubLine ? kControlUpButtonPart
-                                                            : kControlDownButtonPart;
-                    if (slider->direction == Qt::RightToLeft
-                        && slider->orientation == Qt::Horizontal) {
-                        if (cpc == kControlDownButtonPart)
-                            cpc = kControlUpButtonPart;
-                        else if (cpc == kControlUpButtonPart)
-                            cpc = kControlDownButtonPart;
-                    }
-                }
-                HIThemeGetTrackPartBounds(&tdi, cpc, &macRect);
-            }
-            ret = qt_qrectForHIRect(macRect);
-
-            // Tweak: the dark line between the sub/add line buttons belong to only one of the buttons
-            // when doing hit-testing, but both of them have to repaint it. Extend the rect to cover
-            // the line in the cases where HIThemeGetTrackPartBounds returns a rect that doesn't.
-            if (slider->orientation == Qt::Horizontal) {
-                if (slider->direction == Qt::LeftToRight && sc == SC_ScrollBarSubLine)
-                    ret.adjust(0, 0, 1, 0);
-                else if (slider->direction == Qt::RightToLeft && sc == SC_ScrollBarAddLine)
-                    ret.adjust(-1, 0, 1, 0);
-            } else if (sc == SC_ScrollBarAddLine) {
-                ret.adjust(0, -1, 0, 1);
-            }
-        }
-        break;
-    case CC_TitleBar:
-        if (const QStyleOptionTitleBar *titlebar
-                = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
-            HIThemeWindowDrawInfo wdi;
-            memset(&wdi, 0, sizeof(wdi));
-            wdi.version = qt_mac_hitheme_version;
-            wdi.state = kThemeStateActive;
-            wdi.windowType = QtWinType;
-            wdi.titleHeight = titlebar->rect.height();
-            wdi.titleWidth = titlebar->rect.width();
-            wdi.attributes = kThemeWindowHasTitleText;
-            if (titlebar->subControls & SC_TitleBarCloseButton)
-                wdi.attributes |= kThemeWindowHasCloseBox;
-            if (titlebar->subControls & SC_TitleBarMaxButton
-                                        | SC_TitleBarNormalButton)
-                wdi.attributes |= kThemeWindowHasFullZoom;
-            if (titlebar->subControls & SC_TitleBarMinButton)
-                wdi.attributes |= kThemeWindowHasCollapseBox;
-            WindowRegionCode wrc = kWindowGlobalPortRgn;
-
-            if (sc == SC_TitleBarCloseButton)
-                wrc = kWindowCloseBoxRgn;
-            else if (sc == SC_TitleBarMinButton)
-                wrc = kWindowCollapseBoxRgn;
-            else if (sc == SC_TitleBarMaxButton)
-                wrc = kWindowZoomBoxRgn;
-            else if (sc == SC_TitleBarLabel)
-                wrc = kWindowTitleTextRgn;
-            else if (sc == SC_TitleBarSysMenu)
-                ret.setRect(-1024, -1024, 10, proxy()->pixelMetric(PM_TitleBarHeight,
-                                                             titlebar, widget));
-            if (wrc != kWindowGlobalPortRgn) {
-                QCFType<HIShapeRef> region;
-                QRect tmpRect = titlebar->rect;
-                HIRect titleRect = qt_hirectForQRect(tmpRect);
-                HIThemeGetWindowShape(&titleRect, &wdi, kWindowTitleBarRgn, &region);
-                ptrHIShapeGetBounds(region, &titleRect);
-                CFRelease(region);
-                tmpRect.translate(tmpRect.x() - int(titleRect.origin.x),
-                               tmpRect.y() - int(titleRect.origin.y));
-                titleRect = qt_hirectForQRect(tmpRect);
-                HIThemeGetWindowShape(&titleRect, &wdi, wrc, &region);
-                ptrHIShapeGetBounds(region, &titleRect);
-                ret = qt_qrectForHIRect(titleRect);
-            }
-        }
-        break;
-    case CC_ComboBox:
-        if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
-            HIThemeButtonDrawInfo bdi;
-            d->initComboboxBdi(combo, &bdi, widget, d->getDrawState(opt->state));
-
-            switch (sc) {
-            case SC_ComboBoxEditField:{
-                ret = QMacStylePrivate::comboboxEditBounds(combo->rect, bdi);
-                    // hack to posistion the edit feld correctly for QDateTimeEdits
-                    // in calendarPopup mode.
-                    if (qobject_cast<const QDateTimeEdit *>(widget)) {
-                       ret.moveTop(ret.top() - 2);
-                       ret.setHeight(ret.height() +1);
-                    }
-                break; }
-            case SC_ComboBoxArrow:{
-                ret = QMacStylePrivate::comboboxEditBounds(combo->rect, bdi);
-                ret.setX(ret.x() + ret.width());
-                ret.setWidth(combo->rect.right() - ret.right());
-                break; }
-            case SC_ComboBoxListBoxPopup:{
-                if (combo->editable) {
-                    HIRect inner = QMacStylePrivate::comboboxInnerBounds(qt_hirectForQRect(combo->rect), bdi.kind);
-                    QRect editRect = QMacStylePrivate::comboboxEditBounds(combo->rect, bdi);
-                    const int comboTop = combo->rect.top();
-                    ret = QRect(qRound(inner.origin.x),
-                                comboTop,
-                                qRound(inner.origin.x - combo->rect.left() + inner.size.width),
-                                editRect.bottom() - comboTop + 2);
-                } else {
-                    QRect editRect = QMacStylePrivate::comboboxEditBounds(combo->rect, bdi);
-                    ret = QRect(combo->rect.x() + 4 - 11,
-                                combo->rect.y() + 1,
-                                editRect.width() + 10 + 11,
-                                1);
-                 }
-                break; }
-            default:
-                break;
-            }
-        }
-        break;
-    case CC_GroupBox:
-        if (const QStyleOptionGroupBox *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
-            bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
-            bool flat = (groupBox->features & QStyleOptionFrameV2::Flat);
-            bool hasNoText = !checkable && groupBox->text.isEmpty();
-            switch (sc) {
-            case SC_GroupBoxLabel:
-            case SC_GroupBoxCheckBox: {
-                // Cheat and use the smaller font if we need to
-                bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
-                bool fontIsSet = (widget && widget->testAttribute(Qt::WA_SetFont))
-                                  || !QApplication::desktopSettingsAware();
-                int tw;
-                int h;
-                int margin =  flat || hasNoText ? 0 : 12;
-                ret = groupBox->rect.adjusted(margin, 0, -margin, 0);
-
-                if (!fontIsSet) {
-                    HIThemeTextInfo tti;
-                    tti.version = qt_mac_hitheme_version;
-                    tti.state = kThemeStateActive;
-                    tti.fontID = checkable ? kThemeSystemFont : kThemeSmallSystemFont;
-                    tti.horizontalFlushness = kHIThemeTextHorizontalFlushCenter;
-                    tti.verticalFlushness = kHIThemeTextVerticalFlushCenter;
-                    tti.options = kHIThemeTextBoxOptionNone;
-                    tti.truncationPosition = kHIThemeTextTruncationNone;
-                    tti.truncationMaxLines = 1 + groupBox->text.count(QLatin1Char('\n'));
-                    CGFloat width;
-                    CGFloat height;
-                    QCFString groupText = qt_mac_removeMnemonics(groupBox->text);
-                    HIThemeGetTextDimensions(groupText, 0, &tti, &width, &height, 0);
-                    tw = qRound(width);
-                    h = qCeil(height);
-                } else {
-                    QFontMetricsF fm = QFontMetricsF(groupBox->fontMetrics);
-                    h = qCeil(fm.height());
-                    tw = qCeil(fm.size(Qt::TextShowMnemonic, groupBox->text).width());
-                }
-                ret.setHeight(h);
-
-                QRect labelRect = alignedRect(groupBox->direction, groupBox->textAlignment,
-                                              QSize(tw, h), ret);
-                int indicatorWidth = proxy()->pixelMetric(PM_IndicatorWidth, opt, widget);
-                bool rtl = groupBox->direction == Qt::RightToLeft;
-                if (sc == SC_GroupBoxLabel) {
-                    if (checkable) {
-                        int newSum = indicatorWidth + 1;
-                        int newLeft = labelRect.left() + (rtl ? -newSum : newSum);
-                        labelRect.moveLeft(newLeft);
-                    } else if (flat) {
-                        int newLeft = labelRect.left() - (rtl ? 3 : -3);
-                        labelRect.moveLeft(newLeft);
-                        labelRect.moveTop(labelRect.top() + 3);
-                    } else {
-                        int newLeft = labelRect.left() - (rtl ? 3 : 2);
-                        labelRect.moveLeft(newLeft);
-                        labelRect.moveTop(labelRect.top() + 5);
-                    }
-                    ret = labelRect;
-                }
-
-                if (sc == SC_GroupBoxCheckBox) {
-                    int left = rtl ? labelRect.right() - indicatorWidth : labelRect.left();
-                    ret.setRect(left, ret.top(),
-                                indicatorWidth, proxy()->pixelMetric(PM_IndicatorHeight, opt, widget));
-                }
-                break;
-            }
-            case SC_GroupBoxContents:
-            case SC_GroupBoxFrame: {
-                if (flat) {
-                    ret = QWindowsStyle::subControlRect(cc, groupBox, sc, widget);
-                    break;
-                }
-                QFontMetrics fm = groupBox->fontMetrics;
-                bool checkable = groupBox->subControls & SC_GroupBoxCheckBox;
-                int yOffset = 3;
-                if (!checkable) {
-                    if (widget && !widget->testAttribute(Qt::WA_SetFont)
-                            && QApplication::desktopSettingsAware())
-                        fm = QFontMetrics(qt_app_fonts_hash()->value("QSmallFont", QFont()));
-                    yOffset = 5;
-                    if (hasNoText)
-                        yOffset = -qCeil(QFontMetricsF(fm).height());
-                }
-
-                ret = opt->rect.adjusted(0, qCeil(QFontMetricsF(fm).height()) + yOffset, 0, 0);
-                if (sc == SC_GroupBoxContents)
-                    ret.adjust(3, 3, -3, -4);    // guess
-            }
-                break;
-            default:
-                ret = QWindowsStyle::subControlRect(cc, groupBox, sc, widget);
-                break;
-            }
-        }
-        break;
-    case CC_SpinBox:
-        if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
-            QAquaWidgetSize aquaSize = d->aquaSizeConstrain(spin, widget);
-            int spinner_w;
-            int spinBoxSep;
-            int fw = proxy()->pixelMetric(PM_SpinBoxFrameWidth, spin, widget);
-            switch (aquaSize) {
-            default:
-            case QAquaSizeUnknown:
-            case QAquaSizeLarge:
-                spinner_w = 14;
-                spinBoxSep = 2;
-                break;
-            case QAquaSizeSmall:
-                spinner_w = 12;
-                spinBoxSep = 2;
-                break;
-            case QAquaSizeMini:
-                spinner_w = 10;
-                spinBoxSep = 1;
-                break;
-            }
-
-            switch (sc) {
-            case SC_SpinBoxUp:
-            case SC_SpinBoxDown: {
-                if (spin->buttonSymbols == QAbstractSpinBox::NoButtons)
-                    break;
-
-                const int y = fw;
-                const int x = spin->rect.width() - spinner_w;
-                ret.setRect(x + spin->rect.x(), y + spin->rect.y(), spinner_w, spin->rect.height() - y * 2);
-                HIThemeButtonDrawInfo bdi;
-                bdi.version = qt_mac_hitheme_version;
-                bdi.kind = kThemeIncDecButton;
-                int hackTranslateX;
-                switch (aquaSize) {
-                default:
-                case QAquaSizeUnknown:
-                case QAquaSizeLarge:
-                    bdi.kind = kThemeIncDecButton;
-                    hackTranslateX = 0;
-                    break;
-                case QAquaSizeSmall:
-                    bdi.kind = kThemeIncDecButtonSmall;
-                    hackTranslateX = -2;
-                    break;
-                case QAquaSizeMini:
-                    bdi.kind = kThemeIncDecButtonMini;
-                    hackTranslateX = -1;
-                    break;
-                }
-                bdi.state = kThemeStateActive;
-                bdi.value = kThemeButtonOff;
-                bdi.adornment = kThemeAdornmentNone;
-                HIRect hirect = qt_hirectForQRect(ret);
-
-                HIRect outRect;
-                HIThemeGetButtonBackgroundBounds(&hirect, &bdi, &outRect);
-                ret = qt_qrectForHIRect(outRect);
-                switch (sc) {
-                case SC_SpinBoxUp:
-                    ret.setHeight(ret.height() / 2);
-                    break;
-                case SC_SpinBoxDown:
-                    ret.setY(ret.y() + ret.height() / 2);
-                    break;
-                default:
-                    Q_ASSERT(0);
-                    break;
-                }
-                ret.translate(hackTranslateX, 0); // hack: position the buttons correctly (weird that we need this)
-                ret = visualRect(spin->direction, spin->rect, ret);
-                break;
-            }
-            case SC_SpinBoxEditField:
-                if (spin->buttonSymbols == QAbstractSpinBox::NoButtons) {
-                    ret.setRect(fw, fw,
-                                spin->rect.width() - fw * 2,
-                                spin->rect.height() - fw * 2);
-                } else {
-                    ret.setRect(fw, fw,
-                                spin->rect.width() - fw * 2 - spinBoxSep - spinner_w,
-                                spin->rect.height() - fw * 2);
-                }
-                ret = visualRect(spin->direction, spin->rect, ret);
-                break;
-            default:
-                ret = QWindowsStyle::subControlRect(cc, spin, sc, widget);
-                break;
-            }
-        }
-        break;
-    case CC_ToolButton:
-        ret = QWindowsStyle::subControlRect(cc, opt, sc, widget);
-        if (sc == SC_ToolButtonMenu && widget && !qobject_cast<QToolBar*>(widget->parentWidget())) {
-            ret.adjust(-1, 0, 0, 0);
-        }
-        break;
-    default:
-        ret = QWindowsStyle::subControlRect(cc, opt, sc, widget);
-        break;
-    }
-    return ret;
-}
-
-QSize QMacStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
-                                  const QSize &csz, const QWidget *widget) const
-{
-    QSize sz(csz);
-    bool useAquaGuideline = true;
-
-    switch (ct) {
-    case QStyle::CT_SpinBox:
-         // hack to work around horrible sizeHint() code in QAbstractSpinBox
-        sz.setHeight(sz.height() - 3);
-        break;
-       case QStyle::CT_TabWidget:
-        // the size between the pane and the "contentsRect" (+4,+4)
-        // (the "contentsRect" is on the inside of the pane)
-        sz = QWindowsStyle::sizeFromContents(ct, opt, csz, widget);
-        /**
-            This is supposed to show the relationship between the tabBar and
-            the stack widget of a QTabWidget.
-            Unfortunately ascii is not a good way of representing graphics.....
-            PS: The '=' line is the painted frame.
-
-               top    ---+
-                         |
-                         |
-                         |
-                         |                vvv just outside the painted frame is the "pane"
-                      - -|- - - - - - - - - - <-+
-            TAB BAR      +=====^============    | +2 pixels
-                    - - -|- - -|- - - - - - - <-+
-                         |     |      ^   ^^^ just inside the painted frame is the "contentsRect"
-                         |     |      |
-                         |   overlap  |
-                         |     |      |
-            bottom ------+   <-+     +14 pixels
-                                      |
-                                      v
-                ------------------------------  <- top of stack widget
-
-
-        To summarize: 
-             * 2 is the distance between the pane and the contentsRect 
-             * The 14 and the 1's are the distance from the contentsRect to the stack widget.
-               (same value as used in SE_TabWidgetTabContents)
-             * overlap is how much the pane should overlap the tab bar
-        */     
-        // then add the size between the stackwidget and the "contentsRect"
-
-        if (const QStyleOptionTabWidgetFrame *twf
-                = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
-            QSize extra(0,0);
-            const int overlap = pixelMetric(PM_TabBarBaseOverlap, opt, widget);
-            const int gapBetweenTabbarAndStackWidget = 2 + 14 - overlap;
-
-            if (getTabDirection(twf->shape) == kThemeTabNorth || getTabDirection(twf->shape) == kThemeTabSouth) {
-                extra = QSize(2, gapBetweenTabbarAndStackWidget + 1);
-            } else {
-                extra = QSize(gapBetweenTabbarAndStackWidget + 1, 2);
-            }
-            sz+= extra;
-        }
-
-        break;
-    case QStyle::CT_TabBarTab:
-        if (const QStyleOptionTabV3 *tab = qstyleoption_cast<const QStyleOptionTabV3 *>(opt)) {
-            const QAquaWidgetSize AquaSize = d->aquaSizeConstrain(opt, widget);
-            const bool differentFont = (widget && widget->testAttribute(Qt::WA_SetFont))
-                                       || !QApplication::desktopSettingsAware();
-            ThemeTabDirection ttd = getTabDirection(tab->shape);
-            bool vertTabs = ttd == kThemeTabWest || ttd == kThemeTabEast;
-            if (vertTabs)
-                sz.transpose();
-            int defaultTabHeight;
-            int defaultExtraSpace = proxy()->pixelMetric(PM_TabBarTabHSpace, tab, widget); // Remove spurious gcc warning (AFAIK)
-            QFontMetrics fm = opt->fontMetrics;
-            switch (AquaSize) {
-            case QAquaSizeUnknown:
-            case QAquaSizeLarge:
-                if (tab->documentMode)
-                    defaultTabHeight = 23;
-                else
-                    defaultTabHeight = 21;
-                break;
-            case QAquaSizeSmall:
-                defaultTabHeight = 18;
-                break;
-            case QAquaSizeMini:
-                defaultTabHeight = 16;
-                break;
-            }
-            bool setWidth = false;
-            if (differentFont || !tab->icon.isNull()) {
-                sz.rheight() = qMax(defaultTabHeight, sz.height());
-            } else {
-                QSize textSize = fm.size(Qt::TextShowMnemonic, tab->text);
-                sz.rheight() = qMax(defaultTabHeight, textSize.height());
-                sz.rwidth() = textSize.width() + defaultExtraSpace;
-                setWidth = true;
-            }
-
-            if (vertTabs)
-                sz.transpose();
-
-            int maxWidgetHeight = qMax(tab->leftButtonSize.height(), tab->rightButtonSize.height());
-            int maxWidgetWidth = qMax(tab->leftButtonSize.width(), tab->rightButtonSize.width());
-
-            int widgetWidth = 0;
-            int widgetHeight = 0;
-            int padding = 0;
-            if (tab->leftButtonSize.isValid()) {
-                padding += 8;
-                widgetWidth += tab->leftButtonSize.width();
-                widgetHeight += tab->leftButtonSize.height();
-            }
-            if (tab->rightButtonSize.isValid()) {
-                padding += 8;
-                widgetWidth += tab->rightButtonSize.width();
-                widgetHeight += tab->rightButtonSize.height();
-            }
-
-            if (vertTabs) {
-                sz.setHeight(sz.height() + widgetHeight + padding);
-                sz.setWidth(qMax(sz.width(), maxWidgetWidth));
-            } else {
-                if (setWidth)
-                    sz.setWidth(sz.width() + widgetWidth + padding);
-                sz.setHeight(qMax(sz.height(), maxWidgetHeight));
-            }
-        }
-        break;
-    case QStyle::CT_PushButton:
-        // By default, we fit the contents inside a normal rounded push button.
-        // Do this by add enough space around the contents so that rounded
-        // borders (including highlighting when active) will show.
-        sz.rwidth() += QMacStylePrivate::PushButtonLeftOffset + QMacStylePrivate::PushButtonRightOffset + 12;
-        sz.rheight() += QMacStylePrivate::PushButtonTopOffset + QMacStylePrivate::PushButtonBottomOffset;
-        break;
-    case QStyle::CT_MenuItem:
-        if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
-            int maxpmw = mi->maxIconWidth;
-            const QComboBox *comboBox = qobject_cast<const QComboBox *>(widget);
-            int w = sz.width(),
-                h = sz.height();
-            if (mi->menuItemType == QStyleOptionMenuItem::Separator) {
-                w = 10;
-                SInt16 ash;
-                GetThemeMenuSeparatorHeight(&ash);
-                h = ash;
-            } else {
-                h = mi->fontMetrics.height() + 2;
-                if (!mi->icon.isNull()) {
-                    if (comboBox) {
-                        const QSize &iconSize = comboBox->iconSize();
-                        h = qMax(h, iconSize.height() + 4);
-                        maxpmw = qMax(maxpmw, iconSize.width());
-                    } else {
-                        int iconExtent = proxy()->pixelMetric(PM_SmallIconSize);
-                        h = qMax(h, mi->icon.actualSize(QSize(iconExtent, iconExtent)).height() + 4);
-                    }
-                }
-            }
-            if (mi->text.contains(QLatin1Char('\t')))
-                w += 12;
-            if (mi->menuItemType == QStyleOptionMenuItem::SubMenu)
-                w += 20;
-            if (maxpmw)
-                w += maxpmw + 6;
-            // add space for a check. All items have place for a check too.
-            w += 20;
-            if (comboBox && comboBox->isVisible()) {
-                QStyleOptionComboBox cmb;
-                cmb.initFrom(comboBox);
-                cmb.editable = false;
-                cmb.subControls = QStyle::SC_ComboBoxEditField;
-                cmb.activeSubControls = QStyle::SC_None;
-                w = qMax(w, subControlRect(QStyle::CC_ComboBox, &cmb,
-                                                   QStyle::SC_ComboBoxEditField,
-                                                   comboBox).width());
-            } else {
-                w += 12;
-            }
-            sz = QSize(w, h);
-        }
-        break;
-    case CT_ToolButton:
-        if (widget && qobject_cast<const QToolBar *>(widget->parentWidget())) {
-            if (QMainWindow * mainWindow = qobject_cast<QMainWindow *>(widget->parent())) {
-                if (mainWindow->unifiedTitleAndToolBarOnMac()) {
-                    sz.rwidth() += 4;
-                    if (sz.height() <= 32) {
-                        // Workaround strange HIToolBar bug when getting constraints.
-                        sz.rheight() += 1;
-                    }
-                    return sz;
-                }
-            }
-        }
-        sz.rwidth() += 10;
-        sz.rheight() += 10;
-        return sz;
-    case CT_ComboBox:
-        sz.rwidth() += 50;
-        break;
-    case CT_Menu: {
-        QStyleHintReturnMask menuMask;
-        QStyleOption myOption = *opt;
-        myOption.rect.setSize(sz);
-        if (proxy()->styleHint(SH_Menu_Mask, &myOption, widget, &menuMask)) {
-            sz = menuMask.region.boundingRect().size();
-        }
-        break; }
-    case CT_HeaderSection:{
-        const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt);
-        sz = QWindowsStyle::sizeFromContents(ct, opt, csz, widget);
-        if (header->text.contains(QLatin1Char('\n')))
-            useAquaGuideline = false;
-        break; }
-    case CT_ScrollBar :
-        // Make sure that the scroll bar is large enough to display the thumb indicator.
-        if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
-            const int minimumSize = scrollButtonsCutoffSize(thumbIndicatorCutoff, widgetSizePolicy(widget));
-            if (slider->orientation == Qt::Horizontal)
-                sz = sz.expandedTo(QSize(minimumSize, sz.height()));
-            else
-                sz = sz.expandedTo(QSize(sz.width(), minimumSize));
-        }
-        break;
-    case CT_ItemViewItem:
-        if (const QStyleOptionViewItemV4 *vopt = qstyleoption_cast<const QStyleOptionViewItemV4 *>(opt)) {
-            sz = QCommonStyle::sizeFromContents(ct, vopt, csz, widget);
-            sz.setHeight(sz.height() + 2);
-        }
-        break;
-
-    default:
-        sz = QWindowsStyle::sizeFromContents(ct, opt, csz, widget);
-    }
-
-    if (useAquaGuideline){
-        QSize macsz;
-        if (d->aquaSizeConstrain(opt, widget, ct, sz, &macsz) != QAquaSizeUnknown) {
-            if (macsz.width() != -1)
-                sz.setWidth(macsz.width());
-            if (macsz.height() != -1)
-                sz.setHeight(macsz.height());
-        }
-    }
-
-    // The sizes that Carbon and the guidelines gives us excludes the focus frame.
-    // We compensate for this by adding some extra space here to make room for the frame when drawing:
-    if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)){
-        QAquaWidgetSize widgetSize = d->aquaSizeConstrain(opt, widget);
-        int bkind = 0;
-        switch (widgetSize) {
-        default:
-        case QAquaSizeLarge:
-            bkind = combo->editable ? kThemeComboBox : kThemePopupButton;
-            break;
-        case QAquaSizeSmall:
-            bkind = combo->editable ? int(kThemeComboBoxSmall) : int(kThemePopupButtonSmall);
-            break;
-        case QAquaSizeMini:
-            bkind = combo->editable ? kThemeComboBoxMini : kThemePopupButtonMini;
-            break;
-        }
-        HIRect tmpRect = {{0, 0}, {0, 0}};
-        HIRect diffRect = QMacStylePrivate::comboboxInnerBounds(tmpRect, bkind);
-        sz.rwidth() -= qRound(diffRect.size.width);
-        sz.rheight() -= qRound(diffRect.size.height);
-    } else if (ct == CT_PushButton || ct == CT_ToolButton){
-        ThemeButtonKind bkind;
-        QAquaWidgetSize widgetSize = d->aquaSizeConstrain(opt, widget);
-        switch (ct) {
-        default:
-        case CT_PushButton:
-            if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
-                if (btn->features & QStyleOptionButton::CommandLinkButton) {
-                    return QWindowsStyle::sizeFromContents(ct, opt, sz, widget);
-                }
-            }
-
-            switch (widgetSize) {
-            default:
-            case QAquaSizeLarge:
-                bkind = kThemePushButton;
-                break;
-            case QAquaSizeSmall:
-                bkind = kThemePushButtonSmall;
-                break;
-            case QAquaSizeMini:
-                bkind = kThemePushButtonMini;
-                break;
-            }
-            break;
-        case CT_ToolButton:
-            switch (widgetSize) {
-            default:
-            case QAquaSizeLarge:
-                bkind = kThemeLargeBevelButton;
-                break;
-            case QAquaSizeMini:
-            case QAquaSizeSmall:
-                bkind = kThemeSmallBevelButton;
-            }
-            break;
-        }
-
-        HIThemeButtonDrawInfo bdi;
-        bdi.version = qt_mac_hitheme_version;
-        bdi.state = kThemeStateActive;
-        bdi.kind = bkind;
-        bdi.value = kThemeButtonOff;
-        bdi.adornment = kThemeAdornmentNone;
-        HIRect macRect, myRect;
-        myRect = CGRectMake(0, 0, sz.width(), sz.height());
-        HIThemeGetButtonBackgroundBounds(&myRect, &bdi, &macRect);
-        // Mini buttons only return their actual size in HIThemeGetButtonBackgroundBounds, so help them out a bit (guess),
-        if (bkind == kThemePushButtonMini)
-            macRect.size.height += 8.;
-        else if (bkind == kThemePushButtonSmall)
-            macRect.size.height -= 10;
-        sz.setWidth(sz.width() + int(macRect.size.width - myRect.size.width));
-        sz.setHeight(sz.height() + int(macRect.size.height - myRect.size.height));
-    }
-    return sz;
-}
-
-void QMacStyle::drawItemText(QPainter *p, const QRect &r, int flags, const QPalette &pal,
-                             bool enabled, const QString &text, QPalette::ColorRole textRole) const
-{
-    if(flags & Qt::TextShowMnemonic)
-        flags |= Qt::TextHideMnemonic;
-    QWindowsStyle::drawItemText(p, r, flags, pal, enabled, text, textRole);
-}
-
-bool QMacStyle::event(QEvent *e)
-{
-    if(e->type() == QEvent::FocusIn) {
-        QWidget *f = 0;
-        QWidget *focusWidget = QApplication::focusWidget();
-#ifndef QT_NO_GRAPHICSVIEW
-        if (QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(focusWidget)) {
-            QGraphicsItem *focusItem = graphicsView->scene() ? graphicsView->scene()->focusItem() : 0;
-            if (focusItem && focusItem->type() == QGraphicsProxyWidget::Type) {
-                QGraphicsProxyWidget *proxy = static_cast<QGraphicsProxyWidget *>(focusItem);
-                if (proxy->widget())
-                    focusWidget = proxy->widget()->focusWidget();
-            }
-        }
-#endif
-        if (focusWidget && focusWidget->testAttribute(Qt::WA_MacShowFocusRect)) {
-            f = focusWidget;
-            QWidget *top = f->parentWidget();
-            while (top && !top->isWindow() && !(top->windowType() == Qt::SubWindow))
-                top = top->parentWidget();
-#ifndef QT_NO_MAINWINDOW
-            if (qobject_cast<QMainWindow *>(top)) {
-                QWidget *central = static_cast<QMainWindow *>(top)->centralWidget();
-                for (const QWidget *par = f; par; par = par->parentWidget()) {
-                    if (par == central) {
-                        top = central;
-                        break;
-                    }
-                    if (par->isWindow())
-                        break;
-                }
-            }
-#endif
-        }
-        if (f) {
-            if(!d->focusWidget)
-                d->focusWidget = new QFocusFrame(f);
-            d->focusWidget->setWidget(f);
-        } else if(d->focusWidget) {
-            d->focusWidget->setWidget(0);
-        }
-    } else if(e->type() == QEvent::FocusOut) {
-        if(d->focusWidget)
-            d->focusWidget->setWidget(0);
-    }
-    return false;
-}
-
-QIcon QMacStyle::standardIconImplementation(StandardPixmap standardIcon, const QStyleOption *opt,
-                                            const QWidget *widget) const
-{
-    switch (standardIcon) {
-    default:
-        return QWindowsStyle::standardIconImplementation(standardIcon, opt, widget);
-    case SP_ToolBarHorizontalExtensionButton:
-    case SP_ToolBarVerticalExtensionButton: {
-        QPixmap pixmap(qt_mac_toolbar_ext);
-        if (standardIcon == SP_ToolBarVerticalExtensionButton) {
-            QPixmap pix2(pixmap.height(), pixmap.width());
-            pix2.fill(Qt::transparent);
-            QPainter p(&pix2);
-            p.translate(pix2.width(), 0);
-            p.rotate(90);
-            p.drawPixmap(0, 0, pixmap);
-            return pix2;
-        }
-        return pixmap;
-    }
-    }
-}
-
-int QMacStyle::layoutSpacingImplementation(QSizePolicy::ControlType control1,
-                                           QSizePolicy::ControlType control2,
-                                           Qt::Orientation orientation,
-                                           const QStyleOption *option,
-                                           const QWidget *widget) const
-{
-    const int ButtonMask = QSizePolicy::ButtonBox | QSizePolicy::PushButton;
-    bool isMetal = (widget && widget->testAttribute(Qt::WA_MacBrushedMetal));
-    int controlSize = getControlSize(option, widget);
-
-    if (control2 == QSizePolicy::ButtonBox) {
-        /*
-            AHIG seems to prefer a 12-pixel margin between group
-            boxes and the row of buttons. The 20 pixel comes from
-            Builder.
-        */
-        if (isMetal                                         // (AHIG, guess, guess)
-                || (control1 & (QSizePolicy::Frame          // guess
-                                | QSizePolicy::GroupBox     // (AHIG, guess, guess)
-                                | QSizePolicy::TabWidget    // guess
-                                | ButtonMask)))    {        // AHIG
-            return_SIZE(14, 8, 8);
-        } else if (control1 == QSizePolicy::LineEdit) {
-            return_SIZE(8, 8, 8); // Interface Builder
-        } else {
-            return_SIZE(20, 7, 7); // Interface Builder
-        }
-    }
-
-    if ((control1 | control2) & ButtonMask) {
-        if (control1 == QSizePolicy::LineEdit)
-            return_SIZE(8, 8, 8); // Interface Builder
-        else if (control2 == QSizePolicy::LineEdit) {
-            if (orientation == Qt::Vertical)
-                return_SIZE(20, 7, 7); // Interface Builder
-            else
-                return_SIZE(20, 8, 8);
-        }
-        return_SIZE(14, 8, 8);     // Interface Builder
-    }
-
-    switch (CT2(control1, control2)) {
-    case CT1(QSizePolicy::Label):                             // guess
-    case CT2(QSizePolicy::Label, QSizePolicy::DefaultType):   // guess
-    case CT2(QSizePolicy::Label, QSizePolicy::CheckBox):      // AHIG
-    case CT2(QSizePolicy::Label, QSizePolicy::ComboBox):      // AHIG
-    case CT2(QSizePolicy::Label, QSizePolicy::LineEdit):      // guess
-    case CT2(QSizePolicy::Label, QSizePolicy::RadioButton):   // AHIG
-    case CT2(QSizePolicy::Label, QSizePolicy::Slider):        // guess
-    case CT2(QSizePolicy::Label, QSizePolicy::SpinBox):       // guess
-    case CT2(QSizePolicy::Label, QSizePolicy::ToolButton):    // guess
-        return_SIZE(8, 6, 5);
-    case CT1(QSizePolicy::ToolButton):
-        return 8;   // AHIG
-    case CT1(QSizePolicy::CheckBox):
-    case CT2(QSizePolicy::CheckBox, QSizePolicy::RadioButton):
-    case CT2(QSizePolicy::RadioButton, QSizePolicy::CheckBox):
-        if (orientation == Qt::Vertical)
-            return_SIZE(8, 8, 7);        // AHIG and Builder
-        break;
-    case CT1(QSizePolicy::RadioButton):
-        if (orientation == Qt::Vertical)
-            return 5;                   // (Builder, guess, AHIG)
-    }
-
-    if (orientation == Qt::Horizontal
-            && (control2 & (QSizePolicy::CheckBox | QSizePolicy::RadioButton)))
-        return_SIZE(12, 10, 8);        // guess
-
-    if ((control1 | control2) & (QSizePolicy::Frame
-                                 | QSizePolicy::GroupBox
-                                 | QSizePolicy::TabWidget)) {
-        /*
-            These values were chosen so that nested container widgets
-            look good side by side. Builder uses 8, which looks way
-            too small, and AHIG doesn't say anything.
-        */
-        return_SIZE(16, 10, 10);    // guess
-    }
-
-    if ((control1 | control2) & (QSizePolicy::Line | QSizePolicy::Slider))
-        return_SIZE(12, 10, 8);     // AHIG
-
-    if ((control1 | control2) & QSizePolicy::LineEdit)
-        return_SIZE(10, 8, 8);      // AHIG
-
-    /*
-        AHIG and Builder differ by up to 4 pixels for stacked editable
-        comboboxes. We use some values that work fairly well in all
-        cases.
-    */
-    if ((control1 | control2) & QSizePolicy::ComboBox)
-        return_SIZE(10, 8, 7);      // guess
-
-    /*
-        Builder defaults to 8, 6, 5 in lots of cases, but most of the time the
-        result looks too cramped.
-    */
-    return_SIZE(10, 8, 6);  // guess
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/styles/qmacstyle_mac_p.h b/src/gui/styles/qmacstyle_mac_p.h
deleted file mode 100644 (file)
index 7498146..0000000
+++ /dev/null
@@ -1,241 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef QMACSTYLE_MAC_P_H
-#define QMACSTYLE_MAC_P_H
-
-#include <qmacstyle_mac.h>
-#include <qapplication_p.h>
-#include <qcombobox_p.h>
-#include <qmacstylepixmaps_mac_p.h>
-#include <qpaintengine_mac_p.h>
-#include <qpainter_p.h>
-#include <qprintengine_mac_p.h>
-#include <qstylehelper_p.h>
-#include <qapplication.h>
-#include <qbitmap.h>
-#include <qcheckbox.h>
-#include <qcombobox.h>
-#include <qdialogbuttonbox.h>
-#include <qdockwidget.h>
-#include <qevent.h>
-#include <qfocusframe.h>
-#include <qformlayout.h>
-#include <qgroupbox.h>
-#include <qhash.h>
-#include <qheaderview.h>
-#include <qlayout.h>
-#include <qlineedit.h>
-#include <qlistview.h>
-#include <qmainwindow.h>
-#include <qmap.h>
-#include <qmenubar.h>
-#include <qpaintdevice.h>
-#include <qpainter.h>
-#include <qpixmapcache.h>
-#include <qpointer.h>
-#include <qprogressbar.h>
-#include <qpushbutton.h>
-#include <qradiobutton.h>
-#include <qrubberband.h>
-#include <qsizegrip.h>
-#include <qspinbox.h>
-#include <qsplitter.h>
-#include <qstyleoption.h>
-#include <qtextedit.h>
-#include <qtextstream.h>
-#include <qtoolbar.h>
-#include <qtoolbutton.h>
-#include <qtreeview.h>
-#include <qtableview.h>
-#include <qwizard.h>
-#include <qdebug.h>
-#include <qlibrary.h>
-#include <qdatetimeedit.h>
-#include <qmath.h>
-#include <QtGui/qgraphicsproxywidget.h>
-#include <QtGui/qgraphicsview.h>
-#include <qt_cocoa_helpers_mac_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
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5)
-enum {
-    kThemePushButtonTextured = 31,
-    kThemePushButtonTexturedSmall = 32,
-    kThemePushButtonTexturedMini = 33
-};
-
-/* Search fields */
-enum {
-    kHIThemeFrameTextFieldRound = 1000,
-    kHIThemeFrameTextFieldRoundSmall = 1001,
-    kHIThemeFrameTextFieldRoundMini = 1002
-};
-#endif
-
-/*
-    AHIG:
-        Apple Human Interface Guidelines
-        http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/
-
-    Builder:
-        Apple Interface Builder v. 3.1.1
-*/
-
-// this works as long as we have at most 16 different control types
-#define CT1(c) CT2(c, c)
-#define CT2(c1, c2) ((uint(c1) << 16) | uint(c2))
-
-enum QAquaWidgetSize { QAquaSizeLarge = 0, QAquaSizeSmall = 1, QAquaSizeMini = 2,
-                       QAquaSizeUnknown = -1 };
-
-#define SIZE(large, small, mini) \
-    (controlSize == QAquaSizeLarge ? (large) : controlSize == QAquaSizeSmall ? (small) : (mini))
-
-// same as return SIZE(...) but optimized
-#define return_SIZE(large, small, mini) \
-    do { \
-        static const int sizes[] = { (large), (small), (mini) }; \
-        return sizes[controlSize]; \
-    } while (0)
-
-bool qt_mac_buttonIsRenderedFlat(const QPushButton *pushButton, const QStyleOptionButton *option);
-
-class QMacStylePrivate : public QObject
-{
-    Q_OBJECT
-
-public:
-    QMacStylePrivate(QMacStyle *style);
-
-    // Ideally these wouldn't exist, but since they already exist we need some accessors.
-    static const int PushButtonLeftOffset;
-    static const int PushButtonTopOffset;
-    static const int PushButtonRightOffset;
-    static const int PushButtonBottomOffset;
-    static const int MiniButtonH;
-    static const int SmallButtonH;
-    static const int BevelButtonW;
-    static const int BevelButtonH;
-    static const int PushButtonContentPadding;
-
-
-    // Stuff from QAquaAnimate:
-    bool addWidget(QWidget *);
-    void removeWidget(QWidget *);
-
-    enum Animates { AquaPushButton, AquaProgressBar, AquaListViewItemOpen };
-    bool animatable(Animates, const QWidget *) const;
-    void stopAnimate(Animates, QWidget *);
-    void startAnimate(Animates, QWidget *);
-    static ThemeDrawState getDrawState(QStyle::State flags);
-    QAquaWidgetSize aquaSizeConstrain(const QStyleOption *option, const QWidget *widg,
-                             QStyle::ContentsType ct = QStyle::CT_CustomBase,
-                             QSize szHint=QSize(-1, -1), QSize *insz = 0) const;
-    void getSliderInfo(QStyle::ComplexControl cc, const QStyleOptionSlider *slider,
-                          HIThemeTrackDrawInfo *tdi, const QWidget *needToRemoveMe);
-    bool doAnimate(Animates);
-    inline int animateSpeed(Animates) const { return 33; }
-
-    // Utility functions
-    void drawColorlessButton(const HIRect &macRect, HIThemeButtonDrawInfo *bdi,
-                             QPainter *p, const QStyleOption *opt) const;
-
-    QSize pushButtonSizeFromContents(const QStyleOptionButton *btn) const;
-
-    HIRect pushButtonContentBounds(const QStyleOptionButton *btn,
-                                   const HIThemeButtonDrawInfo *bdi) const;
-
-    void initComboboxBdi(const QStyleOptionComboBox *combo, HIThemeButtonDrawInfo *bdi,
-                        const QWidget *widget, const ThemeDrawState &tds);
-
-    static HIRect comboboxInnerBounds(const HIRect &outerBounds, int buttonKind);
-
-    static QRect comboboxEditBounds(const QRect &outerBounds, const HIThemeButtonDrawInfo &bdi);
-
-    static void drawCombobox(const HIRect &outerBounds, const HIThemeButtonDrawInfo &bdi, QPainter *p);
-    static void drawTableHeader(const HIRect &outerBounds, bool drawTopBorder, bool drawLeftBorder,
-                                     const HIThemeButtonDrawInfo &bdi, QPainter *p);
-    bool contentFitsInPushButton(const QStyleOptionButton *btn, HIThemeButtonDrawInfo *bdi,
-                                 ThemeButtonKind buttonKindToCheck) const;
-    void initHIThemePushButton(const QStyleOptionButton *btn, const QWidget *widget,
-                               const ThemeDrawState tds,
-                               HIThemeButtonDrawInfo *bdi) const;
-    QPixmap generateBackgroundPattern() const;
-protected:
-    bool eventFilter(QObject *, QEvent *);
-    void timerEvent(QTimerEvent *);
-
-private slots:
-    void startAnimationTimer();
-
-public:
-    QPointer<QPushButton> defaultButton; //default push buttons
-    int timerID;
-    QList<QPointer<QWidget> > progressBars; //existing progress bars that need animation
-
-    struct ButtonState {
-        int frame;
-        enum { ButtonDark, ButtonLight } dir;
-    } buttonState;
-    UInt8 progressFrame;
-    QPointer<QFocusFrame> focusWidget;
-    CFAbsoluteTime defaultButtonStart;
-    QMacStyle *q;
-    bool mouseDown;
-};
-
-QT_END_NAMESPACE
-
-#endif // QMACSTYLE_MAC_P_H
diff --git a/src/gui/styles/qmacstylepixmaps_mac_p.h b/src/gui/styles/qmacstylepixmaps_mac_p.h
deleted file mode 100644 (file)
index b5f4a0a..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QMACSTYLEPIXMAPS_MAC_P_H
-#define QMACSTYLEPIXMAPS_MAC_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.
-//
-
-static const char * const qt_mac_toolbar_ext[]={
-    "14 9 4 1",
-    "# c #858585",
-    "b c #d9d9d9",
-    ". c #dbdbdb",
-    "a c None",
-    ".###..###.aaaa",
-    "a.###..###.aaa",
-    "aab###bb###baa",
-    "aaab###bb###ba",
-    "aaaa.###..###.",
-    "aaa.###..###.a",
-    "aab###bb###baa",
-    "ab###bb###baaa",
-    ".###..###.aaaa"};
-
-#endif //  QMACSTYLEPIXMAPS_MAC_P_H
diff --git a/src/gui/styles/qstyle_wince.qrc b/src/gui/styles/qstyle_wince.qrc
deleted file mode 100644 (file)
index bdcf604..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource prefix="/trolltech/styles/commonstyle">
-<file>images/filelink-16.png</file>
-<file>images/filelink-32.png</file>
-<file>images/file-16.png</file>
-<file>images/file-32.png</file>
-<file>images/newdirectory-16.png</file>
-<file>images/newdirectory-32.png</file>
-<file>images/parentdir-16.png</file>
-<file>images/parentdir-32.png</file>
-<file>images/dvd-16.png</file>
-<file>images/dvd-32.png</file>
-<file>images/cdr-16.png</file>
-<file>images/cdr-32.png</file>
-<file>images/floppy-16.png</file>
-<file>images/floppy-32.png</file>
-<file>images/harddrive-16.png</file>
-<file>images/harddrive-32.png</file>
-<file>images/trash-16.png</file>
-<file>images/trash-32.png</file>
-<file>images/networkdrive-16.png</file>
-<file>images/networkdrive-32.png</file>
-<file>images/computer-16.png</file>
-<file>images/computer-32.png</file>
-<file>images/desktop-16.png</file>
-<file>images/desktop-32.png</file>
-<file>images/dirclosed-16.png</file>
-<file>images/dirclosed-32.png</file>
-<file>images/dirlink-16.png</file>
-<file>images/dirlink-32.png</file>
-<file>images/diropen-16.png</file>
-<file>images/diropen-32.png</file>
-<file>images/left-16.png</file>
-<file>images/left-32.png</file>
-<file>images/right-16.png</file>
-<file>images/right-32.png</file>
-<file>images/up-16.png</file>
-<file>images/up-32.png</file>
-<file>images/down-16.png</file>
-<file>images/down-32.png</file>
-<file>images/filecontents-16.png</file>
-<file>images/filecontents-32.png</file>
-<file>images/fileinfo-16.png</file>
-<file>images/fileinfo-32.png</file>
-<file>images/viewdetailed-16.png</file>
-<file>images/viewdetailed-32.png</file>
-<file>images/viewlist-16.png</file>
-<file>images/viewlist-32.png</file>
-<file>images/fontbitmap-16.png</file>
-<file>images/fonttruetype-16.png</file>
-<file>images/standardbutton-apply-16.png</file>
-<file>images/standardbutton-apply-32.png</file>
-<file>images/standardbutton-cancel-16.png</file>
-<file>images/standardbutton-cancel-32.png</file>
-<file>images/standardbutton-clear-16.png</file>
-<file>images/standardbutton-clear-32.png</file>
-<file>images/standardbutton-close-16.png</file>
-<file>images/standardbutton-close-32.png</file>
-<file>images/standardbutton-delete-16.png</file>
-<file>images/standardbutton-delete-32.png</file>
-<file>images/standardbutton-help-16.png</file>
-<file>images/standardbutton-help-32.png</file>
-<file>images/standardbutton-no-16.png</file>
-<file>images/standardbutton-no-32.png</file>
-<file>images/standardbutton-ok-16.png</file>
-<file>images/standardbutton-ok-32.png</file>
-<file>images/standardbutton-open-16.png</file>
-<file>images/standardbutton-open-32.png</file>
-<file>images/standardbutton-save-16.png</file>
-<file>images/standardbutton-save-32.png</file>
-<file>images/standardbutton-yes-16.png</file>
-<file>images/standardbutton-yes-32.png</file>
-<file>images/standardbutton-closetab-16.png</file>
-<file>images/standardbutton-closetab-down-16.png</file>
-<file>images/standardbutton-closetab-hover-16.png</file>
-<file>images/refresh-24.png</file>
-<file>images/refresh-32.png</file>
-<file>images/stop-24.png</file>
-<file>images/stop-32.png</file>
-<file>images/media-stop-16.png</file>
-<file>images/media-stop-32.png</file>
-<file>images/media-play-16.png</file>
-<file>images/media-play-32.png</file>
-<file>images/media-pause-16.png</file>
-<file>images/media-pause-32.png</file>
-<file>images/media-seek-forward-16.png</file>
-<file>images/media-seek-forward-32.png</file>
-<file>images/media-seek-backward-16.png</file>
-<file>images/media-seek-backward-32.png</file>
-<file>images/media-skip-forward-16.png</file>
-<file>images/media-skip-forward-32.png</file>
-<file>images/media-skip-backward-16.png</file>
-<file>images/media-skip-backward-32.png</file>
-<file>images/media-volume-16.png</file>
-<file>images/media-volume-muted-16.png</file>
-</qresource>
-</RCC>
diff --git a/src/gui/text/qfont_mac.cpp b/src/gui/text/qfont_mac.cpp
deleted file mode 100644 (file)
index bf77810..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfont.h"
-#include "qfont_p.h"
-#include "qfontengine_p.h"
-#include "qfontengine_mac_p.h"
-#include "qfontengine_coretext_p.h"
-#include "qfontinfo.h"
-#include "qfontmetrics.h"
-#include "qpaintdevice.h"
-#include "qstring.h"
-#include <qt_mac_p.h>
-#include <qtextengine_p.h>
-#include <qunicodetables_p.h>
-#include <qapplication.h>
-#include "qfontdatabase.h"
-#include <qpainter.h>
-#include "qtextengine_p.h"
-#include <stdlib.h>
-
-QT_BEGIN_NAMESPACE
-
-extern float qt_mac_defaultDpi_x(); //qpaintdevice_mac.cpp
-
-int qt_mac_pixelsize(const QFontDef &def, int dpi)
-{
-    float ret;
-    if(def.pixelSize == -1)
-        ret = def.pointSize *  dpi / qt_mac_defaultDpi_x();
-    else
-        ret = def.pixelSize;
-    return qRound(ret);
-}
-int qt_mac_pointsize(const QFontDef &def, int dpi)
-{
-    float ret;
-    if(def.pointSize < 0)
-        ret = def.pixelSize * qt_mac_defaultDpi_x() / float(dpi);
-    else
-        ret = def.pointSize;
-    return qRound(ret);
-}
-
-QString QFont::rawName() const
-{
-    return family();
-}
-
-void QFont::setRawName(const QString &name)
-{
-    setFamily(name);
-}
-
-void QFont::cleanup()
-{
-    QFontCache::cleanup();
-}
-
-/*!
-  Returns an ATSUFontID
-*/
-quint32 QFont::macFontID() const  // ### need 64-bit version
-{
-#ifdef QT_MAC_USE_COCOA
-    return 0;
-#elif 1
-    QFontEngine *fe = d->engineForScript(QUnicodeTables::Common);
-    if (fe && fe->type() == QFontEngine::Multi)
-        return static_cast<QFontEngineMacMulti*>(fe)->macFontID();
-#else
-    Str255 name;
-    if(FMGetFontFamilyName((FMFontFamily)((UInt32)handle()), name) == noErr) {
-        short fnum;
-        GetFNum(name, &fnum);
-        return fnum;
-    }
-#endif
-    return 0;
-}
-
-// Returns an ATSUFonFamilyRef
-Qt::HANDLE QFont::handle() const
-{
-#ifdef QT_MAC_USE_COCOA
-    QFontEngine *fe = d->engineForScript(QUnicodeTables::Common);
-    if (fe && fe->type() == QFontEngine::Multi)
-        return (Qt::HANDLE)static_cast<QCoreTextFontEngineMulti*>(fe)->macFontID();
-#endif
-    return 0;
-}
-
-void QFont::initialize()
-{ }
-
-QString QFont::defaultFamily() const
-{
-    switch(d->request.styleHint) {
-        case QFont::Times:
-            return QString::fromLatin1("Times New Roman");
-        case QFont::Courier:
-            return QString::fromLatin1("Courier New");
-        case QFont::Monospace:
-            return QString::fromLatin1("Courier");
-        case QFont::Decorative:
-            return QString::fromLatin1("Bookman Old Style");
-        case QFont::Cursive:
-            return QString::fromLatin1("Apple Chancery");
-        case QFont::Fantasy:
-            return QString::fromLatin1("Papyrus");
-        case QFont::Helvetica:
-        case QFont::System:
-        default:
-            return QString::fromLatin1("Helvetica");
-    }
-}
-
-QString QFont::lastResortFamily() const
-{
-    return QString::fromLatin1("Helvetica");
-}
-
-QString QFont::lastResortFont() const
-{
-    return QString::fromLatin1("Geneva");
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/text/qfont_win.cpp b/src/gui/text/qfont_win.cpp
deleted file mode 100644 (file)
index 50f7b2e..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfont.h"
-#include "qfont_p.h"
-#include "qfontengine_p.h"
-#include "qtextengine_p.h"
-#include "qfontmetrics.h"
-#include "qfontinfo.h"
-
-#include "qwidget.h"
-#include "qpainter.h"
-#include <limits.h>
-#include "qt_windows.h"
-#include <qapplication_p.h>
-#include "qapplication.h"
-#include <qunicodetables_p.h>
-#include <qfontdatabase.h>
-
-QT_BEGIN_NAMESPACE
-        
-extern HDC   shared_dc();                // common dc for all fonts
-extern QFont::Weight weightFromInteger(int weight); // qfontdatabase.cpp
-
-// ### maybe move to qapplication_win
-QFont qt_LOGFONTtoQFont(LOGFONT& lf, bool /*scale*/)
-{
-    QString family = QString::fromWCharArray(lf.lfFaceName);
-    QFont qf(family);
-    qf.setItalic(lf.lfItalic);
-    if (lf.lfWeight != FW_DONTCARE)
-        qf.setWeight(weightFromInteger(lf.lfWeight));
-    int lfh = qAbs(lf.lfHeight);
-    qf.setPointSizeF(lfh * 72.0 / GetDeviceCaps(shared_dc(),LOGPIXELSY));
-    qf.setUnderline(false);
-    qf.setOverline(false);
-    qf.setStrikeOut(false);
-    return qf;
-}
-
-
-static inline float pixelSize(const QFontDef &request, int dpi)
-{
-    float pSize;
-    if (request.pointSize != -1)
-        pSize = request.pointSize * dpi/ 72.;
-    else
-        pSize = request.pixelSize;
-    return pSize;
-}
-
-static inline float pointSize(const QFontDef &fd, int dpi)
-{
-    float pSize;
-    if (fd.pointSize < 0)
-        pSize = fd.pixelSize * 72. / ((float)dpi);
-    else
-        pSize = fd.pointSize;
-    return pSize;
-}
-
-/*****************************************************************************
-  QFont member functions
- *****************************************************************************/
-
-void QFont::initialize()
-{
-}
-
-void QFont::cleanup()
-{
-    QFontCache::cleanup();
-}
-
-HFONT QFont::handle() const
-{
-    QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
-    Q_ASSERT(engine != 0);
-    if (engine->type() == QFontEngine::Multi)
-        engine = static_cast<QFontEngineMulti *>(engine)->engine(0);
-    if (engine->type() == QFontEngine::Win)
-       return static_cast<QFontEngineWin *>(engine)->hfont;
-    return 0;
-}
-
-QString QFont::rawName() const
-{
-    return family();
-}
-
-void QFont::setRawName(const QString &name)
-{
-    setFamily(name);
-}
-
-QString QFont::defaultFamily() const
-{
-    switch(d->request.styleHint) {
-        case QFont::Times:
-            return QString::fromLatin1("Times New Roman");
-        case QFont::Courier:
-        case QFont::Monospace:
-            return QString::fromLatin1("Courier New");
-        case QFont::Decorative:
-            return QString::fromLatin1("Bookman Old Style");
-        case QFont::Cursive:
-            return QString::fromLatin1("Comic Sans MS");
-        case QFont::Fantasy:
-            return QString::fromLatin1("Impact");
-        case QFont::Helvetica:
-            return QString::fromLatin1("Arial");
-        case QFont::System:
-        default:
-            return QString::fromLatin1("MS Sans Serif");
-    }
-}
-
-QString QFont::lastResortFamily() const
-{
-    return QString::fromLatin1("helvetica");
-}
-
-QString QFont::lastResortFont() const
-{
-    return QString::fromLatin1("arial");
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/text/qfontdatabase_mac.h b/src/gui/text/qfontdatabase_mac.h
deleted file mode 100644 (file)
index 8149598..0000000
+++ /dev/null
@@ -1,568 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qt_mac_p.h>
-#include "qfontengine_p.h"
-#include <qfile.h>
-#include <qabstractfileengine.h>
-#include <stdlib.h>
-#include <qendian.h>
-#include <qfontengine_coretext_p.h>
-#include <qfontengine_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-int qt_mac_pixelsize(const QFontDef &def, int dpi); //qfont_mac.cpp
-int qt_mac_pointsize(const QFontDef &def, int dpi); //qfont_mac.cpp
-
-#ifndef QT_MAC_USE_COCOA
-static void initWritingSystems(QtFontFamily *family, ATSFontRef atsFont)
-{
-    ByteCount length = 0;
-    if (ATSFontGetTable(atsFont, MAKE_TAG('O', 'S', '/', '2'), 0, 0, 0, &length) != noErr)
-        return;
-    QVarLengthArray<uchar> os2Table(length);
-    if (length < 86
-        || ATSFontGetTable(atsFont, MAKE_TAG('O', 'S', '/', '2'), 0, length, os2Table.data(), &length) != noErr)
-        return;
-
-    // See also qfontdatabase_win.cpp, offsets taken from OS/2 table in the TrueType spec
-    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) };
-    QList<QFontDatabase::WritingSystem> systems = qt_determine_writing_systems_from_truetype_bits(unicodeRange, codePageRange);
-#if 0
-    QCFString name;
-    ATSFontGetName(atsFont, kATSOptionFlagsDefault, &name);
-    qDebug() << systems.count() << "writing systems for" << QString(name);
-qDebug() << "first char" << hex << unicodeRange[0];
-    for (int i = 0; i < systems.count(); ++i)
-        qDebug() << QFontDatabase::writingSystemName(systems.at(i));
-#endif
-    for (int i = 0; i < systems.count(); ++i)
-        family->writingSystems[systems.at(i)] = QtFontFamily::Supported;
-}
-#else
-// 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
-    0, // Ogham
-    0, // Runic
-    0 // N'Ko
-};
-enum { LanguageCount = sizeof(languageForWritingSystem) / sizeof(const char *) };
-#endif
-
-static void initializeDb()
-{
-    QFontDatabasePrivate *db = privateDb();
-    if(!db || db->count)
-        return;
-
-#if defined(QT_MAC_USE_COCOA) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-    QCFType<CTFontCollectionRef> collection = CTFontCollectionCreateFromAvailableFonts(0);
-    if(!collection)
-        return;
-    QCFType<CFArrayRef> fonts = CTFontCollectionCreateMatchingFontDescriptors(collection);
-    if(!fonts)
-        return;
-    QString foundry_name = "CoreText";
-    const int numFonts = CFArrayGetCount(fonts);
-    for(int i = 0; i < numFonts; ++i) {
-        CTFontDescriptorRef font = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fonts, i);
-        QCFString family_name = (CFStringRef)CTFontDescriptorCopyLocalizedAttribute(font, kCTFontFamilyNameAttribute, NULL);
-        QCFString style_name = (CFStringRef)CTFontDescriptorCopyLocalizedAttribute(font, kCTFontStyleNameAttribute, NULL);
-        QtFontFamily *family = db->family(family_name, true);
-
-        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))
-                    family->writingSystems[i] = QtFontFamily::Supported;
-            }
-        }
-
-        QtFontFoundry *foundry = family->foundry(foundry_name, true);
-
-        QtFontStyle::Key styleKey;
-        QString styleName = style_name;
-        if(QCFType<CFDictionaryRef> styles = (CFDictionaryRef)CTFontDescriptorCopyAttribute(font, kCTFontTraitsAttribute)) {
-            if(CFNumberRef weight = (CFNumberRef)CFDictionaryGetValue(styles, kCTFontWeightTrait)) {
-                Q_ASSERT(CFNumberIsFloatType(weight));
-                double d;
-                if(CFNumberGetValue(weight, kCFNumberDoubleType, &d)) {
-                    //qDebug() << "BOLD" << (QString)family_name << d;
-                    styleKey.weight = (d > 0.0) ? QFont::Bold : QFont::Normal;
-                }
-            }
-            if(CFNumberRef italic = (CFNumberRef)CFDictionaryGetValue(styles, kCTFontSlantTrait)) {
-                Q_ASSERT(CFNumberIsFloatType(italic));
-                double d;
-                if(CFNumberGetValue(italic, kCFNumberDoubleType, &d)) {
-                    //qDebug() << "ITALIC" << (QString)family_name << d;
-                    if (d > 0.0)
-                        styleKey.style = QFont::StyleItalic;
-                }
-            }
-        }
-
-        QtFontStyle *style = foundry->style(styleKey, styleName, true);
-        style->smoothScalable = true;
-        if(QCFType<CFNumberRef> size = (CFNumberRef)CTFontDescriptorCopyAttribute(font, kCTFontSizeAttribute)) {
-            //qDebug() << "WHEE";
-            int pixel_size=0;
-            if(CFNumberIsFloatType(size)) {
-                double d;
-                CFNumberGetValue(size, kCFNumberDoubleType, &d);
-                pixel_size = d;
-            } else {
-                CFNumberGetValue(size, kCFNumberIntType, &pixel_size);
-            }
-            //qDebug() << "SIZE" << (QString)family_name << pixel_size;
-            if(pixel_size)
-                style->pixelSize(pixel_size, true);
-        } else {
-            //qDebug() << "WTF?";
-        }
-    }
-} else 
-#endif
-    {
-#ifndef QT_MAC_USE_COCOA
-        FMFontIterator it;
-        if (!FMCreateFontIterator(0, 0, kFMUseGlobalScopeOption, &it)) {
-            while (true) {
-                FMFont fmFont;
-                if (FMGetNextFont(&it, &fmFont) != noErr)
-                    break;
-
-                FMFontFamily fmFamily;
-                FMFontStyle fmStyle;
-                QString familyName;
-
-                QtFontStyle::Key styleKey;
-
-                ATSFontRef atsFont = FMGetATSFontRefFromFont(fmFont);
-
-                if (!FMGetFontFamilyInstanceFromFont(fmFont, &fmFamily, &fmStyle)) {
-                    { //sanity check the font, and see if we can use it at all! --Sam
-                        ATSUFontID fontID;
-                        if(ATSUFONDtoFontID(fmFamily, 0, &fontID) != noErr)
-                            continue;
-                    }
-
-                    if (fmStyle & ::italic)
-                        styleKey.style = QFont::StyleItalic;
-                    if (fmStyle & ::bold)
-                        styleKey.weight = QFont::Bold;
-
-                    ATSFontFamilyRef familyRef = FMGetATSFontFamilyRefFromFontFamily(fmFamily);
-                    QCFString cfFamilyName;;
-                    ATSFontFamilyGetName(familyRef, kATSOptionFlagsDefault, &cfFamilyName);
-                    familyName = cfFamilyName;
-                } else {
-                    QCFString cfFontName;
-                    ATSFontGetName(atsFont, kATSOptionFlagsDefault, &cfFontName);
-                    familyName = cfFontName;
-                    quint16 macStyle = 0;
-                    {
-                        uchar data[4];
-                        ByteCount len = 4;
-                        if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 44, 4, &data, &len) == noErr)
-                            macStyle = qFromBigEndian<quint16>(data);
-                    }
-                    if (macStyle & 1)
-                        styleKey.weight = QFont::Bold;
-                    if (macStyle & 2)
-                        styleKey.style = QFont::StyleItalic;
-                }
-
-                QtFontFamily *family = db->family(familyName, true);
-                QtFontFoundry *foundry = family->foundry(QString(), true);
-                QtFontStyle *style = foundry->style(styleKey, QString(), true);
-                style->pixelSize(0, true);
-                style->smoothScalable = true;
-
-                initWritingSystems(family, atsFont);
-            }
-            FMDisposeFontIterator(&it);
-        }
-#endif
-    }
-
-}
-
-static inline void load(const QString & = QString(), int = -1)
-{
-    initializeDb();
-}
-
-static const char *styleHint(const QFontDef &request)
-{
-    const char *stylehint = 0;
-    switch (request.styleHint) {
-    case QFont::SansSerif:
-        stylehint = "Arial";
-        break;
-    case QFont::Serif:
-        stylehint = "Times New Roman";
-        break;
-    case QFont::TypeWriter:
-        stylehint = "Courier New";
-        break;
-    default:
-        if (request.fixedPitch)
-            stylehint = "Courier New";
-        break;
-    }
-    return stylehint;
-}
-
-static inline float weightToFloat(unsigned int weight)
-{
-    return (weight - 50) / 100.0;
-}
-
-static QFontEngine *loadFromDatabase(QFontDef &req, const QFontPrivate *d)
-{
-#if defined(QT_MAC_USE_COCOA)
-    QCFString fontName = NULL;
-#else
-    ATSFontFamilyRef familyRef = 0;
-    ATSFontRef fontRef = 0;
-#endif
-
-    QStringList family_list = familyList(req);
-
-    const char *stylehint = styleHint(req);
-    if (stylehint)
-        family_list << QLatin1String(stylehint);
-
-    // add QFont::defaultFamily() to the list, for compatibility with previous versions
-    family_list << QApplication::font().defaultFamily();
-
-    QMutexLocker locker(fontDatabaseMutex());
-    QFontDatabasePrivate *db = privateDb();
-    if (!db->count)
-        initializeDb();
-    for (int i = 0; i < family_list.size(); ++i) {
-        for (int k = 0; k < db->count; ++k) {
-            if (db->families[k]->name.compare(family_list.at(i), Qt::CaseInsensitive) == 0) {
-#if defined(QT_MAC_USE_COCOA)
-                CFStringRef familyName = QCFString::toCFStringRef(db->families[k]->name);
-                QCFType<CTFontDescriptorRef> descriptor = CTFontDescriptorCreateWithAttributes(
-                                    QCFType<CFDictionaryRef>(CFDictionaryCreate(kCFAllocatorDefault,
-                                        (const void**)&kCTFontFamilyNameAttribute,
-                                        (const void**)&familyName, 1,
-                                        &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)));
-                CFRelease(familyName);
-                QCFType<CTFontRef> ctFont = CTFontCreateWithFontDescriptor(descriptor, 0, NULL);
-                if (ctFont) {
-                    fontName = CTFontCopyFullName(ctFont);
-                    goto found;
-                }
-#else
-                familyRef = ATSFontFamilyFindFromName(QCFString(db->families[k]->name), kATSOptionFlagsDefault);
-                if (familyRef) {
-                    fontRef = ATSFontFindFromName(QCFString(db->families[k]->name), kATSOptionFlagsDefault);
-                    goto found;
-                }
-#endif
-            }
-        }
-    }
-found:
-#ifdef QT_MAC_USE_COCOA
-    if (fontName)
-        return new QCoreTextFontEngineMulti(fontName, req, d->kerning);
-#else
-    if (familyRef) {
-        QCFString actualName;
-        if (ATSFontFamilyGetName(familyRef, kATSOptionFlagsDefault, &actualName) == noErr)
-            req.family = actualName;
-        return new QFontEngineMacMulti(familyRef, fontRef, req, d->kerning);
-    }
-#endif
-    return NULL;
-}
-
-void QFontDatabase::load(const QFontPrivate *d, int script)
-{
-    // sanity checks
-    if(!qApp)
-        qWarning("QFont: Must construct a QApplication before a QFont");
-
-    Q_ASSERT(script >= 0 && script < QUnicodeTables::ScriptCount);
-    Q_UNUSED(script);
-
-    QFontDef req = d->request;
-    req.pixelSize = qt_mac_pixelsize(req, d->dpi);
-
-    // set the point size to 0 to get better caching
-    req.pointSize = 0;
-    QFontCache::Key key = QFontCache::Key(req, QUnicodeTables::Common, d->screen);
-
-    if(!(d->engineData = QFontCache::instance()->findEngineData(key))) {
-        d->engineData = new QFontEngineData;
-        QFontCache::instance()->insertEngineData(key, d->engineData);
-    } else {
-        d->engineData->ref.ref();
-    }
-    if(d->engineData->engine) // already loaded
-        return;
-
-    // set it to the actual pointsize, so QFontInfo will do the right thing
-    req.pointSize = qRound(qt_mac_pointsize(d->request, d->dpi));
-
-    QFontEngine *e = QFontCache::instance()->findEngine(key);
-    if(!e && qt_enable_test_font && req.family == QLatin1String("__Qt__Box__Engine__")) {
-        e = new QTestFontEngine(req.pixelSize);
-        e->fontDef = req;
-    }
-
-    if(e) {
-        e->ref.ref();
-        d->engineData->engine = e;
-        return; // the font info and fontdef should already be filled
-    }
-
-    QFontEngine *engine = NULL;
-#if defined(QT_MAC_USE_COCOA)
-    // Shortcut to get the font directly without going through the font database
-    if (!req.family.isEmpty() && !req.styleName.isEmpty()) {
-        QCFString expectedFamily = QCFString(req.family);
-        QCFString expectedStyle = QCFString(req.styleName);
-
-        QCFType<CFMutableDictionaryRef> attributes = CFDictionaryCreateMutable(NULL, 0,
-            &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
-        CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, expectedFamily);
-        CFDictionaryAddValue(attributes, kCTFontStyleNameAttribute, expectedStyle);
-
-        QCFType<CTFontDescriptorRef> descriptor = CTFontDescriptorCreateWithAttributes(attributes);
-        CGAffineTransform transform = qt_transform_from_fontdef(req);
-        QCFType<CTFontRef> ctFont = CTFontCreateWithFontDescriptor(descriptor, req.pixelSize, &transform);
-        if (ctFont) {
-            QCFString familyName = CTFontCopyFamilyName(ctFont);
-            // Only accept the font if the family name is exactly the same as we specified
-            if (CFEqual(expectedFamily, familyName)) {
-                engine = new QCoreTextFontEngineMulti(ctFont, req, d->kerning);
-            }
-        }
-    }
-#endif
-    if (!engine)
-        engine = loadFromDatabase(req, d);
-
-    if (engine) {
-        d->engineData->engine = engine;
-        engine->ref.ref();
-        QFontCache::instance()->insertEngine(key, engine);
-    }
-}
-
-static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
-{
-    ATSFontContainerRef handle;
-    OSStatus e  = noErr;
-
-    if(fnt->data.isEmpty()) {
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-                FSRef ref;
-                if(qt_mac_create_fsref(fnt->fileName, &ref) != noErr)
-                    return;
-
-                ATSFontActivateFromFileReference(&ref, kATSFontContextLocal, kATSFontFormatUnspecified, 0, kATSOptionFlagsDefault, &handle);
-        } else 
-#endif
-        {
-#ifndef Q_WS_MAC64
-                FSSpec spec;
-                if(qt_mac_create_fsspec(fnt->fileName, &spec) != noErr)
-                    return;
-
-                e = ATSFontActivateFromFileSpecification(&spec, kATSFontContextLocal, kATSFontFormatUnspecified,
-                                                   0, kATSOptionFlagsDefault, &handle);
-#endif
-        }
-    } else {
-        e = ATSFontActivateFromMemory((void *)fnt->data.constData(), fnt->data.size(), kATSFontContextLocal,
-                                           kATSFontFormatUnspecified, 0, kATSOptionFlagsDefault, &handle);
-
-        fnt->data = QByteArray();
-    }
-
-    if(e != noErr)
-        return;
-
-    ItemCount fontCount = 0;
-    e = ATSFontFindFromContainer(handle, kATSOptionFlagsDefault, 0, 0, &fontCount);
-    if(e != noErr)
-        return;
-
-    QVarLengthArray<ATSFontRef> containedFonts(fontCount);
-    e = ATSFontFindFromContainer(handle, kATSOptionFlagsDefault, fontCount, containedFonts.data(), &fontCount);
-    if(e != noErr)
-        return;
-
-    fnt->families.clear();
-#if defined(QT_MAC_USE_COCOA)
-    // Make sure that the family name set on the font matches what
-    // kCTFontFamilyNameAttribute returns in initializeDb().
-    // So far the best solution seems find the installed font
-    // using CoreText and get the family name from it.
-    // (ATSFontFamilyGetName appears to be the correct API, but also
-    // returns the font display name.)
-    for(int i = 0; i < containedFonts.size(); ++i) {
-        QCFString fontPostScriptName;
-        ATSFontGetPostScriptName(containedFonts[i], kATSOptionFlagsDefault, &fontPostScriptName);
-        QCFType<CTFontDescriptorRef> font = CTFontDescriptorCreateWithNameAndSize(fontPostScriptName, 14);
-        QCFString familyName = (CFStringRef)CTFontDescriptorCopyAttribute(font, kCTFontFamilyNameAttribute);
-        fnt->families.append(familyName);
-    }
-#else
-    for(int i = 0; i < containedFonts.size(); ++i) {
-        QCFString family;
-        ATSFontGetName(containedFonts[i], kATSOptionFlagsDefault, &family);
-        fnt->families.append(family);
-    }
-#endif
-
-    fnt->handle = handle;
-}
-
-bool QFontDatabase::removeApplicationFont(int handle)
-{
-    QMutexLocker locker(fontDatabaseMutex());
-
-    QFontDatabasePrivate *db = privateDb();
-    if(handle < 0 || handle >= db->applicationFonts.count())
-        return false;
-
-    OSStatus e = ATSFontDeactivate(db->applicationFonts.at(handle).handle,
-                                   /*iRefCon=*/0, kATSOptionFlagsDefault);
-    if(e != noErr)
-        return false;
-
-    db->applicationFonts[handle] = QFontDatabasePrivate::ApplicationFont();
-
-    db->invalidate();
-    return true;
-}
-
-bool QFontDatabase::removeAllApplicationFonts()
-{
-    QMutexLocker locker(fontDatabaseMutex());
-
-    QFontDatabasePrivate *db = privateDb();
-    for(int i = 0; i < db->applicationFonts.count(); ++i) {
-        if(!removeApplicationFont(i))
-            return false;
-    }
-    return true;
-}
-
-bool QFontDatabase::supportsThreadedFontRendering()
-{
-    return true;
-}
-
-QString QFontDatabase::resolveFontFamilyAlias(const QString &family)
-{
-    QCFString expectedFamily = QCFString(family);
-
-    QCFType<CFMutableDictionaryRef> attributes = CFDictionaryCreateMutable(NULL, 0,
-        &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
-    CFDictionaryAddValue(attributes, kCTFontFamilyNameAttribute, expectedFamily);
-    QCFType<CTFontDescriptorRef> descriptor = CTFontDescriptorCreateWithAttributes(attributes);
-
-    QCFType<CFMutableSetRef> mandatoryAttributes = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
-    CFSetAddValue(mandatoryAttributes, kCTFontFamilyNameAttribute);
-
-    QCFType<CTFontRef> font = CTFontCreateWithFontDescriptor(descriptor, 0.0, NULL);
-    QCFType<CTFontDescriptorRef> matched = CTFontDescriptorCreateMatchingFontDescriptor(descriptor, mandatoryAttributes);
-    if (!matched)
-        return family;
-
-    QCFString familyName = (CFStringRef) CTFontDescriptorCopyLocalizedAttribute(matched, kCTFontFamilyNameAttribute, NULL);
-    return familyName;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/text/qfontdatabase_win.h b/src/gui/text/qfontdatabase_win.h
deleted file mode 100644 (file)
index 55db6cb..0000000
+++ /dev/null
@@ -1,1348 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qt_windows.h"
-#include <qmath.h>
-#include <qapplication_p.h>
-#include "qfont_p.h"
-#include "qfontengine_p.h"
-#include "qpaintdevice.h"
-#include <qsystemlibrary_p.h>
-#include "qabstractfileengine.h"
-#include "qendian.h"
-
-#if !defined(QT_NO_DIRECTWRITE)
-#  include "qsettings.h"
-#  include "qfontenginedirectwrite_p.h"
-#endif
-
-#ifdef Q_OS_WINCE
-#   include <QTemporaryFile>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-extern HDC   shared_dc();                // common dc for all fonts
-
-#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)) \
-   )
-
-static HFONT stock_sysfont  = 0;
-
-static bool 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;
-}
-
-static inline quint16 getUShort(const unsigned char *p)
-{
-    quint16 val;
-    val = *p++ << 8;
-    val |= *p;
-
-    return val;
-}
-
-static QString getEnglishName(const uchar *table, quint32 bytes)
-{
-    QString i18n_name;
-    enum {
-        NameRecordSize = 12,
-        FamilyId = 1,
-        MS_LangIdEnglish = 0x009
-    };
-
-    // get the name table
-    quint16 count;
-    quint16 string_offset;
-    const unsigned char *names;
-
-    int microsoft_id = -1;
-    int apple_id = -1;
-    int unicode_id = -1;
-
-    if(getUShort(table) != 0)
-        goto error;
-
-    count = getUShort(table+2);
-    string_offset = getUShort(table+4);
-    names = table + 6;
-
-    if(string_offset >= bytes || 6 + count*NameRecordSize > string_offset)
-        goto error;
-
-    for(int i = 0; i < count; ++i) {
-        // search for the correct name entry
-
-        quint16 platform_id = getUShort(names + i*NameRecordSize);
-        quint16 encoding_id = getUShort(names + 2 + i*NameRecordSize);
-        quint16 language_id = getUShort(names + 4 + i*NameRecordSize);
-        quint16 name_id = getUShort(names + 6 + i*NameRecordSize);
-
-        if(name_id != FamilyId)
-            continue;
-
-        enum {
-            PlatformId_Unicode = 0,
-            PlatformId_Apple = 1,
-            PlatformId_Microsoft = 3
-        };
-
-        quint16 length = getUShort(names + 8 + i*NameRecordSize);
-        quint16 offset = 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
-            && microsoft_id == -1)
-            microsoft_id = i;
-            // not sure if encoding id 4 for Unicode is utf16 or ucs4...
-        else if(platform_id == PlatformId_Unicode && encoding_id < 4 && unicode_id == -1)
-            unicode_id = i;
-        else if(platform_id == PlatformId_Apple && encoding_id == 0 && language_id == 0)
-            apple_id = i;
-    }
-    {
-        bool unicode = false;
-        int id = -1;
-        if(microsoft_id != -1) {
-            id = microsoft_id;
-            unicode = true;
-        } else if(apple_id != -1) {
-            id = apple_id;
-            unicode = false;
-        } else if (unicode_id != -1) {
-            id = unicode_id;
-            unicode = true;
-        }
-        if(id != -1) {
-            quint16 length = getUShort(names + 8 + id*NameRecordSize);
-            quint16 offset = getUShort(names + 10 + id*NameRecordSize);
-            if(unicode) {
-                // utf16
-
-                length /= 2;
-                i18n_name.resize(length);
-                QChar *uc = (QChar *) i18n_name.unicode();
-                const unsigned char *string = table + string_offset + offset;
-                for(int i = 0; i < length; ++i)
-                    uc[i] = getUShort(string + 2*i);
-            } else {
-                // Apple Roman
-
-                i18n_name.resize(length);
-                QChar *uc = (QChar *) i18n_name.unicode();
-                const unsigned char *string = table + string_offset + offset;
-                for(int i = 0; i < length; ++i)
-                    uc[i] = QLatin1Char(string[i]);
-            }
-        }
-    }
-  error:
-    //qDebug("got i18n name of '%s' for font '%s'", i18n_name.latin1(), familyName.toLocal8Bit().data());
-    return i18n_name;
-}
-
-static QString getEnglishName(const QString &familyName)
-{
-    QString i18n_name;
-
-    HDC hdc = GetDC( 0 );
-    LOGFONT lf;
-    memset(&lf, 0, sizeof(LOGFONT));
-    memcpy(lf.lfFaceName, familyName.utf16(), qMin(LF_FACESIZE, familyName.length()) * sizeof(wchar_t));
-    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;
-
-    i18n_name = getEnglishName(table, bytes);
-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;
-}
-
-extern QFont::Weight weightFromInteger(int weight); // qfontdatabase.cpp
-
-static
-void addFontToDatabase(QString familyName, const QString &scriptName,
-                       TEXTMETRIC *textmetric,
-                       const FONTSIGNATURE *signature,
-                       int type)
-{
-    const int script = -1;
-    const QString foundryName;
-    Q_UNUSED(script);
-
-    bool italic = false;
-    int weight;
-    bool fixed;
-    bool ttf;
-    bool scalable;
-    int size;
-
-//    QString escript = QString::fromWCharArray(f->elfScript);
-//    qDebug("script=%s", escript.latin1());
-
-    NEWTEXTMETRIC *tm = (NEWTEXTMETRIC *)textmetric;
-    fixed = !(tm->tmPitchAndFamily & TMPF_FIXED_PITCH);
-    ttf = (tm->tmPitchAndFamily & TMPF_TRUETYPE);
-    scalable = tm->tmPitchAndFamily & (TMPF_VECTOR|TMPF_TRUETYPE);
-    size = scalable ? SMOOTH_SCALABLE : tm->tmHeight;
-    italic = tm->tmItalic;
-    weight = tm->tmWeight;
-
-    // the "@family" fonts are just the same as "family". Ignore them.
-    if (familyName[0] != QLatin1Char('@') && !familyName.startsWith(QLatin1String("WST_"))) {
-        QtFontStyle::Key styleKey;
-        styleKey.style = italic ? QFont::StyleItalic : QFont::StyleNormal;
-        styleKey.weight = weightFromInteger(weight);
-
-        QtFontFamily *family = privateDb()->family(familyName, true);
-
-        if(ttf && localizedName(familyName) && family->english_name.isEmpty())
-            family->english_name = getEnglishName(familyName);
-
-        QtFontFoundry *foundry = family->foundry(foundryName, true);
-        QtFontStyle *style = foundry->style(styleKey, QString(), true);
-        style->smoothScalable = scalable;
-        style->pixelSize( size, TRUE);
-
-        // add fonts windows can generate for us:
-        if (styleKey.weight <= QFont::DemiBold) {
-            QtFontStyle::Key key(styleKey);
-            key.weight = QFont::Bold;
-            QtFontStyle *style = foundry->style(key, QString(), true);
-            style->smoothScalable = scalable;
-            style->pixelSize( size, TRUE);
-        }
-        if (styleKey.style != QFont::StyleItalic) {
-            QtFontStyle::Key key(styleKey);
-            key.style = QFont::StyleItalic;
-            QtFontStyle *style = foundry->style(key, QString(), true);
-            style->smoothScalable = scalable;
-            style->pixelSize( size, TRUE);
-        }
-        if (styleKey.weight <= QFont::DemiBold && styleKey.style != QFont::StyleItalic) {
-            QtFontStyle::Key key(styleKey);
-            key.weight = QFont::Bold;
-            key.style = QFont::StyleItalic;
-            QtFontStyle *style = foundry->style(key, QString(), true);
-            style->smoothScalable = scalable;
-            style->pixelSize( size, TRUE);
-        }
-
-        family->fixedPitch = fixed;
-
-        if (!family->writingSystemCheck && type & TRUETYPE_FONTTYPE) {
-            quint32 unicodeRange[4] = {
-                signature->fsUsb[0], signature->fsUsb[1],
-                signature->fsUsb[2], signature->fsUsb[3]
-            };
-#ifdef Q_WS_WINCE
-            if (signature->fsUsb[0] == 0) {
-                // If the unicode ranges bit mask is zero then
-                // EnumFontFamiliesEx failed to determine it properly.
-                // In this case we just pretend that the font supports all languages.
-                unicodeRange[0] = 0xbfffffff;   // second most significant bit must be zero
-                unicodeRange[1] = 0xffffffff;
-                unicodeRange[2] = 0xffffffff;
-                unicodeRange[3] = 0xffffffff;
-            }
-#endif
-            quint32 codePageRange[2] = {
-                signature->fsCsb[0], signature->fsCsb[1]
-            };
-            QList<QFontDatabase::WritingSystem> systems = qt_determine_writing_systems_from_truetype_bits(unicodeRange, codePageRange);
-
-            for (int i = 0; i < systems.count(); ++i) {
-                QFontDatabase::WritingSystem writingSystem = systems.at(i);
-
-                // ### 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 (writingSystem != QFontDatabase::Thai || familyName != QLatin1String("Segoe UI"))
-                    family->writingSystems[writingSystem] = QtFontFamily::Supported;
-            }
-        } else if (!family->writingSystemCheck) {
-            //qDebug("family='%s' script=%s", family->name.latin1(), script.latin1());
-            if (scriptName == QLatin1String("Western")
-                || scriptName == QLatin1String("Baltic")
-                || scriptName == QLatin1String("Central European")
-                || scriptName == QLatin1String("Turkish")
-                || scriptName == QLatin1String("Vietnamese"))
-                family->writingSystems[QFontDatabase::Latin] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("Thai"))
-                family->writingSystems[QFontDatabase::Thai] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("Symbol")
-                     || scriptName == QLatin1String("Other"))
-                family->writingSystems[QFontDatabase::Symbol] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("OEM/Dos"))
-                family->writingSystems[QFontDatabase::Latin] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("CHINESE_GB2312"))
-                family->writingSystems[QFontDatabase::SimplifiedChinese] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("CHINESE_BIG5"))
-                family->writingSystems[QFontDatabase::TraditionalChinese] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("Cyrillic"))
-                family->writingSystems[QFontDatabase::Cyrillic] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("Hangul"))
-                family->writingSystems[QFontDatabase::Korean] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("Hebrew"))
-                family->writingSystems[QFontDatabase::Hebrew] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("Greek"))
-                family->writingSystems[QFontDatabase::Greek] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("Japanese"))
-                family->writingSystems[QFontDatabase::Japanese] = QtFontFamily::Supported;
-            else if (scriptName == QLatin1String("Arabic"))
-                family->writingSystems[QFontDatabase::Arabic] = QtFontFamily::Supported;
-        }
-    }
-}
-
-static
-int CALLBACK
-storeFont(ENUMLOGFONTEX* f, NEWTEXTMETRICEX *textmetric, int type, LPARAM /*p*/)
-{
-    QString familyName = QString::fromWCharArray(f->elfLogFont.lfFaceName);
-    QString script = QString::fromWCharArray(f->elfScript);
-
-    FONTSIGNATURE signature = textmetric->ntmFontSig;
-
-    // NEWTEXTMETRICEX 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
-    addFontToDatabase(familyName, script, (TEXTMETRIC *)textmetric, &signature, type);
-    // keep on enumerating
-    return 1;
-}
-
-static
-void populate_database(const QString& fam)
-{
-    QFontDatabasePrivate *d = privateDb();
-    if (!d)
-        return;
-
-    QtFontFamily *family = 0;
-    if(!fam.isEmpty()) {
-        family = d->family(fam);
-        if(family && family->loaded)
-            return;
-    } else if (d->count) {
-        return;
-    }
-
-    HDC dummy = GetDC(0);
-
-    LOGFONT lf;
-    lf.lfCharSet = DEFAULT_CHARSET;
-    if (fam.isNull()) {
-        lf.lfFaceName[0] = 0;
-    } else {
-        memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32));  // 32 = Windows hard-coded
-    }
-    lf.lfPitchAndFamily = 0;
-
-    EnumFontFamiliesEx(dummy, &lf,
-        (FONTENUMPROC)storeFont, (LPARAM)privateDb(), 0);
-
-    ReleaseDC(0, dummy);
-
-    for (int i = 0; i < d->applicationFonts.count(); ++i) {
-        QFontDatabasePrivate::ApplicationFont fnt = d->applicationFonts.at(i);
-        if (!fnt.memoryFont)
-            continue;
-        for (int j = 0; j < fnt.families.count(); ++j) {
-            const QString familyName = fnt.families.at(j);
-            HDC hdc = GetDC(0);
-            LOGFONT lf;
-            memset(&lf, 0, sizeof(LOGFONT));
-            memcpy(lf.lfFaceName, familyName.utf16(), sizeof(wchar_t) * qMin(LF_FACESIZE, familyName.size()));
-            lf.lfCharSet = DEFAULT_CHARSET;
-            HFONT hfont = CreateFontIndirect(&lf);
-            HGDIOBJ oldobj = SelectObject(hdc, hfont);
-
-            TEXTMETRIC textMetrics;
-            GetTextMetrics(hdc, &textMetrics);
-
-            addFontToDatabase(familyName, QString(),
-                              &textMetrics,
-                              &fnt.signatures.at(j),
-                              TRUETYPE_FONTTYPE);
-
-            SelectObject(hdc, oldobj);
-            DeleteObject(hfont);
-            ReleaseDC(0, hdc);
-        }
-    }
-
-    if(!fam.isEmpty()) {
-        family = d->family(fam);
-        if(family) {
-            if(!family->writingSystemCheck) {
-            }
-            family->loaded = true;
-        }
-    }
-}
-
-static void initializeDb()
-{
-    QFontDatabasePrivate *db = privateDb();
-    if (!db || db->count)
-        return;
-
-    populate_database(QString());
-
-#ifdef QFONTDATABASE_DEBUG
-    // print the database
-    for (int f = 0; f < db->count; f++) {
-        QtFontFamily *family = db->families[f];
-        qDebug("    %s: %p", qPrintable(family->name), family);
-        populate_database(family->name);
-
-#if 0
-        qDebug("        scripts supported:");
-        for (int i = 0; i < QUnicodeTables::ScriptCount; i++)
-            if(family->writingSystems[i] & QtFontFamily::Supported)
-                qDebug("            %d", i);
-        for (int fd = 0; fd < family->count; fd++) {
-            QtFontFoundry *foundry = family->foundries[fd];
-            qDebug("        %s", foundry->name.latin1());
-            for (int s = 0; s < foundry->count; s++) {
-                QtFontStyle *style = foundry->styles[s];
-                qDebug("            style: style=%d weight=%d smooth=%d",  style->key.style,
-                       style->key.weight, style->smoothScalable );
-                if(!style->smoothScalable) {
-                    for(int i = 0; i < style->count; ++i) {
-                        qDebug("                %d", style->pixelSizes[i].pixelSize);
-                    }
-                }
-            }
-        }
-#endif
-    }
-#endif // QFONTDATABASE_DEBUG
-
-}
-
-static inline void load(const QString &family = QString(), int = -1)
-{
-    populate_database(family);
-}
-
-
-
-
-
-// --------------------------------------------------------------------------------------
-// font loader
-// --------------------------------------------------------------------------------------
-
-
-
-static void initFontInfo(QFontEngineWin *fe, const QFontDef &request, HDC fontHdc, int dpi)
-{
-    fe->fontDef = request;                                // most settings are equal
-
-    HDC dc = ((request.styleStrategy & QFont::PreferDevice) && fontHdc) ? fontHdc : shared_dc();
-    SelectObject(dc, fe->hfont);
-    wchar_t n[64];
-    GetTextFace(dc, 64, n);
-    fe->fontDef.family = QString::fromWCharArray(n);
-    fe->fontDef.fixedPitch = !(fe->tm.tmPitchAndFamily & TMPF_FIXED_PITCH);
-    if (fe->fontDef.pointSize < 0) {
-        fe->fontDef.pointSize = fe->fontDef.pixelSize * 72. / dpi;
-    } else if (fe->fontDef.pixelSize == -1) {
-        fe->fontDef.pixelSize = qRound(fe->fontDef.pointSize * dpi / 72.);
-    }
-}
-
-#if !defined(QT_NO_DIRECTWRITE)
-static void initFontInfo(QFontEngineDirectWrite *fe, const QFontDef &request,
-                         int dpi, IDWriteFont *font)
-{
-    fe->fontDef = request;
-
-    IDWriteFontFamily *fontFamily = NULL;
-    HRESULT hr = font->GetFontFamily(&fontFamily);
-
-    IDWriteLocalizedStrings *familyNames = NULL;
-    if (SUCCEEDED(hr))
-        hr = fontFamily->GetFamilyNames(&familyNames);
-
-    UINT32 index = 0;
-    BOOL exists = false;
-
-    wchar_t localeName[LOCALE_NAME_MAX_LENGTH];
-
-    if (SUCCEEDED(hr)) {
-        int defaultLocaleSuccess = GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH);
-
-        if (defaultLocaleSuccess)
-            hr = familyNames->FindLocaleName(localeName, &index, &exists);
-
-        if (SUCCEEDED(hr) && !exists)
-            hr = familyNames->FindLocaleName(L"en-us", &index, &exists);
-    }
-
-    if (!exists)
-        index = 0;
-
-    UINT32 length = 0;
-    if (SUCCEEDED(hr))
-        hr = familyNames->GetStringLength(index, &length);
-
-    wchar_t *name = new (std::nothrow) wchar_t[length+1];
-    if (name == NULL)
-        hr = E_OUTOFMEMORY;
-
-    // Get the family name.
-    if (SUCCEEDED(hr))
-        hr = familyNames->GetString(index, name, length + 1);
-
-    if (SUCCEEDED(hr))
-        fe->fontDef.family = QString::fromWCharArray(name);
-
-    delete[] name;
-    if (familyNames != NULL)
-        familyNames->Release();
-
-    if (FAILED(hr))
-        qErrnoWarning(hr, "initFontInfo: Failed to get family name");
-
-    if (fe->fontDef.pointSize < 0)
-        fe->fontDef.pointSize = fe->fontDef.pixelSize * 72. / dpi;
-    else if (fe->fontDef.pixelSize == -1)
-        fe->fontDef.pixelSize = qRound(fe->fontDef.pointSize * dpi / 72.);
-}
-#endif
-
-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;
-
-#if !defined(QT_NO_DIRECTWRITE)
-static QString fontNameSubstitute(const QString &familyName)
-{
-    QLatin1String key("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\"
-                      "FontSubstitutes");
-    return QSettings(key, QSettings::NativeFormat).value(familyName, familyName).toString();
-}
-#endif
-
-static inline HFONT systemFont()
-{
-    if (stock_sysfont == 0)
-        stock_sysfont = (HFONT)GetStockObject(SYSTEM_FONT);
-    return stock_sysfont;
-}
-
-#if !defined(DEFAULT_GUI_FONT)
-#define DEFAULT_GUI_FONT 17
-#endif
-
-static QFontEngine *loadEngine(int script, const QFontDef &request,
-                               HDC fontHdc, int dpi, bool rawMode,
-                               const QtFontDesc *desc,
-                               const QStringList &family_list)
-{
-    LOGFONT lf;
-    memset(&lf, 0, sizeof(LOGFONT));
-
-    bool useDevice = (request.styleStrategy & QFont::PreferDevice) && fontHdc;
-
-    HDC hdc = shared_dc();
-    QString font_name = desc != 0 ? desc->family->name : request.family;
-
-    if (useDevice) {
-        hdc = fontHdc;
-        font_name = request.family;
-    }
-
-    bool stockFont = false;
-    bool preferClearTypeAA = false;
-
-    HFONT hfont = 0;
-
-
-#if !defined(QT_NO_DIRECTWRITE)
-    bool useDirectWrite = (request.hintingPreference == QFont::PreferNoHinting)
-                       || (request.hintingPreference == QFont::PreferVerticalHinting);
-    IDWriteFont *directWriteFont = 0;
-#else
-    bool useDirectWrite = false;
-#endif
-
-    if (rawMode) {                        // will choose a stock font
-        int f, deffnt = SYSTEM_FONT;
-        QString fam = desc != 0 ? desc->family->name.toLower() : request.family.toLower();
-        if (fam == QLatin1String("default"))
-            f = deffnt;
-        else if (fam == QLatin1String("system"))
-            f = SYSTEM_FONT;
-#ifndef Q_WS_WINCE
-        else if (fam == QLatin1String("system_fixed"))
-            f = SYSTEM_FIXED_FONT;
-        else if (fam == QLatin1String("ansi_fixed"))
-            f = ANSI_FIXED_FONT;
-        else if (fam == QLatin1String("ansi_var"))
-            f = ANSI_VAR_FONT;
-        else if (fam == QLatin1String("device_default"))
-            f = DEVICE_DEFAULT_FONT;
-        else if (fam == QLatin1String("oem_fixed"))
-            f = OEM_FIXED_FONT;
-#endif
-        else if (fam[0] == QLatin1Char('#'))
-            f = fam.right(fam.length()-1).toInt();
-        else
-            f = deffnt;
-        hfont = (HFONT)GetStockObject(f);
-        if (!hfont) {
-            qErrnoWarning("QFontEngine::loadEngine: GetStockObject failed");
-            hfont = systemFont();
-        }
-        stockFont = true;
-    } else {
-
-        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.lfHeight = -qRound(request.pixelSize);
-        lf.lfWidth                = 0;
-        lf.lfEscapement        = 0;
-        lf.lfOrientation        = 0;
-        if (desc == 0 || desc->style->key.weight == 50)
-            lf.lfWeight = FW_DONTCARE;
-        else
-            lf.lfWeight = (desc->style->key.weight*900)/99;
-        lf.lfItalic         = (desc != 0 && desc->style->key.style != QFont::StyleNormal);
-        lf.lfCharSet        = DEFAULT_CHARSET;
-
-        int strat = OUT_DEFAULT_PRECIS;
-        if (request.styleStrategy & QFont::PreferBitmap) {
-            strat = OUT_RASTER_PRECIS;
-#ifndef Q_WS_WINCE
-        } 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;
-#endif
-        }
-
-        lf.lfOutPrecision   = strat;
-
-        int qual = DEFAULT_QUALITY;
-
-        if (request.styleStrategy & QFont::PreferMatch)
-            qual = DRAFT_QUALITY;
-#ifndef Q_WS_WINCE
-        else if (request.styleStrategy & QFont::PreferQuality)
-            qual = PROOF_QUALITY;
-#endif
-
-        if (request.styleStrategy & QFont::PreferAntialias) {
-            if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
-                qual = CLEARTYPE_QUALITY;
-                preferClearTypeAA = true;
-            } else {
-                qual = ANTIALIASED_QUALITY;
-            }
-        } else if (request.styleStrategy & QFont::NoAntialias) {
-            qual = NONANTIALIASED_QUALITY;
-        }
-
-        lf.lfQuality        = qual;
-
-        lf.lfClipPrecision  = CLIP_DEFAULT_PRECIS;
-        lf.lfPitchAndFamily = DEFAULT_PITCH | hint;
-
-        QString fam = font_name;
-
-        if(fam.isEmpty())
-            fam = QLatin1String("MS Sans Serif");
-
-        if ((fam == QLatin1String("MS Sans Serif"))
-            && (request.style == QFont::StyleItalic || (-lf.lfHeight > 18 && -lf.lfHeight != 24))) {
-            fam = QLatin1String("Arial"); // MS Sans Serif has bearing problems in italic, and does not scale
-        }
-        if (fam == QLatin1String("Courier") && !(request.styleStrategy & QFont::PreferBitmap))
-            fam = QLatin1String("Courier New");
-
-        memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32));  // 32 = Windows hard-coded
-
-        hfont = CreateFontIndirect(&lf);
-        if (!hfont)
-            qErrnoWarning("QFontEngine::loadEngine: CreateFontIndirect failed");
-
-        stockFont = (hfont == 0);
-        bool ttf = false;
-        int avWidth = 0;
-        BOOL res;
-        HGDIOBJ oldObj = SelectObject(hdc, hfont);
-
-        TEXTMETRIC tm;
-        res = GetTextMetrics(hdc, &tm);
-        avWidth = tm.tmAveCharWidth;
-        ttf = tm.tmPitchAndFamily & TMPF_TRUETYPE;
-        SelectObject(hdc, oldObj);
-
-        if (!ttf || !useDirectWrite) {
-            useDirectWrite = false;
-
-            if (hfont && (!ttf || request.stretch != 100)) {
-                DeleteObject(hfont);
-                if (!res)
-                    qErrnoWarning("QFontEngine::loadEngine: GetTextMetrics failed");
-                lf.lfWidth = avWidth * request.stretch/100;
-                hfont = CreateFontIndirect(&lf);
-                if (!hfont)
-                    qErrnoWarning("QFontEngine::loadEngine: CreateFontIndirect with stretch failed");
-            }
-
-#ifndef Q_WS_WINCE
-            if (hfont == 0) {
-                hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
-                stockFont = true;
-            }
-#else
-            if (hfont == 0) {
-                hfont = (HFONT)GetStockObject(SYSTEM_FONT);
-                stockFont = true;
-            }
-#endif
-
-        }
-
-#if !defined(QT_NO_DIRECTWRITE)
-        else {
-            // Default to false for DirectWrite (and re-enable once/if everything
-            // turns out okay)
-            useDirectWrite = false;
-
-            QFontDatabasePrivate *db = privateDb();
-            if (db->directWriteFactory == 0) {
-                HRESULT hr = DWriteCreateFactory(
-                            DWRITE_FACTORY_TYPE_SHARED,
-                            __uuidof(IDWriteFactory),
-                            reinterpret_cast<IUnknown **>(&db->directWriteFactory)
-                            );
-                if (FAILED(hr)) {
-                    qErrnoWarning("QFontEngine::loadEngine: DWriteCreateFactory failed");
-                } else {
-                    hr = db->directWriteFactory->GetGdiInterop(&db->directWriteGdiInterop);
-                    if (FAILED(hr))
-                        qErrnoWarning("QFontEngine::loadEngine: GetGdiInterop failed");
-                }
-            }
-
-            if (db->directWriteGdiInterop != 0) {
-                QString nameSubstitute = fontNameSubstitute(QString::fromWCharArray(lf.lfFaceName));
-                memcpy(lf.lfFaceName, nameSubstitute.utf16(),
-                       sizeof(wchar_t) * qMin(nameSubstitute.length() + 1, LF_FACESIZE));
-
-                HRESULT hr = db->directWriteGdiInterop->CreateFontFromLOGFONT(
-                            &lf,
-                            &directWriteFont);
-                if (FAILED(hr)) {
-#ifndef QT_NO_DEBUG
-                    qErrnoWarning("QFontEngine::loadEngine: CreateFontFromLOGFONT failed "
-                                  "for %ls (0x%lx)",
-                                  lf.lfFaceName, hr);
-#endif
-                } else {
-                    DeleteObject(hfont);
-                    useDirectWrite = true;
-                }
-            }
-        }
-#endif
-
-    }
-
-    QFontEngine *fe = 0;
-    if (!useDirectWrite)  {
-        QFontEngineWin *few = new QFontEngineWin(font_name, hfont, stockFont, lf);
-        if (preferClearTypeAA)
-            few->glyphFormat = QFontEngineGlyphCache::Raster_RGBMask;
-
-        // Also check for OpenType tables when using complex scripts
-        // ### TODO: This only works for scripts that require OpenType. More generally
-        // for scripts that do not require OpenType we should just look at the list of
-        // supported writing systems in the font's OS/2 table.
-        if (scriptRequiresOpenType(script)) {
-            HB_Face hbFace = few->harfbuzzFace();
-            if (!hbFace || !hbFace->supported_scripts[script]) {
-                FM_DEBUG("  OpenType support missing for script\n");
-                delete few;
-                return 0;
-            }
-        }
-
-        initFontInfo(few, request, fontHdc, dpi);
-        fe = few;
-    }
-
-#if !defined(QT_NO_DIRECTWRITE)
-    else {
-        QFontDatabasePrivate *db = privateDb();
-
-        IDWriteFontFace *directWriteFontFace = NULL;
-        HRESULT hr = directWriteFont->CreateFontFace(&directWriteFontFace);
-        if (SUCCEEDED(hr)) {
-            QFontEngineDirectWrite *fedw = new QFontEngineDirectWrite(db->directWriteFactory,
-                                                                      directWriteFontFace,
-                                                                      request.pixelSize);
-
-            initFontInfo(fedw, request, dpi, directWriteFont);
-
-            fe = fedw;
-        } else {
-            qErrnoWarning(hr, "QFontEngine::loadEngine: CreateFontFace failed");
-        }
-    }
-
-    if (directWriteFont != 0)
-        directWriteFont->Release();
-#endif
-
-    if(script == QUnicodeTables::Common
-       && !(request.styleStrategy & QFont::NoFontMerging)
-       && desc != 0
-       && !(desc->family->writingSystems[QFontDatabase::Symbol] & QtFontFamily::Supported)) {
-        if(!tryFonts) {
-            LANGID lid = GetUserDefaultLangID();
-            switch( lid&0xff ) {
-            case LANG_CHINESE: // Chinese (Taiwan)
-                if ( lid == 0x0804 ) // Taiwan
-                    tryFonts = ch_TW_tryFonts;
-                else
-                    tryFonts = ch_CN_tryFonts;
-                break;
-            case LANG_JAPANESE:
-                tryFonts = jp_tryFonts;
-                break;
-            case LANG_KOREAN:
-                tryFonts = kr_tryFonts;
-                break;
-            default:
-                tryFonts = other_tryFonts;
-                break;
-            }
-        }
-        QStringList fm = QFontDatabase().families();
-        QStringList list = family_list;
-        const char **tf = tryFonts;
-        while(tf && *tf) {
-            if(fm.contains(QLatin1String(*tf)))
-                list << QLatin1String(*tf);
-            ++tf;
-        }
-        QFontEngine *mfe = new QFontEngineMultiWin(fe, list);
-        mfe->fontDef = fe->fontDef;
-        fe = mfe;
-    }
-    return fe;
-}
-
-QFontEngine *qt_load_font_engine_win(const QFontDef &request)
-{
-    // From qfont.cpp
-    extern int qt_defaultDpi();
-
-    QFontCache::Key key(request, QUnicodeTables::Common);
-    QFontEngine *fe = QFontCache::instance()->findEngine(key);
-    if (fe != 0)
-        return fe;
-    else
-        return loadEngine(QUnicodeTables::Common, request, 0, qt_defaultDpi(), false, 0,
-                          QStringList());
-}
-
-const char *styleHint(const QFontDef &request)
-{
-    const char *stylehint = 0;
-    switch (request.styleHint) {
-    case QFont::SansSerif:
-        stylehint = "Arial";
-        break;
-    case QFont::Serif:
-        stylehint = "Times New Roman";
-        break;
-    case QFont::TypeWriter:
-        stylehint = "Courier New";
-        break;
-    default:
-        if (request.fixedPitch)
-            stylehint = "Courier New";
-        break;
-    }
-    return stylehint;
-}
-
-static QFontEngine *loadWin(const QFontPrivate *d, int script, const QFontDef &req)
-{
-    // list of families to try
-    QStringList family_list = familyList(req);
-
-    const char *stylehint = styleHint(d->request);
-    if (stylehint)
-        family_list << QLatin1String(stylehint);
-
-    // append the default fallback font for the specified script
-    // family_list << ... ; ###########
-
-    // add the default family
-    QString defaultFamily = QApplication::font().family();
-    if (! family_list.contains(defaultFamily))
-        family_list << defaultFamily;
-
-    // add QFont::defaultFamily() to the list, for compatibility with
-    // previous versions
-    family_list << QApplication::font().defaultFamily();
-
-    // null family means find the first font matching the specified script
-    family_list << QString();
-
-    QtFontDesc desc;
-    QFontEngine *fe = 0;
-    QList<int> blacklistedFamilies;
-
-    while (!fe) {
-        for (int i = 0; i < family_list.size(); ++i) {
-            QString family, foundry;
-            parseFontName(family_list.at(i), foundry, family);
-            FM_DEBUG("loadWin: >>>>>>>>>>>>>>trying to match '%s'", family.toLatin1().data());
-            QT_PREPEND_NAMESPACE(match)(script, req, family, foundry, -1, &desc, blacklistedFamilies);
-            if (desc.family)
-                break;
-        }
-        if (!desc.family)
-            break;
-        fe = loadEngine(script, req, d->hdc, d->dpi, d->rawMode, &desc, family_list);
-        if (!fe)
-            blacklistedFamilies.append(desc.familyIndex);
-    }
-    return fe;
-}
-
-void QFontDatabase::load(const QFontPrivate *d, int script)
-{
-    // sanity checks
-    if (!qApp)
-        qWarning("QFontDatabase::load: Must construct QApplication first");
-    Q_ASSERT(script >= 0 && script < QUnicodeTables::ScriptCount);
-
-    // normalize the request to get better caching
-    QFontDef req = d->request;
-    if (req.pixelSize <= 0)
-        req.pixelSize = floor((100.0 * req.pointSize * d->dpi) / 72. + 0.5) / 100;
-    if (req.pixelSize < 1)
-        req.pixelSize = 1;
-    if (req.weight == 0)
-        req.weight = QFont::Normal;
-    if (req.stretch == 0)
-        req.stretch = 100;
-
-    QFontCache::Key key(req, d->rawMode ? QUnicodeTables::Common : script, d->screen);
-    if (!d->engineData)
-        getEngineData(d, key);
-
-    // the cached engineData could have already loaded the engine we want
-    if (d->engineData->engines[script])
-        return;
-
-    QFontEngine *fe = QFontCache::instance()->findEngine(key);
-
-    // set it to the actual pointsize, so QFontInfo will do the right thing
-    if (req.pointSize < 0)
-        req.pointSize = req.pixelSize*72./d->dpi;
-
-    if (!fe) {
-        if (qt_enable_test_font && req.family == QLatin1String("__Qt__Box__Engine__")) {
-            fe = new QTestFontEngine(req.pixelSize);
-            fe->fontDef = req;
-        } else {
-            QMutexLocker locker(fontDatabaseMutex());
-            if (!privateDb()->count)
-                initializeDb();
-            fe = loadWin(d, script, req);
-        }
-        if (!fe) {
-            fe = new QFontEngineBox(req.pixelSize);
-            fe->fontDef = QFontDef();
-        }
-    }
-    d->engineData->engines[script] = fe;
-    fe->ref.ref();
-    QFontCache::instance()->insertEngine(key, fe);
-}
-
-#if !defined(FR_PRIVATE)
-#define FR_PRIVATE 0x10
-#endif
-
-typedef int (WINAPI *PtrAddFontResourceExW)(LPCWSTR, DWORD, PVOID);
-typedef HANDLE (WINAPI *PtrAddFontMemResourceEx)(PVOID, DWORD, PVOID, DWORD *);
-typedef BOOL (WINAPI *PtrRemoveFontResourceExW)(LPCWSTR, DWORD, PVOID);
-typedef BOOL (WINAPI *PtrRemoveFontMemResourceEx)(HANDLE);
-
-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, QFontDatabasePrivate::ApplicationFont *appFont)
-{
-    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;
-        QString name = getEnglishName(table, length);
-        if (name.isEmpty())
-            continue;
-
-        appFont->families << name;
-        FONTSIGNATURE signature;
-        getFontTable(data, font, MAKE_TAG('O', 'S', '/', '2'), &table, &length);
-        if (table && length >= 86) {
-            // See also qfontdatabase_mac.cpp, 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));
-        }
-        appFont->signatures << signature;
-    }
-}
-
-static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
-{
-    if(!fnt->data.isEmpty()) {
-#ifndef Q_OS_WINCE
-        PtrAddFontMemResourceEx ptrAddFontMemResourceEx = (PtrAddFontMemResourceEx)QSystemLibrary::resolve(QLatin1String("gdi32"),
-                                                                                                     "AddFontMemResourceEx");
-        if (!ptrAddFontMemResourceEx)
-            return;
-#endif
-        getFamiliesAndSignatures(fnt->data, fnt);
-        if (fnt->families.isEmpty())
-            return;
-
-#ifdef Q_OS_WINCE
-        HANDLE handle = 0;
-
-        {
-#ifdef QT_NO_TEMPORARYFILE
-           wchar_t lpBuffer[MAX_PATH];
-           GetTempPath(MAX_PATH, lpBuffer);
-           QString s = QString::fromWCharArray(lpBuffer);
-           QFile tempfile(s + QLatin1String("/font") + QString::number(GetTickCount()) + QLatin1String(".ttf"));
-           if (!tempfile.open(QIODevice::ReadWrite))
-#else
-            QTemporaryFile tempfile(QLatin1String("XXXXXXXX.ttf"));
-            if (!tempfile.open())
-#endif // QT_NO_TEMPORARYFILE
-                return;
-            if (tempfile.write(fnt->data) == -1)
-                return;
-
-#ifndef QT_NO_TEMPORARYFILE
-            tempfile.setAutoRemove(false);
-#endif
-            fnt->fileName = QFileInfo(tempfile.fileName()).absoluteFilePath();
-        }
-
-        if (AddFontResource((LPCWSTR)fnt->fileName.utf16()) == 0) {
-            QFile(fnt->fileName).remove();
-            return;
-        }
-#else
-        DWORD dummy = 0;
-        HANDLE handle = ptrAddFontMemResourceEx((void *)fnt->data.constData(), fnt->data.size(), 0,
-                                                &dummy);
-        if (handle == 0)
-            return;
-#endif // Q_OS_WINCE
-
-        fnt->handle = handle;
-        fnt->data = QByteArray();
-        fnt->memoryFont = true;
-    } else {
-        QFile f(fnt->fileName);
-        if (!f.open(QIODevice::ReadOnly))
-            return;
-        QByteArray data = f.readAll();
-        f.close();
-        getFamiliesAndSignatures(data, fnt);
-
-#ifdef Q_OS_WINCE
-        QFileInfo fileinfo(fnt->fileName);
-        fnt->fileName = fileinfo.absoluteFilePath();
-        if (AddFontResource((LPCWSTR)fnt->fileName.utf16()) == 0)
-            return;
-#else
-        PtrAddFontResourceExW ptrAddFontResourceExW = (PtrAddFontResourceExW)QSystemLibrary::resolve(QLatin1String("gdi32"),
-                                                                                               "AddFontResourceExW");
-        if (!ptrAddFontResourceExW
-            || ptrAddFontResourceExW((wchar_t*)fnt->fileName.utf16(), FR_PRIVATE, 0) == 0)
-            return;
-#endif // Q_OS_WINCE
-
-        fnt->memoryFont = false;
-    }
-}
-
-bool QFontDatabase::removeApplicationFont(int handle)
-{
-    QMutexLocker locker(fontDatabaseMutex());
-
-    QFontDatabasePrivate *db = privateDb();
-    if (handle < 0 || handle >= db->applicationFonts.count())
-        return false;
-
-    const QFontDatabasePrivate::ApplicationFont font = db->applicationFonts.at(handle);
-    db->applicationFonts[handle] = QFontDatabasePrivate::ApplicationFont();
-    if (font.memoryFont) {
-#ifdef Q_OS_WINCE
-        bool removeSucceeded = RemoveFontResource((LPCWSTR)font.fileName.utf16());
-        QFile tempfile(font.fileName);
-        tempfile.remove();
-        if (!removeSucceeded)
-            return false;
-#else
-        PtrRemoveFontMemResourceEx ptrRemoveFontMemResourceEx = (PtrRemoveFontMemResourceEx)QSystemLibrary::resolve(QLatin1String("gdi32"),
-                                                                                                              "RemoveFontMemResourceEx");
-        if (!ptrRemoveFontMemResourceEx
-            || !ptrRemoveFontMemResourceEx(font.handle))
-            return false;
-#endif // Q_OS_WINCE
-    } else {
-#ifdef Q_OS_WINCE
-        if (!RemoveFontResource((LPCWSTR)font.fileName.utf16()))
-            return false;
-#else
-        PtrRemoveFontResourceExW ptrRemoveFontResourceExW = (PtrRemoveFontResourceExW)QSystemLibrary::resolve(QLatin1String("gdi32"),
-                                                                                                        "RemoveFontResourceExW");
-        if (!ptrRemoveFontResourceExW
-            || !ptrRemoveFontResourceExW((LPCWSTR)font.fileName.utf16(), FR_PRIVATE, 0))
-            return false;
-#endif // Q_OS_WINCE
-    }
-
-    db->invalidate();
-    return true;
-}
-
-bool QFontDatabase::removeAllApplicationFonts()
-{
-    QMutexLocker locker(fontDatabaseMutex());
-
-    QFontDatabasePrivate *db = privateDb();
-    for (int i = 0; i < db->applicationFonts.count(); ++i)
-        if (!removeApplicationFont(i))
-            return false;
-    return true;
-}
-
-bool QFontDatabase::supportsThreadedFontRendering()
-{
-    return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/text/qfontengine_coretext.mm b/src/gui/text/qfontengine_coretext.mm
deleted file mode 100644 (file)
index bc0777f..0000000
+++ /dev/null
@@ -1,943 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfontengine_coretext_p.h"
-
-#include <QtCore/qendian.h>
-#include <QtCore/qsettings.h>
-
-#include <qimage_p.h>
-
-#if !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-
-QT_BEGIN_NAMESPACE
-
-static float SYNTHETIC_ITALIC_SKEW = tanf(14 * acosf(0) / 90);
-
-static void loadAdvancesForGlyphs(CTFontRef ctfont,
-                                  QVarLengthArray<CGGlyph> &cgGlyphs,
-                                  QGlyphLayout *glyphs, int len,
-                                  QTextEngine::ShaperFlags flags,
-                                  const QFontDef &fontDef)
-{
-    Q_UNUSED(flags);
-    QVarLengthArray<CGSize> advances(len);
-    CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, cgGlyphs.data(), advances.data(), len);
-
-    for (int i = 0; i < len; ++i) {
-        if (glyphs->glyphs[i] & 0xff000000)
-            continue;
-        glyphs->advances_x[i] = QFixed::fromReal(advances[i].width);
-        glyphs->advances_y[i] = QFixed::fromReal(advances[i].height);
-    }
-
-    if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
-        for (int i = 0; i < len; ++i) {
-            glyphs->advances_x[i] = glyphs->advances_x[i].round();
-            glyphs->advances_y[i] = glyphs->advances_y[i].round();
-        }
-    }
-}
-
-QCoreTextFontEngineMulti::QCoreTextFontEngineMulti(const QCFString &name, const QFontDef &fontDef, bool kerning)
-    : QFontEngineMulti(0)
-{
-    this->fontDef = fontDef;
-    CTFontSymbolicTraits symbolicTraits = 0;
-    if (fontDef.weight >= QFont::Bold)
-        symbolicTraits |= kCTFontBoldTrait;
-    switch (fontDef.style) {
-    case QFont::StyleNormal:
-        break;
-    case QFont::StyleItalic:
-    case QFont::StyleOblique:
-        symbolicTraits |= kCTFontItalicTrait;
-        break;
-    }
-
-    transform = CGAffineTransformIdentity;
-    if (fontDef.stretch != 100) {
-        transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
-    }
-    transformAdvances = QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7;
-
-    QCFType<CTFontDescriptorRef> descriptor = CTFontDescriptorCreateWithNameAndSize(name, fontDef.pixelSize);
-    QCFType<CTFontRef> baseFont = CTFontCreateWithFontDescriptor(descriptor, fontDef.pixelSize, &transform);
-    ctfont = NULL;
-    // There is a side effect in Core Text: if we apply 0 as symbolic traits to a font in normal weight,
-    // we will get the light version of that font (while the way supposed to work doesn't:
-    // setting kCTFontWeightTrait to some value between -1.0 to 0.0 has no effect on font selection)
-    if (fontDef.weight != QFont::Normal || symbolicTraits)
-        ctfont = CTFontCreateCopyWithSymbolicTraits(baseFont, fontDef.pixelSize, &transform, symbolicTraits, symbolicTraits);
-
-    // CTFontCreateCopyWithSymbolicTraits returns NULL if we ask for a trait that does
-    // not exist for the given font. (for example italic)
-    if (ctfont == 0) {
-        ctfont = baseFont;
-        CFRetain(ctfont);
-    }
-    init(kerning);
-}
-
-QCoreTextFontEngineMulti::QCoreTextFontEngineMulti(CTFontRef ctFontRef, const QFontDef &fontDef, bool kerning)
-    : QFontEngineMulti(0)
-{
-    this->fontDef = fontDef;
-    ctfont = (CTFontRef) CFRetain(ctFontRef);
-    init(kerning);
-}
-
-QCoreTextFontEngineMulti::~QCoreTextFontEngineMulti()
-{
-    CFRelease(ctfont);
-}
-
-void QCoreTextFontEngineMulti::init(bool kerning)
-{
-    Q_ASSERT(ctfont != NULL);
-    attributeDict = CFDictionaryCreateMutable(0, 2,
-                                       &kCFTypeDictionaryKeyCallBacks,
-                                       &kCFTypeDictionaryValueCallBacks);
-    CFDictionaryAddValue(attributeDict, kCTFontAttributeName, ctfont);
-    if (!kerning) {
-        float zero = 0.0;
-        QCFType<CFNumberRef> noKern = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &zero);
-        CFDictionaryAddValue(attributeDict, kCTKernAttributeName, noKern);
-    }
-
-    QCoreTextFontEngine *fe = new QCoreTextFontEngine(ctfont, fontDef);
-    fontDef.family = fe->fontDef.family;
-    fontDef.styleName = fe->fontDef.styleName;
-    transform = fe->transform;
-    fe->ref.ref();
-    engines.append(fe);
-}
-
-uint QCoreTextFontEngineMulti::fontIndexForFont(CTFontRef font) const
-{
-    for (int i = 0; i < engines.count(); ++i) {
-        if (CFEqual(engineAt(i)->ctfont, font))
-            return i;
-    }
-
-    QCoreTextFontEngineMulti *that = const_cast<QCoreTextFontEngineMulti *>(this);
-    QCoreTextFontEngine *fe = new QCoreTextFontEngine(font, fontDef);
-    fe->ref.ref();
-    that->engines.append(fe);
-    return engines.count() - 1;
-}
-
-bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
-                                            int *nglyphs, QTextEngine::ShaperFlags flags,
-                                            unsigned short *logClusters, const HB_CharAttributes *,
-                                            QScriptItem *si) const
-{
-    QCFType<CFStringRef> cfstring = CFStringCreateWithCharactersNoCopy(0,
-                                                               reinterpret_cast<const UniChar *>(str),
-                                                               len, kCFAllocatorNull);
-    QCFType<CFAttributedStringRef> attributedString = CFAttributedStringCreate(0, cfstring, attributeDict);
-    QCFType<CTTypesetterRef> typeSetter;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
-    if (flags & QTextEngine::RightToLeft) {
-        const void *optionKeys[] = { kCTTypesetterOptionForcedEmbeddingLevel };
-        const short rtlForcedEmbeddingLevelValue = 1;
-        const void *rtlOptionValues[] = { CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &rtlForcedEmbeddingLevelValue) };
-        QCFType<CFDictionaryRef> options = CFDictionaryCreate(kCFAllocatorDefault, optionKeys, rtlOptionValues, 1,
-                                                              &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
-        typeSetter = CTTypesetterCreateWithAttributedStringAndOptions(attributedString, options);
-    } else
-#else
-    Q_UNUSED(flags);
-#endif
-        typeSetter = CTTypesetterCreateWithAttributedString(attributedString);
-
-    CFRange range = {0, 0};
-    QCFType<CTLineRef> line = CTTypesetterCreateLine(typeSetter, range);
-    CFArrayRef array = CTLineGetGlyphRuns(line);
-    uint arraySize = CFArrayGetCount(array);
-    glyph_t *outGlyphs = glyphs->glyphs;
-    HB_GlyphAttributes *outAttributes = glyphs->attributes;
-    QFixed *outAdvances_x = glyphs->advances_x;
-    QFixed *outAdvances_y = glyphs->advances_y;
-    glyph_t *initialGlyph = outGlyphs;
-
-    if (arraySize == 0) {
-        // CoreText failed to shape the text we gave it, so we assume one glyph
-        // per character and build a list of invalid glyphs with zero advance
-        *nglyphs = len;
-        for (int i = 0; i < len; ++i) {
-            outGlyphs[i] = 0;
-            if (logClusters)
-                logClusters[i] = i;
-            outAdvances_x[i] = QFixed();
-            outAdvances_y[i] = QFixed();
-            outAttributes[i].clusterStart = true;
-        }
-        return true;
-    }
-
-    const bool rtl = (CTRunGetStatus(static_cast<CTRunRef>(CFArrayGetValueAtIndex(array, 0))) & kCTRunStatusRightToLeft);
-
-    bool outOBounds = false;
-    for (uint i = 0; i < arraySize; ++i) {
-        CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex(array, rtl ? (arraySize - 1 - i) : i));
-        CFIndex glyphCount = CTRunGetGlyphCount(run);
-        if (glyphCount == 0)
-            continue;
-
-        Q_ASSERT((CTRunGetStatus(run) & kCTRunStatusRightToLeft) == rtl);
-        CFRange stringRange = CTRunGetStringRange(run);
-        CGAffineTransform textMatrix = CTRunGetTextMatrix(run);
-        int prepend = 0;
-#if MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5
-        UniChar beginGlyph = CFStringGetCharacterAtIndex(cfstring, stringRange.location);
-        QChar dir = QChar::direction(beginGlyph);
-        bool beginWithOverride = dir == QChar::DirLRO || dir == QChar::DirRLO || dir == QChar::DirLRE || dir == QChar::DirRLE;
-        if (beginWithOverride) {
-            logClusters[stringRange.location] = 0;
-            outGlyphs[0] = 0xFFFF;
-            outAdvances_x[0] = 0;
-            outAdvances_y[0] = 0;
-            outAttributes[0].clusterStart = true;
-            outAttributes[0].dontPrint = true;
-            outGlyphs++;
-            outAdvances_x++;
-            outAdvances_y++;
-            outAttributes++;
-            prepend = 1;
-        }
-#endif
-        UniChar endGlyph = CFStringGetCharacterAtIndex(cfstring, stringRange.location + stringRange.length - 1);
-        bool endWithPDF = QChar::direction(endGlyph) == QChar::DirPDF;
-        if (endWithPDF)
-            glyphCount++;
-
-        if (!outOBounds && outGlyphs + glyphCount - initialGlyph > *nglyphs) {
-            outOBounds = true;
-        }
-        if (!outOBounds) {
-            CFDictionaryRef runAttribs = CTRunGetAttributes(run);
-            //NSLog(@"Dictionary %@", runAttribs);
-            if (!runAttribs)
-                runAttribs = attributeDict;
-            CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttribs, kCTFontAttributeName));
-            uint fontIndex = fontIndexForFont(runFont);
-            const QFontEngine *engine = engineAt(fontIndex);
-            fontIndex <<= 24;
-            si->ascent = qMax(engine->ascent(), si->ascent);
-            si->descent = qMax(engine->descent(), si->descent);
-            si->leading = qMax(engine->leading(), si->leading);
-            //NSLog(@"Run Font Name = %@", CTFontCopyFamilyName(runFont));
-            if (endWithPDF)
-                glyphCount--;
-
-            QVarLengthArray<CGGlyph, 512> cgglyphs(0);
-            const CGGlyph *tmpGlyphs = CTRunGetGlyphsPtr(run);
-            if (!tmpGlyphs) {
-                cgglyphs.resize(glyphCount);
-                CTRunGetGlyphs(run, range, cgglyphs.data());
-                tmpGlyphs = cgglyphs.constData();
-            }
-            QVarLengthArray<CGPoint, 512> cgpoints(0);
-            const CGPoint *tmpPoints = CTRunGetPositionsPtr(run);
-            if (!tmpPoints) {
-                cgpoints.resize(glyphCount);
-                CTRunGetPositions(run, range, cgpoints.data());
-                tmpPoints = cgpoints.constData();
-            }
-
-            const int rtlOffset = rtl ? (glyphCount - 1) : 0;
-            const int rtlSign = rtl ? -1 : 1;
-
-            if (logClusters) {
-                CFRange stringRange = CTRunGetStringRange(run);
-                QVarLengthArray<CFIndex, 512> stringIndices(0);
-                const CFIndex *tmpIndices = CTRunGetStringIndicesPtr(run);
-                if (!tmpIndices) {
-                    stringIndices.resize(glyphCount);
-                    CTRunGetStringIndices(run, range, stringIndices.data());
-                    tmpIndices = stringIndices.constData();
-                }
-
-                const int firstGlyphIndex = outGlyphs - initialGlyph;
-                outAttributes[0].clusterStart = true;
-
-                CFIndex k = 0;
-                CFIndex i = 0;
-                for (i = stringRange.location + prepend;
-                     (i < stringRange.location + stringRange.length) && (k < glyphCount); ++i) {
-                    if (tmpIndices[k * rtlSign + rtlOffset] == i || i == stringRange.location + prepend) {
-                        logClusters[i] = k + firstGlyphIndex;
-                        outAttributes[k].clusterStart = true;
-                        ++k;
-                    } else {
-                        logClusters[i] = k + firstGlyphIndex - 1;
-                    }
-                }
-                // in case of a ligature at the end, fill the remaining logcluster entries
-                for (;i < stringRange.location + stringRange.length; i++) {
-                    logClusters[i] = k + firstGlyphIndex - 1;
-                }
-            }
-            for (CFIndex i = 0; i < glyphCount - 1; ++i) {
-                int idx = rtlOffset + rtlSign * i;
-                outGlyphs[idx] = tmpGlyphs[i] | fontIndex;
-                CGSize advance = CGSizeMake(tmpPoints[i + 1].x - tmpPoints[i].x, tmpPoints[i].y - tmpPoints[i + 1].y);
-                if (transformAdvances)
-                    advance = CGSizeApplyAffineTransform(advance, textMatrix);
-
-                outAdvances_x[idx] = QFixed::fromReal(advance.width);
-                // Use negative y advance for flipped coordinate system
-                outAdvances_y[idx] = QFixed::fromReal(advance.height);
-
-                if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
-                    outAdvances_x[idx] = outAdvances_x[idx].round();
-                    outAdvances_y[idx] = outAdvances_y[idx].round();
-                }
-            }
-            CGSize lastGlyphAdvance;
-            CTFontGetAdvancesForGlyphs(runFont, kCTFontHorizontalOrientation, tmpGlyphs + glyphCount - 1, &lastGlyphAdvance, 1);
-
-            outGlyphs[rtl ? 0 : (glyphCount - 1)] = tmpGlyphs[glyphCount - 1] | fontIndex;
-            outAdvances_x[rtl ? 0 : (glyphCount - 1)] =
-                    (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
-                    ? QFixed::fromReal(lastGlyphAdvance.width).round()
-                    : QFixed::fromReal(lastGlyphAdvance.width);
-
-            if (endWithPDF) {
-                logClusters[stringRange.location + stringRange.length - 1] = glyphCount + prepend;
-                outGlyphs[glyphCount] = 0xFFFF;
-                outAdvances_x[glyphCount] = 0;
-                outAdvances_y[glyphCount] = 0;
-                outAttributes[glyphCount].clusterStart = true;
-                outAttributes[glyphCount].dontPrint = true;
-                glyphCount++;
-            }
-        }
-        outGlyphs += glyphCount;
-        outAttributes += glyphCount;
-        outAdvances_x += glyphCount;
-        outAdvances_y += glyphCount;
-    }
-    *nglyphs = (outGlyphs - initialGlyph);
-    return !outOBounds;
-}
-
-bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
-                                            int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
-    *nglyphs = len;
-    QCFType<CFStringRef> cfstring;
-
-    QVarLengthArray<CGGlyph> cgGlyphs(len);
-    CTFontGetGlyphsForCharacters(ctfont, (const UniChar*)str, cgGlyphs.data(), len);
-
-    for (int i = 0; i < len; ++i) {
-        if (cgGlyphs[i]) {
-            glyphs->glyphs[i] = cgGlyphs[i];
-        } else {
-            if (!cfstring)
-                cfstring = CFStringCreateWithCharactersNoCopy(0, reinterpret_cast<const UniChar *>(str), len, kCFAllocatorNull);
-            QCFType<CTFontRef> substituteFont = CTFontCreateForString(ctfont, cfstring, CFRangeMake(i, 1));
-            CGGlyph substituteGlyph = 0;
-            CTFontGetGlyphsForCharacters(substituteFont, (const UniChar*)str + i, &substituteGlyph, 1);
-            if (substituteGlyph) {
-                const uint fontIndex = (fontIndexForFont(substituteFont) << 24);
-                glyphs->glyphs[i] = substituteGlyph | fontIndex;
-                if (!(flags & QTextEngine::GlyphIndicesOnly)) {
-                    CGSize advance;
-                    CTFontGetAdvancesForGlyphs(substituteFont, kCTFontHorizontalOrientation, &substituteGlyph, &advance, 1);
-                    glyphs->advances_x[i] = QFixed::fromReal(advance.width);
-                    glyphs->advances_y[i] = QFixed::fromReal(advance.height);
-                }
-            }
-        }
-    }
-
-    if (flags & QTextEngine::GlyphIndicesOnly)
-        return true;
-
-    loadAdvancesForGlyphs(ctfont, cgGlyphs, glyphs, len, flags, fontDef);
-    return true;
-}
-
-void QCoreTextFontEngineMulti::loadEngine(int)
-{
-    // Do nothing
-    Q_ASSERT(false);
-}
-
-extern int qt_antialiasing_threshold; // from qapplication.cpp
-
-CGAffineTransform qt_transform_from_fontdef(const QFontDef &fontDef)
-{
-    CGAffineTransform transform = CGAffineTransformIdentity;
-    if (fontDef.stretch != 100)
-        transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
-    return transform;
-}
-
-QCoreTextFontEngine::QCoreTextFontEngine(CTFontRef font, const QFontDef &def)
-{
-    fontDef = def;
-    transform = qt_transform_from_fontdef(fontDef);
-    ctfont = font;
-    CFRetain(ctfont);
-    cgFont = CTFontCopyGraphicsFont(font, NULL);
-    init();
-}
-
-QCoreTextFontEngine::QCoreTextFontEngine(CGFontRef font, const QFontDef &def)
-{
-    fontDef = def;
-    transform = qt_transform_from_fontdef(fontDef);
-    cgFont = font;
-    // Keep reference count balanced
-    CFRetain(cgFont);
-    ctfont = CTFontCreateWithGraphicsFont(font, fontDef.pixelSize, &transform, NULL);
-    init();
-}
-
-QCoreTextFontEngine::~QCoreTextFontEngine()
-{
-    CFRelease(cgFont);
-    CFRelease(ctfont);
-}
-
-extern QFont::Weight weightFromInteger(int weight); // qfontdatabase.cpp
-
-int getTraitValue(CFDictionaryRef allTraits, CFStringRef trait)
-{
-    if (CFDictionaryContainsKey(allTraits, trait)) {
-        CFNumberRef traitNum = (CFNumberRef) CFDictionaryGetValue(allTraits, trait);
-        float v = 0;
-        CFNumberGetValue(traitNum, kCFNumberFloatType, &v);
-        // the value we get from CFNumberRef is from -1.0 to 1.0
-        int value = v * 500 + 500;
-        return value;
-    }
-
-    return 0;
-}
-
-void QCoreTextFontEngine::init()
-{
-    Q_ASSERT(ctfont != NULL);
-    Q_ASSERT(cgFont != NULL);
-
-    QCFString family = CTFontCopyFamilyName(ctfont);
-    fontDef.family = family;
-
-    QCFString styleName = (CFStringRef) CTFontCopyAttribute(ctfont, kCTFontStyleNameAttribute);
-    fontDef.styleName = styleName;
-
-    synthesisFlags = 0;
-    CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(ctfont);
-    if (traits & kCTFontItalicTrait)
-        fontDef.style = QFont::StyleItalic;
-
-    CFDictionaryRef allTraits = CTFontCopyTraits(ctfont);
-    fontDef.weight = weightFromInteger(getTraitValue(allTraits, kCTFontWeightTrait));
-    int slant = getTraitValue(allTraits, kCTFontSlantTrait);
-    if (slant > 500 && !(traits & kCTFontItalicTrait))
-        fontDef.style = QFont::StyleOblique;
-    CFRelease(allTraits);
-
-    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>(reinterpret_cast<const uchar *>(os2Table.constData() + 8));
-        // qAbs is a workaround for weird fonts like Lucida Grande
-        qint16 width = qAbs(qFromBigEndian<qint16>(reinterpret_cast<const uchar *>(os2Table.constData() + 2)));
-        avgCharWidth = QFixed::fromReal(width * fontDef.pixelSize / emSize);
-    } else
-        avgCharWidth = QFontEngine::averageCharWidth();
-}
-
-bool QCoreTextFontEngine::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
-                                       int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
-    *nglyphs = len;
-    QCFType<CFStringRef> cfstring;
-
-    QVarLengthArray<CGGlyph> cgGlyphs(len);
-    CTFontGetGlyphsForCharacters(ctfont, (const UniChar*)str, cgGlyphs.data(), len);
-
-    for (int i = 0; i < len; ++i)
-        if (cgGlyphs[i])
-            glyphs->glyphs[i] = cgGlyphs[i];
-
-    if (flags & QTextEngine::GlyphIndicesOnly)
-        return true;
-
-    loadAdvancesForGlyphs(ctfont, cgGlyphs, glyphs, len, flags, fontDef);
-    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, kCTFontHorizontalOrientation, &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, kCTFontHorizontalOrientation, &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::descent() const
-{
-    QFixed d = QFixed::fromReal(CTFontGetDescent(ctfont));
-    if (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
-        d = d.round();
-
-    // subtract a pixel to even out the historical +1 in QFontMetrics::height().
-    // Fix in Qt 5.
-    return d - 1;
-}
-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
-{
-    return 0;
-}
-
-qreal QCoreTextFontEngine::minLeftBearing() const
-{
-    return 0;
-}
-
-qreal QCoreTextFontEngine::minRightBearing() const
-{
-    return 0;
-}
-
-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<CGSize> advances(glyphs.size());
-    QVarLengthArray<CGGlyph> cgGlyphs(glyphs.size());
-
-    for (int i = 0; i < glyphs.size() - 1; ++i) {
-        advances[i].width = (positions[i + 1].x - positions[i].x).toReal();
-        advances[i].height = (positions[i + 1].y - positions[i].y).toReal();
-        cgGlyphs[i] = glyphs[i];
-    }
-    advances[glyphs.size() - 1].width = 0;
-    advances[glyphs.size() - 1].height = 0;
-    cgGlyphs[glyphs.size() - 1] = glyphs[glyphs.size() - 1];
-
-    CGContextSetFont(ctx, cgFont);
-    //NSLog(@"Font inDraw %@  ctfont %@", CGFontCopyFullName(cgFont), CTFontCopyFamilyName(ctfont));
-
-    CGContextSetTextPosition(ctx, positions[0].x.toReal(), positions[0].y.toReal());
-
-    CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
-
-    if (synthesisFlags & QFontEngine::SynthesizedBold) {
-        CGContextSetTextPosition(ctx, positions[0].x.toReal() + 0.5 * lineThickness().toReal(),
-                                 positions[0].y.toReal());
-
-        CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
-    }
-
-    CGContextSetTextMatrix(ctx, oldTextMatrix);
-}
-
-struct ConvertPathInfo
-{
-    ConvertPathInfo(QPainterPath *newPath, const QPointF &newPos) : path(newPath), pos(newPos) {}
-    QPainterPath *path;
-    QPointF pos;
-};
-
-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->pos.x(),
-                                 element->points[0].y + myInfo->pos.y());
-            break;
-        case kCGPathElementAddLineToPoint:
-            myInfo->path->lineTo(element->points[0].x + myInfo->pos.x(),
-                                 element->points[0].y + myInfo->pos.y());
-            break;
-        case kCGPathElementAddQuadCurveToPoint:
-            myInfo->path->quadTo(element->points[0].x + myInfo->pos.x(),
-                                 element->points[0].y + myInfo->pos.y(),
-                                 element->points[1].x + myInfo->pos.x(),
-                                 element->points[1].y + myInfo->pos.y());
-            break;
-        case kCGPathElementAddCurveToPoint:
-            myInfo->path->cubicTo(element->points[0].x + myInfo->pos.x(),
-                                  element->points[0].y + myInfo->pos.y(),
-                                  element->points[1].x + myInfo->pos.x(),
-                                  element->points[1].y + myInfo->pos.y(),
-                                  element->points[2].x + myInfo->pos.x(),
-                                  element->points[2].y + myInfo->pos.y());
-            break;
-        case kCGPathElementCloseSubpath:
-            myInfo->path->closeSubpath();
-            break;
-        default:
-            qDebug() << "Unhandled path transform type: " << element->type;
-    }
-
-}
-
-void QCoreTextFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nGlyphs,
-                                          QPainterPath *path, QTextItem::RenderFlags)
-{
-    CGAffineTransform cgMatrix = CGAffineTransformIdentity;
-    cgMatrix = CGAffineTransformScale(cgMatrix, 1, -1);
-
-    if (synthesisFlags & QFontEngine::SynthesizedItalic)
-        cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0));
-
-    for (int i = 0; i < nGlyphs; ++i) {
-        QCFType<CGPathRef> cgpath = CTFontCreatePathForGlyph(ctfont, glyphs[i], &cgMatrix);
-        ConvertPathInfo info(path, positions[i].toPointF());
-        CGPathApply(cgpath, &info, convertCGPathToQPainterPath);
-    }
-}
-
-QImage QCoreTextFontEngine::imageForGlyph(glyph_t glyph, QFixed subPixelPosition, int margin, bool aa)
-{
-    Q_UNUSED(margin);
-    const glyph_metrics_t br = boundingBox(glyph);
-    QImage im(qRound(br.width) + 2, qRound(br.height) + 2, QImage::Format_RGB32);
-    im.fill(0);
-
-    CGColorSpaceRef colorspace =
-#ifdef Q_WS_MAC
-            CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
-#else
-            CGColorSpaceCreateDeviceRGB();
-#endif
-    uint cgflags = kCGImageAlphaNoneSkipFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
-    cgflags |= kCGBitmapByteOrder32Host;
-#endif
-    CGContextRef ctx = CGBitmapContextCreate(im.bits(), im.width(), im.height(),
-                                             8, im.bytesPerLine(), colorspace,
-                                             cgflags);
-    CGContextSetFontSize(ctx, fontDef.pixelSize);
-    CGContextSetShouldAntialias(ctx, (aa || fontDef.pointSize > qt_antialiasing_threshold)
-                                 && !(fontDef.styleStrategy & QFont::NoAntialias));
-    CGContextSetShouldSmoothFonts(ctx, aa);
-    CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
-    CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, 1, 0, 0);
-
-    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);
-    CGContextSetRGBFillColor(ctx, 1, 1, 1, 1);
-    CGContextSetTextDrawingMode(ctx, kCGTextFill);
-
-    CGContextSetFont(ctx, cgFont);
-
-    qreal pos_x = -br.x.truncate() + subPixelPosition.toReal();
-    qreal pos_y = im.height() + br.y.toReal();
-    CGContextSetTextPosition(ctx, pos_x, pos_y);
-
-    CGSize advance;
-    advance.width = 0;
-    advance.height = 0;
-    CGGlyph cgGlyph = glyph;
-    CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
-
-    if (synthesisFlags & QFontEngine::SynthesizedBold) {
-        CGContextSetTextPosition(ctx, pos_x + 0.5 * lineThickness().toReal(), pos_y);
-        CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
-    }
-
-    CGContextRelease(ctx);
-
-    return im;
-}
-
-QImage QCoreTextFontEngine::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition)
-{
-    QImage im = imageForGlyph(glyph, subPixelPosition, 0, false);
-
-    QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
-    QVector<QRgb> colors(256);
-    for (int i=0; i<256; ++i)
-        colors[i] = qRgba(0, 0, 0, i);
-    indexed.setColorTable(colors);
-
-    for (int y=0; y<im.height(); ++y) {
-        uint *src = (uint*) im.scanLine(y);
-        uchar *dst = indexed.scanLine(y);
-        for (int x=0; x<im.width(); ++x) {
-            *dst = qGray(*src);
-            ++dst;
-            ++src;
-        }
-    }
-
-    return indexed;
-}
-
-QImage QCoreTextFontEngine::alphaRGBMapForGlyph(glyph_t glyph, QFixed subPixelPosition, int margin, const QTransform &x)
-{
-    if (x.type() >= QTransform::TxScale)
-        return QFontEngine::alphaRGBMapForGlyph(glyph, subPixelPosition, margin, x);
-
-    QImage im = imageForGlyph(glyph, subPixelPosition, margin, true);
-    qGamma_correct_back_to_linear_cs(&im);
-    return im;
-}
-
-void QCoreTextFontEngine::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
-    int i, numGlyphs = glyphs->numGlyphs;
-    QVarLengthArray<CGGlyph> cgGlyphs(numGlyphs);
-
-    for (i = 0; i < numGlyphs; ++i) {
-        if (glyphs->glyphs[i] & 0xff000000)
-            cgGlyphs[i] = 0;
-        else
-            cgGlyphs[i] = glyphs->glyphs[i];
-    }
-
-    loadAdvancesForGlyphs(ctfont, cgGlyphs, glyphs, numGlyphs, flags, fontDef);
-}
-
-QFontEngine::FaceId QCoreTextFontEngine::faceId() const
-{
-    FaceId result;
-    result.index = 0;
-
-    QCFString name = CTFontCopyName(ctfont, kCTFontUniqueNameKey);
-    result.filename = QCFString::toQString(name).toUtf8();
-
-    return result;
-}
-
-bool QCoreTextFontEngine::canRender(const QChar *string, int len)
-{
-    QVarLengthArray<CGGlyph> cgGlyphs(len);
-    return CTFontGetGlyphsForCharacters(ctfont, (const UniChar *) string, cgGlyphs.data(), len);
-}
-
-bool QCoreTextFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
-    QCFType<CFDataRef> table = CTFontCopyTable(ctfont, tag, 0);
-    if (!table || !length)
-        return false;
-    CFIndex tableLength = CFDataGetLength(table);
-    int availableLength = *length;
-    *length = tableLength;
-    if (buffer) {
-        if (tableLength > availableLength)
-            return false;
-        CFDataGetBytes(table, CFRangeMake(0, tableLength), buffer);
-    }
-    return true;
-}
-
-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::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);
-}
-
-QFontEngine::Properties QCoreTextFontEngine::properties() const
-{
-    Properties result;
-
-    QCFString psName, copyright;
-    psName = CTFontCopyPostScriptName(ctfont);
-    copyright = CTFontCopyName(ctfont, kCTFontCopyrightNameKey);
-    result.postscriptName = QCFString::toQString(psName).toUtf8();
-    result.copyright = QCFString::toQString(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;
-}
-
-QT_END_NAMESPACE
-
-#endif// !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-
diff --git a/src/gui/text/qfontengine_mac.mm b/src/gui/text/qfontengine_mac.mm
deleted file mode 100644 (file)
index 0827d7a..0000000
+++ /dev/null
@@ -1,1229 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qfontengine_mac_p.h"
-
-#include <qapplication_p.h>
-#include <qfontengine_p.h>
-#include <qpainter_p.h>
-#include <qtextengine_p.h>
-#include <qbitmap.h>
-#include <qpaintengine_mac_p.h>
-#include <qprintengine_mac_p.h>
-#include <qglobal.h>
-#include <qpixmap.h>
-#include <qpixmapcache.h>
-#include <qvarlengtharray.h>
-#include <qdebug.h>
-#include <qendian.h>
-#include <qmath.h>
-#include <qimage_p.h>
-
-#include <ApplicationServices/ApplicationServices.h>
-#include <AppKit/AppKit.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
-  QFontEngine debug facilities
- *****************************************************************************/
-//#define DEBUG_ADVANCES
-
-extern int qt_antialiasing_threshold; // QApplication.cpp
-
-#ifndef FixedToQFixed
-#define FixedToQFixed(a) QFixed::fromFixed((a) >> 10)
-#define QFixedToFixed(x) ((x).value() << 10)
-#endif
-
-class QMacFontPath
-{
-    float x, y;
-    QPainterPath *path;
-public:
-    inline QMacFontPath(float _x, float _y, QPainterPath *_path) : x(_x), y(_y), path(_path) { }
-    inline void setPosition(float _x, float _y) { x = _x; y = _y; }
-    inline void advance(float _x) { x += _x; }
-    static OSStatus lineTo(const Float32Point *, void *);
-    static OSStatus cubicTo(const Float32Point *, const Float32Point *,
-                            const Float32Point *, void *);
-    static OSStatus moveTo(const Float32Point *, void *);
-    static OSStatus closePath(void *);
-};
-
-OSStatus QMacFontPath::lineTo(const Float32Point *pt, void *data)
-
-{
-    QMacFontPath *p = static_cast<QMacFontPath*>(data);
-    p->path->lineTo(p->x + pt->x, p->y + pt->y);
-    return noErr;
-}
-
-OSStatus QMacFontPath::cubicTo(const Float32Point *cp1, const Float32Point *cp2,
-                               const Float32Point *ep, void *data)
-
-{
-    QMacFontPath *p = static_cast<QMacFontPath*>(data);
-    p->path->cubicTo(p->x + cp1->x, p->y + cp1->y,
-                     p->x + cp2->x, p->y + cp2->y,
-                     p->x + ep->x, p->y + ep->y);
-    return noErr;
-}
-
-OSStatus QMacFontPath::moveTo(const Float32Point *pt, void *data)
-{
-    QMacFontPath *p = static_cast<QMacFontPath*>(data);
-    p->path->moveTo(p->x + pt->x, p->y + pt->y);
-    return noErr;
-}
-
-OSStatus QMacFontPath::closePath(void *data)
-{
-    static_cast<QMacFontPath*>(data)->path->closeSubpath();
-    return noErr;
-}
-
-
-#ifndef QT_MAC_USE_COCOA
-QFontEngineMacMulti::QFontEngineMacMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning)
-    : QFontEngineMulti(0)
-{
-    this->fontDef = fontDef;
-    this->kerning = kerning;
-
-    // hopefully (CTFontCreateWithName or CTFontCreateWithFontDescriptor) + CTFontCreateCopyWithSymbolicTraits
-    // (or CTFontCreateWithQuickdrawInstance)
-    FMFontFamily fmFamily;
-    FMFontStyle fntStyle = 0;
-    fmFamily = FMGetFontFamilyFromATSFontFamilyRef(atsFamily);
-    if (fmFamily == kInvalidFontFamily) {
-        // Use the ATSFont then...
-        fontID = FMGetFontFromATSFontRef(atsFontRef);
-    } else {
-        if (fontDef.weight >= QFont::Bold)
-            fntStyle |= ::bold;
-        if (fontDef.style != QFont::StyleNormal)
-            fntStyle |= ::italic;
-
-        FMFontStyle intrinsicStyle;
-        FMFont fnt = 0;
-        if (FMGetFontFromFontFamilyInstance(fmFamily, fntStyle, &fnt, &intrinsicStyle) == noErr)
-           fontID = FMGetATSFontRefFromFont(fnt);
-    }
-
-    // CFDictionaryRef, <CTStringAttributes.h>
-    OSStatus status;
-
-    status = ATSUCreateTextLayout(&textLayout);
-    Q_ASSERT(status == noErr);
-
-    const int maxAttributeCount = 5;
-    ATSUAttributeTag tags[maxAttributeCount + 1];
-    ByteCount sizes[maxAttributeCount + 1];
-    ATSUAttributeValuePtr values[maxAttributeCount + 1];
-    int attributeCount = 0;
-
-    Fixed size = FixRatio(fontDef.pixelSize, 1);
-    tags[attributeCount] = kATSUSizeTag;
-    sizes[attributeCount] = sizeof(size);
-    values[attributeCount] = &size;
-    ++attributeCount;
-
-    tags[attributeCount] = kATSUFontTag;
-    sizes[attributeCount] = sizeof(fontID);
-    values[attributeCount] = &this->fontID;
-    ++attributeCount;
-
-    transform = CGAffineTransformIdentity;
-    if (fontDef.stretch != 100) {
-        transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
-        tags[attributeCount] = kATSUFontMatrixTag;
-        sizes[attributeCount] = sizeof(transform);
-        values[attributeCount] = &transform;
-        ++attributeCount;
-    }
-
-    status = ATSUCreateStyle(&style);
-    Q_ASSERT(status == noErr);
-
-    Q_ASSERT(attributeCount < maxAttributeCount + 1);
-    status = ATSUSetAttributes(style, attributeCount, tags, sizes, values);
-    Q_ASSERT(status == noErr);
-
-    QFontEngineMac *fe = new QFontEngineMac(style, fontID, fontDef, this);
-    fe->ref.ref();
-    engines.append(fe);
-}
-
-QFontEngineMacMulti::~QFontEngineMacMulti()
-{
-    ATSUDisposeTextLayout(textLayout);
-    ATSUDisposeStyle(style);
-
-    for (int i = 0; i < engines.count(); ++i) {
-        QFontEngineMac *fe = const_cast<QFontEngineMac *>(static_cast<const QFontEngineMac *>(engines.at(i)));
-        fe->multiEngine = 0;
-        if (!fe->ref.deref())
-            delete fe;
-    }
-    engines.clear();
-}
-
-struct QGlyphLayoutInfo
-{
-    QGlyphLayout *glyphs;
-    int *numGlyphs;
-    bool callbackCalled;
-    int *mappedFonts;
-    QTextEngine::ShaperFlags flags;
-    QFontEngineMacMulti::ShaperItem *shaperItem;
-    unsigned int styleStrategy;
-};
-
-static OSStatus atsuPostLayoutCallback(ATSULayoutOperationSelector selector, ATSULineRef lineRef, URefCon refCon,
-                                 void *operationExtraParameter, ATSULayoutOperationCallbackStatus *callbackStatus)
-{
-    Q_UNUSED(selector);
-    Q_UNUSED(operationExtraParameter);
-
-    QGlyphLayoutInfo *nfo = reinterpret_cast<QGlyphLayoutInfo *>(refCon);
-    nfo->callbackCalled = true;
-
-    ATSLayoutRecord *layoutData = 0;
-    ItemCount itemCount = 0;
-
-    OSStatus e = noErr;
-    e = ATSUDirectGetLayoutDataArrayPtrFromLineRef(lineRef, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
-                                                   /*iCreate =*/ false,
-                                                   (void **) &layoutData,
-                                                   &itemCount);
-    if (e != noErr)
-        return e;
-
-    *nfo->numGlyphs = itemCount - 1;
-
-    Fixed *baselineDeltas = 0;
-
-    e = ATSUDirectGetLayoutDataArrayPtrFromLineRef(lineRef, kATSUDirectDataBaselineDeltaFixedArray,
-                                                   /*iCreate =*/ true,
-                                                   (void **) &baselineDeltas,
-                                                   &itemCount);
-    if (e != noErr)
-        return e;
-
-    int nextCharStop = -1;
-    int currentClusterGlyph = -1; // first glyph in log cluster
-    QFontEngineMacMulti::ShaperItem *item = nfo->shaperItem;
-    if (item->charAttributes) {
-        item = nfo->shaperItem;
-#if !defined(QT_NO_DEBUG)
-        int surrogates = 0;
-        const QChar *str = item->string;
-        for (int i = item->from; i < item->from + item->length - 1; ++i)
-            surrogates += (str[i].isHighSurrogate() && str[i+1].isLowSurrogate());
-#endif
-        for (nextCharStop = item->from; nextCharStop < item->from + item->length; ++nextCharStop)
-            if (item->charAttributes[nextCharStop].charStop)
-                break;
-        nextCharStop -= item->from;
-    }
-
-    nfo->glyphs->attributes[0].clusterStart = true;
-    int glyphIdx = 0;
-    int glyphIncrement = 1;
-    if (nfo->flags & QTextEngine::RightToLeft) {
-        glyphIdx  = itemCount - 2;
-        glyphIncrement = -1;
-    }
-    for (int i = 0; i < *nfo->numGlyphs; ++i, glyphIdx += glyphIncrement) {
-
-        int charOffset = layoutData[glyphIdx].originalOffset / sizeof(UniChar);
-        const int fontIdx = nfo->mappedFonts[charOffset];
-
-        ATSGlyphRef glyphId = layoutData[glyphIdx].glyphID;
-
-        QFixed yAdvance = FixedToQFixed(baselineDeltas[glyphIdx]);
-        QFixed xAdvance = FixedToQFixed(layoutData[glyphIdx + 1].realPos - layoutData[glyphIdx].realPos);
-
-        if (nfo->styleStrategy & QFont::ForceIntegerMetrics) {
-            yAdvance = yAdvance.round();
-            xAdvance = xAdvance.round();
-        }
-
-        if (glyphId != 0xffff || i == 0) {
-            if (i < nfo->glyphs->numGlyphs)
-            {
-                nfo->glyphs->glyphs[i] = (glyphId & 0x00ffffff) | (fontIdx << 24);
-
-                nfo->glyphs->advances_y[i] = yAdvance;
-                nfo->glyphs->advances_x[i] = xAdvance;
-            }
-        } else {
-            // ATSUI gives us 0xffff as glyph id at the index in the glyph array for
-            // a character position that maps to a ligtature. Such a glyph id does not
-            // result in any visual glyph, but it may have an advance, which is why we
-            // sum up the glyph advances.
-            --i;
-            nfo->glyphs->advances_y[i] += yAdvance;
-            nfo->glyphs->advances_x[i] += xAdvance;
-            *nfo->numGlyphs -= 1;
-        }
-
-        if (item->log_clusters) {
-            if (charOffset >= nextCharStop) {
-                nfo->glyphs->attributes[i].clusterStart = true;
-                currentClusterGlyph = i;
-
-                ++nextCharStop;
-                for (; nextCharStop < item->length; ++nextCharStop)
-                    if (item->charAttributes[item->from + nextCharStop].charStop)
-                        break;
-            } else {
-                if (currentClusterGlyph == -1)
-                    currentClusterGlyph = i;
-            }
-            item->log_clusters[charOffset] = currentClusterGlyph;
-
-            // surrogate handling
-            if (charOffset < item->length - 1) {
-                QChar current = item->string[item->from + charOffset];
-                QChar next = item->string[item->from + charOffset + 1];
-                if (current.isHighSurrogate() && next.isLowSurrogate())
-                    item->log_clusters[charOffset + 1] = currentClusterGlyph;
-            }
-        }
-    }
-
-    /*
-    if (item) {
-        qDebug() << "resulting logclusters:";
-        for (int i = 0; i < item->length; ++i)
-            qDebug() << "logClusters[" << i << "] =" << item->log_clusters[i];
-        qDebug() << "clusterstarts:";
-        for (int i = 0; i < *nfo->numGlyphs; ++i)
-            qDebug() << "clusterStart[" << i << "] =" << nfo->glyphs[i].attributes.clusterStart;
-    }
-    */
-
-    ATSUDirectReleaseLayoutDataArrayPtr(lineRef, kATSUDirectDataBaselineDeltaFixedArray,
-                                        (void **) &baselineDeltas);
-
-    ATSUDirectReleaseLayoutDataArrayPtr(lineRef, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
-                                        (void **) &layoutData);
-
-    *callbackStatus = kATSULayoutOperationCallbackStatusHandled;
-    return noErr;
-}
-
-int QFontEngineMacMulti::fontIndexForFontID(ATSUFontID id) const
-{
-    for (int i = 0; i < engines.count(); ++i) {
-        if (engineAt(i)->fontID == id)
-            return i;
-    }
-
-    QFontEngineMacMulti *that = const_cast<QFontEngineMacMulti *>(this);
-    QFontEngineMac *fe = new QFontEngineMac(style, id, fontDef, that);
-    fe->ref.ref();
-    that->engines.append(fe);
-    return engines.count() - 1;
-}
-
-bool QFontEngineMacMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
-    return stringToCMap(str, len, glyphs, nglyphs, flags, /*logClusters=*/0, /*charAttributes=*/0, /*si=*/0);
-}
-
-bool QFontEngineMacMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags,
-                                       unsigned short *logClusters, const HB_CharAttributes *charAttributes, QScriptItem *) const
-{
-    if (*nglyphs < len) {
-        *nglyphs = len;
-        return false;
-    }
-
-    ShaperItem shaperItem;
-    shaperItem.string = str;
-    shaperItem.from = 0;
-    shaperItem.length = len;
-    shaperItem.glyphs = *glyphs;
-    shaperItem.glyphs.numGlyphs = *nglyphs;
-    shaperItem.flags = flags;
-    shaperItem.log_clusters = logClusters;
-    shaperItem.charAttributes = charAttributes;
-
-    const int maxChars = qMax(1,
-                              int(SHRT_MAX / maxCharWidth())
-                              - 10 // subtract a few to be on the safe side
-                             );
-    if (len < maxChars || !charAttributes)
-        return stringToCMapInternal(str, len, glyphs, nglyphs, flags, &shaperItem);
-
-    int charIdx = 0;
-    int glyphIdx = 0;
-    ShaperItem tmpItem = shaperItem;
-
-    do {
-        tmpItem.from = shaperItem.from + charIdx;
-
-        int charCount = qMin(maxChars, len - charIdx);
-
-        int lastWhitespace = tmpItem.from + charCount - 1;
-        int lastSoftBreak = lastWhitespace;
-        int lastCharStop = lastSoftBreak;
-        for (int i = lastCharStop; i >= tmpItem.from; --i) {
-            if (tmpItem.charAttributes[i].whiteSpace) {
-                lastWhitespace = i;
-                break;
-            } if (tmpItem.charAttributes[i].lineBreakType != HB_NoBreak) {
-                lastSoftBreak = i;
-            } if (tmpItem.charAttributes[i].charStop) {
-                lastCharStop = i;
-            }
-        }
-        charCount = qMin(lastWhitespace, qMin(lastSoftBreak, lastCharStop)) - tmpItem.from + 1;
-
-        int glyphCount = shaperItem.glyphs.numGlyphs - glyphIdx;
-        if (glyphCount <= 0)
-            return false;
-        tmpItem.length = charCount;
-        tmpItem.glyphs = shaperItem.glyphs.mid(glyphIdx, glyphCount);
-        tmpItem.log_clusters = shaperItem.log_clusters + charIdx;
-        if (!stringToCMapInternal(tmpItem.string + tmpItem.from, tmpItem.length,
-                                  &tmpItem.glyphs, &glyphCount, flags,
-                                  &tmpItem)) {
-            *nglyphs = glyphIdx + glyphCount;
-            return false;
-       }
-        for (int i = 0; i < charCount; ++i)
-            tmpItem.log_clusters[i] += glyphIdx;
-        glyphIdx += glyphCount;
-        charIdx += charCount;
-    } while (charIdx < len);
-    *nglyphs = glyphIdx;
-    glyphs->numGlyphs = glyphIdx;
-
-    return true;
-}
-
-bool QFontEngineMacMulti::stringToCMapInternal(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags,ShaperItem *shaperItem) const
-{
-    //qDebug() << "stringToCMap" << QString(str, len);
-
-    OSStatus e = noErr;
-
-    e = ATSUSetTextPointerLocation(textLayout, (UniChar *)(str), 0, len, len);
-    if (e != noErr) {
-        qWarning("Qt: internal: %ld: Error ATSUSetTextPointerLocation %s: %d", long(e), __FILE__, __LINE__);
-        return false;
-    }
-
-    QGlyphLayoutInfo nfo;
-    nfo.glyphs = glyphs;
-    nfo.numGlyphs = nglyphs;
-    nfo.callbackCalled = false;
-    nfo.flags = flags;
-    nfo.shaperItem = shaperItem;
-    nfo.styleStrategy = fontDef.styleStrategy;
-
-    int prevNumGlyphs = *nglyphs;
-
-    QVarLengthArray<int> mappedFonts(len);
-    for (int i = 0; i < len; ++i)
-        mappedFonts[i] = 0;
-    nfo.mappedFonts = mappedFonts.data();
-
-    Q_ASSERT(sizeof(void *) <= sizeof(URefCon));
-    e = ATSUSetTextLayoutRefCon(textLayout, (URefCon)&nfo);
-    if (e != noErr) {
-        qWarning("Qt: internal: %ld: Error ATSUSetTextLayoutRefCon %s: %d", long(e), __FILE__, __LINE__);
-        return false;
-    }
-
-    {
-        const int maxAttributeCount = 3;
-        ATSUAttributeTag tags[maxAttributeCount + 1];
-        ByteCount sizes[maxAttributeCount + 1];
-        ATSUAttributeValuePtr values[maxAttributeCount + 1];
-        int attributeCount = 0;
-
-        tags[attributeCount] = kATSULineLayoutOptionsTag;
-        ATSLineLayoutOptions layopts = kATSLineHasNoOpticalAlignment
-                                       | kATSLineIgnoreFontLeading
-                                       | kATSLineNoSpecialJustification // we do kashidas ourselves
-                                       | kATSLineDisableAllJustification
-                                       ;
-
-        if (fontDef.styleStrategy & QFont::NoAntialias)
-            layopts |= kATSLineNoAntiAliasing;
-
-        if (!kerning)
-            layopts |= kATSLineDisableAllKerningAdjustments;
-
-        values[attributeCount] = &layopts;
-        sizes[attributeCount] = sizeof(layopts);
-        ++attributeCount;
-
-        tags[attributeCount] = kATSULayoutOperationOverrideTag;
-        ATSULayoutOperationOverrideSpecifier spec;
-        spec.operationSelector = kATSULayoutOperationPostLayoutAdjustment;
-        spec.overrideUPP = atsuPostLayoutCallback;
-        values[attributeCount] = &spec;
-        sizes[attributeCount] = sizeof(spec);
-        ++attributeCount;
-
-        // CTWritingDirection
-        Boolean direction;
-        if (flags & QTextEngine::RightToLeft)
-            direction = kATSURightToLeftBaseDirection;
-        else
-            direction = kATSULeftToRightBaseDirection;
-        tags[attributeCount] = kATSULineDirectionTag;
-        values[attributeCount] = &direction;
-        sizes[attributeCount] = sizeof(direction);
-        ++attributeCount;
-
-        Q_ASSERT(attributeCount < maxAttributeCount + 1);
-        e = ATSUSetLayoutControls(textLayout, attributeCount, tags, sizes, values);
-        if (e != noErr) {
-            qWarning("Qt: internal: %ld: Error ATSUSetLayoutControls %s: %d", long(e), __FILE__, __LINE__);
-            return false;
-        }
-
-    }
-
-    e = ATSUSetRunStyle(textLayout, style, 0, len);
-    if (e != noErr) {
-        qWarning("Qt: internal: %ld: Error ATSUSetRunStyle %s: %d", long(e), __FILE__, __LINE__);
-        return false;
-    }
-
-    if (!(fontDef.styleStrategy & QFont::NoFontMerging)) {
-        int pos = 0;
-        do {
-            ATSUFontID substFont = 0;
-            UniCharArrayOffset changedOffset = 0;
-            UniCharCount changeCount = 0;
-
-            e = ATSUMatchFontsToText(textLayout, pos, len - pos,
-                                     &substFont, &changedOffset,
-                                     &changeCount);
-            if (e == kATSUFontsMatched) {
-                int fontIdx = fontIndexForFontID(substFont);
-                for (uint i = 0; i < changeCount; ++i)
-                    mappedFonts[changedOffset + i] = fontIdx;
-                pos = changedOffset + changeCount;
-                ATSUSetRunStyle(textLayout, engineAt(fontIdx)->style, changedOffset, changeCount);
-            } else if (e == kATSUFontsNotMatched) {
-                pos = changedOffset + changeCount;
-            }
-        } while (pos < len && e != noErr);
-    }
-    {    // trigger the a layout
-        // CFAttributedStringCreate, CTFramesetterCreateWithAttributedString (or perhaps Typesetter)
-        Rect rect;
-        e = ATSUMeasureTextImage(textLayout, kATSUFromTextBeginning, kATSUToTextEnd,
-                                 /*iLocationX =*/ 0, /*iLocationY =*/ 0,
-                                 &rect);
-        if (e != noErr) {
-            qWarning("Qt: internal: %ld: Error ATSUMeasureTextImage %s: %d", long(e), __FILE__, __LINE__);
-            return false;
-        }
-    }
-
-    if (!nfo.callbackCalled) {
-            qWarning("Qt: internal: %ld: Error ATSUMeasureTextImage did not trigger callback %s: %d", long(e), __FILE__, __LINE__);
-            return false;
-    }
-
-    ATSUClearLayoutCache(textLayout, kATSUFromTextBeginning);
-    if (prevNumGlyphs < *nfo.numGlyphs)
-        return false;
-    return true;
-}
-
-void QFontEngineMacMulti::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
-    Q_ASSERT(false);
-    Q_UNUSED(glyphs);
-    Q_UNUSED(flags);
-}
-
-void QFontEngineMacMulti::doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const
-{
-    //Q_ASSERT(false);
-}
-
-void QFontEngineMacMulti::loadEngine(int /*at*/)
-{
-    // should never be called!
-    Q_ASSERT(false);
-}
-
-bool QFontEngineMacMulti::canRender(const QChar *string, int len)
-{
-    ATSUSetTextPointerLocation(textLayout, reinterpret_cast<const UniChar *>(string), 0, len, len);
-    ATSUSetRunStyle(textLayout, style, 0, len);
-
-    OSStatus e = noErr;
-    int pos = 0;
-    do {
-        FMFont substFont = 0;
-        UniCharArrayOffset changedOffset = 0;
-        UniCharCount changeCount = 0;
-
-        // CTFontCreateForString
-        e = ATSUMatchFontsToText(textLayout, pos, len - pos,
-                                 &substFont, &changedOffset,
-                                 &changeCount);
-        if (e == kATSUFontsMatched) {
-            pos = changedOffset + changeCount;
-        } else if (e == kATSUFontsNotMatched) {
-            break;
-        }
-    } while (pos < len && e != noErr);
-
-    return e == noErr || e == kATSUFontsMatched;
-}
-
-QFontEngineMac::QFontEngineMac(ATSUStyle baseStyle, ATSUFontID fontID, const QFontDef &def, QFontEngineMacMulti *multiEngine)
-    : fontID(fontID), multiEngine(multiEngine), cmap(0), symbolCMap(false)
-{
-    fontDef = def;
-    ATSUCreateAndCopyStyle(baseStyle, &style);
-    ATSFontRef atsFont = FMGetATSFontRefFromFont(fontID);
-    cgFont = CGFontCreateWithPlatformFont(&atsFont);
-
-    const int maxAttributeCount = 4;
-    ATSUAttributeTag tags[maxAttributeCount + 1];
-    ByteCount sizes[maxAttributeCount + 1];
-    ATSUAttributeValuePtr values[maxAttributeCount + 1];
-    int attributeCount = 0;
-
-    synthesisFlags = 0;
-
-    // synthesizing using CG is not recommended
-    quint16 macStyle = 0;
-    {
-        uchar data[4];
-        ByteCount len = 4;
-        if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 44, 4, &data, &len) == noErr)
-            macStyle = qFromBigEndian<quint16>(data);
-    }
-
-    Boolean atsuBold = false;
-    Boolean atsuItalic = false;
-    if (fontDef.weight >= QFont::Bold) {
-        if (!(macStyle & 1)) {
-            synthesisFlags |= SynthesizedBold;
-            atsuBold = true;
-            tags[attributeCount] = kATSUQDBoldfaceTag;
-            sizes[attributeCount] = sizeof(atsuBold);
-            values[attributeCount] = &atsuBold;
-            ++attributeCount;
-        }
-    }
-    if (fontDef.style != QFont::StyleNormal) {
-        if (!(macStyle & 2)) {
-            synthesisFlags |= SynthesizedItalic;
-            atsuItalic = true;
-            tags[attributeCount] = kATSUQDItalicTag;
-            sizes[attributeCount] = sizeof(atsuItalic);
-            values[attributeCount] = &atsuItalic;
-            ++attributeCount;
-        }
-    }
-
-    tags[attributeCount] = kATSUFontTag;
-    values[attributeCount] = &fontID;
-    sizes[attributeCount] = sizeof(fontID);
-    ++attributeCount;
-
-    Q_ASSERT(attributeCount < maxAttributeCount + 1);
-    OSStatus err = ATSUSetAttributes(style, attributeCount, tags, sizes, values);
-    Q_ASSERT(err == noErr);
-    Q_UNUSED(err);
-
-    // CTFontCopyTable
-    quint16 tmpFsType;
-    if (ATSFontGetTable(atsFont, MAKE_TAG('O', 'S', '/', '2'), 8, 2, &tmpFsType, 0) == noErr)
-       fsType = qFromBigEndian<quint16>(tmpFsType);
-    else
-        fsType = 0;
-
-    if (multiEngine)
-       transform = multiEngine->transform;
-    else
-       transform = CGAffineTransformIdentity;
-
-    ATSUTextMeasurement metric;
-
-    ATSUGetAttribute(style, kATSUAscentTag, sizeof(metric), &metric, 0);
-    m_ascent = FixRound(metric);
-
-    ATSUGetAttribute(style, kATSUDescentTag, sizeof(metric), &metric, 0);
-    m_descent = FixRound(metric);
-
-    ATSUGetAttribute(style, kATSULeadingTag, sizeof(metric), &metric, 0);
-    m_leading = FixRound(metric);
-
-    ATSFontMetrics metrics;
-
-    ATSFontGetHorizontalMetrics(FMGetATSFontRefFromFont(fontID), kATSOptionFlagsDefault, &metrics);
-    m_maxCharWidth = metrics.maxAdvanceWidth * fontDef.pointSize;
-
-    ATSFontGetHorizontalMetrics(FMGetATSFontRefFromFont(fontID), kATSOptionFlagsDefault, &metrics);
-    m_xHeight = QFixed::fromReal(metrics.xHeight * fontDef.pointSize);
-
-    ATSFontGetHorizontalMetrics(FMGetATSFontRefFromFont(fontID), kATSOptionFlagsDefault, &metrics);
-    m_averageCharWidth = QFixed::fromReal(metrics.avgAdvanceWidth * fontDef.pointSize);
-
-    // Use width of 'X' if ATSFontGetHorizontalMetrics returns 0 for avgAdvanceWidth.
-    if (m_averageCharWidth == QFixed(0)) {
-        QChar c('X');
-        QGlyphLayoutArray<1> glyphs;
-        int nglyphs = 1;
-        stringToCMap(&c, 1, &glyphs, &nglyphs, 0);
-        glyph_metrics_t metrics = boundingBox(glyphs);
-        m_averageCharWidth =  metrics.width;
-    }
-}
-
-QFontEngineMac::~QFontEngineMac()
-{
-    ATSUDisposeStyle(style);
-}
-
-static inline unsigned int getChar(const QChar *str, int &i, const int len)
-{
-    uint ucs4 = str[i].unicode();
-    if (str[i].isHighSurrogate() && i < len-1 && str[i+1].isLowSurrogate()) {
-        ++i;
-        ucs4 = QChar::surrogateToUcs4(ucs4, str[i].unicode());
-    }
-    return ucs4;
-}
-
-// Not used directly for shaping, only used to calculate m_averageCharWidth
-bool QFontEngineMac::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
-    if (!cmap) {
-        cmapTable = getSfntTable(MAKE_TAG('c', 'm', 'a', 'p'));
-        int size = 0;
-        cmap = getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()), cmapTable.size(), &symbolCMap, &size);
-        if (!cmap)
-            return false;
-    }
-    if (symbolCMap) {
-        for (int i = 0; i < len; ++i) {
-            unsigned int uc = getChar(str, i, len);
-            glyphs->glyphs[i] = getTrueTypeGlyphIndex(cmap, uc);
-            if(!glyphs->glyphs[i] && uc < 0x100)
-                glyphs->glyphs[i] = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
-        }
-    } else {
-        for (int i = 0; i < len; ++i) {
-            unsigned int uc = getChar(str, i, len);
-            glyphs->glyphs[i] = getTrueTypeGlyphIndex(cmap, uc);
-        }
-    }
-
-    *nglyphs = len;
-    glyphs->numGlyphs = *nglyphs;
-
-    if (!(flags & QTextEngine::GlyphIndicesOnly))
-        recalcAdvances(glyphs, flags);
-
-    return true;
-}
-
-void QFontEngineMac::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
-    Q_UNUSED(flags)
-
-    QVarLengthArray<GlyphID> atsuGlyphs(glyphs->numGlyphs);
-    for (int i = 0; i < glyphs->numGlyphs; ++i)
-        atsuGlyphs[i] = glyphs->glyphs[i];
-
-    QVarLengthArray<ATSGlyphScreenMetrics> metrics(glyphs->numGlyphs);
-
-    ATSUGlyphGetScreenMetrics(style, glyphs->numGlyphs, atsuGlyphs.data(), sizeof(GlyphID),
-                              /* iForcingAntiAlias =*/ false,
-                              /* iAntiAliasSwitch =*/true,
-                              metrics.data());
-
-    for (int i = 0; i < glyphs->numGlyphs; ++i) {
-        glyphs->advances_x[i] = QFixed::fromReal(metrics[i].deviceAdvance.x);
-        glyphs->advances_y[i] = QFixed::fromReal(metrics[i].deviceAdvance.y);
-
-        if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
-            glyphs->advances_x[i] = glyphs->advances_x[i].round();
-            glyphs->advances_y[i] = glyphs->advances_y[i].round();
-        }
-    }
-}
-
-glyph_metrics_t QFontEngineMac::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 QFontEngineMac::boundingBox(glyph_t glyph)
-{
-    GlyphID atsuGlyph = glyph;
-
-    ATSGlyphScreenMetrics metrics;
-
-    ATSUGlyphGetScreenMetrics(style, 1, &atsuGlyph, 0,
-                              /* iForcingAntiAlias =*/ false,
-                              /* iAntiAliasSwitch =*/true,
-                              &metrics);
-
-    // ### check again
-
-    glyph_metrics_t gm;
-    gm.width = int(metrics.width);
-    gm.height = int(metrics.height);
-    gm.x = QFixed::fromReal(metrics.topLeft.x);
-    gm.y = -QFixed::fromReal(metrics.topLeft.y);
-    gm.xoff = QFixed::fromReal(metrics.deviceAdvance.x);
-    gm.yoff = QFixed::fromReal(metrics.deviceAdvance.y);
-
-    if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
-        gm.x = gm.x.floor();
-        gm.y = gm.y.floor();
-        gm.xoff = gm.xoff.round();
-        gm.yoff = gm.yoff.round();
-    }
-
-    return gm;
-}
-
-QFixed QFontEngineMac::ascent() const
-{
-    return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
-            ? m_ascent.round()
-            : m_ascent;
-}
-
-QFixed QFontEngineMac::descent() const
-{
-    // subtract a pixel to even out the historical +1 in QFontMetrics::height().
-    // Fix in Qt 5.
-    return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
-            ? m_descent.round() - 1
-            : m_descent;
-}
-
-QFixed QFontEngineMac::leading() const
-{
-    return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
-            ? m_leading.round()
-            : m_leading;
-}
-
-qreal QFontEngineMac::maxCharWidth() const
-{
-    return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
-            ? qRound(m_maxCharWidth)
-            : m_maxCharWidth;
-}
-
-QFixed QFontEngineMac::xHeight() const
-{
-    return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
-            ? m_xHeight.round()
-            : m_xHeight;
-}
-
-QFixed QFontEngineMac::averageCharWidth() const
-{
-    return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
-            ? m_averageCharWidth.round()
-            : m_averageCharWidth;
-}
-
-static void addGlyphsToPathHelper(ATSUStyle style, glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, QPainterPath *path)
-{
-    if (!numGlyphs)
-        return;
-
-    OSStatus e;
-
-    QMacFontPath fontpath(0, 0, path);
-    ATSCubicMoveToUPP moveTo = NewATSCubicMoveToUPP(QMacFontPath::moveTo);
-    ATSCubicLineToUPP lineTo = NewATSCubicLineToUPP(QMacFontPath::lineTo);
-    ATSCubicCurveToUPP cubicTo = NewATSCubicCurveToUPP(QMacFontPath::cubicTo);
-    ATSCubicClosePathUPP closePath = NewATSCubicClosePathUPP(QMacFontPath::closePath);
-
-    // CTFontCreatePathForGlyph
-    for (int i = 0; i < numGlyphs; ++i) {
-        GlyphID glyph = glyphs[i];
-
-        fontpath.setPosition(positions[i].x.toReal(), positions[i].y.toReal());
-        ATSUGlyphGetCubicPaths(style, glyph, moveTo, lineTo,
-                               cubicTo, closePath, &fontpath, &e);
-    }
-
-    DisposeATSCubicMoveToUPP(moveTo);
-    DisposeATSCubicLineToUPP(lineTo);
-    DisposeATSCubicCurveToUPP(cubicTo);
-    DisposeATSCubicClosePathUPP(closePath);
-}
-
-void QFontEngineMac::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, QPainterPath *path,
-                                           QTextItem::RenderFlags)
-{
-    addGlyphsToPathHelper(style, glyphs, positions, numGlyphs, path);
-}
-
-
-/*!
-  Helper function for alphaMapForGlyph and alphaRGBMapForGlyph. The two are identical, except for
-  the subpixel antialiasing...
-*/
-QImage QFontEngineMac::imageForGlyph(glyph_t glyph, int margin, bool colorful)
-{
-    const glyph_metrics_t br = boundingBox(glyph);
-    QImage im(qRound(br.width)+2, qRound(br.height)+4, QImage::Format_RGB32);
-    im.fill(0xff000000);
-
-    CGColorSpaceRef colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
-    uint cgflags = kCGImageAlphaNoneSkipFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
-    cgflags |= kCGBitmapByteOrder32Host;
-#endif
-    CGContextRef ctx = CGBitmapContextCreate(im.bits(), im.width(), im.height(),
-                                             8, im.bytesPerLine(), colorspace,
-                                             cgflags);
-    CGContextSetFontSize(ctx, fontDef.pixelSize);
-    CGContextSetShouldAntialias(ctx, fontDef.pointSize > qt_antialiasing_threshold && !(fontDef.styleStrategy & QFont::NoAntialias));
-    // turn off sub-pixel hinting - no support for that in OpenGL
-    CGContextSetShouldSmoothFonts(ctx, colorful);
-    CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
-    CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, 1, 0, 0);
-    CGAffineTransformConcat(cgMatrix, oldTextMatrix);
-
-    if (synthesisFlags & QFontEngine::SynthesizedItalic)
-        cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, tanf(14 * acosf(0) / 90), 1, 0, 0));
-
-    cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
-
-    CGContextSetTextMatrix(ctx, cgMatrix);
-    CGContextSetRGBFillColor(ctx, 1, 1, 1, 1);
-    CGContextSetTextDrawingMode(ctx, kCGTextFill);
-    CGContextSetFont(ctx, cgFont);
-
-    qreal pos_x = -br.x.toReal() + 1;
-    qreal pos_y = im.height() + br.y.toReal() - 2;
-    CGContextSetTextPosition(ctx, pos_x, pos_y);
-
-    CGSize advance;
-    advance.width = 0;
-    advance.height = 0;
-    CGGlyph cgGlyph = glyph;
-    CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
-
-    if (synthesisFlags & QFontEngine::SynthesizedBold) {
-        CGContextSetTextPosition(ctx, pos_x + 0.5 * lineThickness().toReal(), pos_y);
-        CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
-    }
-
-    CGContextRelease(ctx);
-
-    return im;
-}
-
-QImage QFontEngineMac::alphaMapForGlyph(glyph_t glyph)
-{
-    QImage im = imageForGlyph(glyph, 2, false);
-
-    QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
-    QVector<QRgb> colors(256);
-    for (int i=0; i<256; ++i)
-        colors[i] = qRgba(0, 0, 0, i);
-    indexed.setColorTable(colors);
-
-    for (int y=0; y<im.height(); ++y) {
-        uint *src = (uint*) im.scanLine(y);
-        uchar *dst = indexed.scanLine(y);
-        for (int x=0; x<im.width(); ++x) {
-            *dst = qGray(*src);
-            ++dst;
-            ++src;
-        }
-    }
-
-    return indexed;
-}
-
-QImage QFontEngineMac::alphaRGBMapForGlyph(glyph_t glyph, QFixed, int margin, const QTransform &t)
-{
-    QImage im = imageForGlyph(glyph, margin, true);
-
-    if (t.type() >= QTransform::TxScale) {
-        im = im.transformed(t);
-    }
-
-    qGamma_correct_back_to_linear_cs(&im);
-
-    return im;
-}
-
-
-bool QFontEngineMac::canRender(const QChar *string, int len)
-{
-    Q_ASSERT(false);
-    Q_UNUSED(string);
-    Q_UNUSED(len);
-    return false;
-}
-
-void QFontEngineMac::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, -tanf(14 * acosf(0) / 90), 1, 0, 0));
-
-    cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
-
-    CGContextSetTextMatrix(ctx, cgMatrix);
-
-    CGContextSetTextDrawingMode(ctx, kCGTextFill);
-
-
-    QVarLengthArray<CGSize> advances(glyphs.size());
-    QVarLengthArray<CGGlyph> cgGlyphs(glyphs.size());
-
-    for (int i = 0; i < glyphs.size() - 1; ++i) {
-        advances[i].width = (positions[i + 1].x - positions[i].x).toReal();
-        advances[i].height = (positions[i + 1].y - positions[i].y).toReal();
-        cgGlyphs[i] = glyphs[i];
-    }
-    advances[glyphs.size() - 1].width = 0;
-    advances[glyphs.size() - 1].height = 0;
-    cgGlyphs[glyphs.size() - 1] = glyphs[glyphs.size() - 1];
-
-    CGContextSetFont(ctx, cgFont);
-
-    CGContextSetTextPosition(ctx, positions[0].x.toReal(), positions[0].y.toReal());
-
-    CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
-
-    if (synthesisFlags & QFontEngine::SynthesizedBold) {
-        CGContextSetTextPosition(ctx, positions[0].x.toReal() + 0.5 * lineThickness().toReal(),
-                                      positions[0].y.toReal());
-
-        CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
-    }
-
-    CGContextSetTextMatrix(ctx, oldTextMatrix);
-}
-
-QFontEngine::FaceId QFontEngineMac::faceId() const
-{
-    FaceId ret;
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-    // CTFontGetPlatformFont
-    FSRef ref;
-    if (ATSFontGetFileReference(FMGetATSFontRefFromFont(fontID), &ref) != noErr)
-        return ret;
-    ret.filename = QByteArray(128, 0);
-    ret.index = fontID;
-    FSRefMakePath(&ref, (UInt8 *)ret.filename.data(), ret.filename.size());
-}else
-#endif
-{
-    FSSpec spec;
-    if (ATSFontGetFileSpecification(FMGetATSFontRefFromFont(fontID), &spec) != noErr)
-        return ret;
-
-    FSRef ref;
-    FSpMakeFSRef(&spec, &ref);
-    ret.filename = QByteArray(128, 0);
-    ret.index = fontID;
-    FSRefMakePath(&ref, (UInt8 *)ret.filename.data(), ret.filename.size());
-}
-    return ret;
-}
-
-QByteArray QFontEngineMac::getSfntTable(uint tag) const
-{
-    ATSFontRef atsFont = FMGetATSFontRefFromFont(fontID);
-
-    ByteCount length;
-    OSStatus status = ATSFontGetTable(atsFont, tag, 0, 0, 0, &length);
-    if (status != noErr)
-        return QByteArray();
-    QByteArray table(length, 0);
-    // CTFontCopyTable
-    status = ATSFontGetTable(atsFont, tag, 0, table.length(), table.data(), &length);
-    if (status != noErr)
-        return QByteArray();
-    return table;
-}
-
-QFontEngine::Properties QFontEngineMac::properties() const
-{
-    QFontEngine::Properties props;
-    ATSFontRef atsFont = FMGetATSFontRefFromFont(fontID);
-    quint16 tmp;
-    // CTFontGetUnitsPerEm
-    if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 18, 2, &tmp, 0) == noErr)
-       props.emSquare = qFromBigEndian<quint16>(tmp);
-    struct {
-        qint16 xMin;
-        qint16 yMin;
-        qint16 xMax;
-        qint16 yMax;
-    } bbox;
-    bbox.xMin = bbox.xMax = bbox.yMin = bbox.yMax = 0;
-    // CTFontGetBoundingBox
-    if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'e', 'a', 'd'), 36, 8, &bbox, 0) == noErr) {
-        bbox.xMin = qFromBigEndian<quint16>(bbox.xMin);
-        bbox.yMin = qFromBigEndian<quint16>(bbox.yMin);
-        bbox.xMax = qFromBigEndian<quint16>(bbox.xMax);
-        bbox.yMax = qFromBigEndian<quint16>(bbox.yMax);
-    }
-    struct {
-        qint16 ascender;
-        qint16 descender;
-        qint16 linegap;
-    } metrics;
-    metrics.ascender = metrics.descender = metrics.linegap = 0;
-    // CTFontGetAscent, etc.
-    if (ATSFontGetTable(atsFont, MAKE_TAG('h', 'h', 'e', 'a'), 4, 6, &metrics, 0) == noErr) {
-        metrics.ascender = qFromBigEndian<quint16>(metrics.ascender);
-        metrics.descender = qFromBigEndian<quint16>(metrics.descender);
-        metrics.linegap = qFromBigEndian<quint16>(metrics.linegap);
-    }
-    props.ascent = metrics.ascender;
-    props.descent = -metrics.descender;
-    props.leading = metrics.linegap;
-    props.boundingBox = QRectF(bbox.xMin, -bbox.yMax,
-                           bbox.xMax - bbox.xMin,
-                           bbox.yMax - bbox.yMin);
-    props.italicAngle = 0;
-    props.capHeight = props.ascent;
-
-    qint16 lw = 0;
-    // fonts lie
-    if (ATSFontGetTable(atsFont, MAKE_TAG('p', 'o', 's', 't'), 10, 2, &lw, 0) == noErr)
-       lw = qFromBigEndian<quint16>(lw);
-    props.lineWidth = lw;
-
-    // CTFontCopyPostScriptName
-    QCFString psName;
-    if (ATSFontGetPostScriptName(FMGetATSFontRefFromFont(fontID), kATSOptionFlagsDefault, &psName) == noErr)
-        props.postscriptName = QString(psName).toUtf8();
-    props.postscriptName = QFontEngine::convertToPostscriptFontFamilyName(props.postscriptName);
-    return props;
-}
-
-void QFontEngineMac::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
-{
-    ATSUStyle unscaledStyle;
-    ATSUCreateAndCopyStyle(style, &unscaledStyle);
-
-    int emSquare = properties().emSquare.toInt();
-
-    const int maxAttributeCount = 4;
-    ATSUAttributeTag tags[maxAttributeCount + 1];
-    ByteCount sizes[maxAttributeCount + 1];
-    ATSUAttributeValuePtr values[maxAttributeCount + 1];
-    int attributeCount = 0;
-
-    Fixed size = FixRatio(emSquare, 1);
-    tags[attributeCount] = kATSUSizeTag;
-    sizes[attributeCount] = sizeof(size);
-    values[attributeCount] = &size;
-    ++attributeCount;
-
-    Q_ASSERT(attributeCount < maxAttributeCount + 1);
-    OSStatus err = ATSUSetAttributes(unscaledStyle, attributeCount, tags, sizes, values);
-    Q_ASSERT(err == noErr);
-    Q_UNUSED(err);
-
-    // various CTFont metrics functions: CTFontGetBoundingRectsForGlyphs, CTFontGetAdvancesForGlyphs
-    GlyphID atsuGlyph = glyph;
-    ATSGlyphScreenMetrics atsuMetrics;
-    ATSUGlyphGetScreenMetrics(unscaledStyle, 1, &atsuGlyph, 0,
-                              /* iForcingAntiAlias =*/ false,
-                              /* iAntiAliasSwitch =*/true,
-                              &atsuMetrics);
-
-    metrics->width = int(atsuMetrics.width);
-    metrics->height = int(atsuMetrics.height);
-    metrics->x = QFixed::fromReal(atsuMetrics.topLeft.x);
-    metrics->y = -QFixed::fromReal(atsuMetrics.topLeft.y);
-    metrics->xoff = QFixed::fromReal(atsuMetrics.deviceAdvance.x);
-    metrics->yoff = QFixed::fromReal(atsuMetrics.deviceAdvance.y);
-
-    QFixedPoint p;
-    addGlyphsToPathHelper(unscaledStyle, &glyph, &p, 1, path);
-
-    ATSUDisposeStyle(unscaledStyle);
-}
-#endif // !QT_MAC_USE_COCOA
-
-QT_END_NAMESPACE
diff --git a/src/gui/text/qfontengine_mac_p.h b/src/gui/text/qfontengine_mac_p.h
deleted file mode 100644 (file)
index 8d8fe07..0000000
+++ /dev/null
@@ -1,171 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QFONTENGINE_MAC_P_H
-#define QFONTENGINE_MAC_P_H
-
-#include <qfontengine_p.h>
-
-#ifndef QT_MAC_USE_COCOA
-
-QT_BEGIN_NAMESPACE
-
-class QFontEngineMacMulti;
-class QFontEngineMac : public QFontEngine
-{
-    friend class QFontEngineMacMulti;
-public:
-    QFontEngineMac(ATSUStyle baseStyle, ATSUFontID fontID, const QFontDef &def, QFontEngineMacMulti *multiEngine = 0);
-    virtual ~QFontEngineMac();
-
-    virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *numGlyphs, QTextEngine::ShaperFlags flags) const;
-    virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
-    virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
-    virtual glyph_metrics_t boundingBox(glyph_t glyph);
-
-    virtual QFixed ascent() const;
-    virtual QFixed descent() const;
-    virtual QFixed leading() const;
-    virtual QFixed xHeight() const;
-    virtual qreal maxCharWidth() const;
-    virtual QFixed averageCharWidth() const;
-
-    virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs,
-                                 QPainterPath *path, QTextItem::RenderFlags);
-
-    virtual const char *name() const { return "QFontEngineMac"; }
-
-    virtual bool canRender(const QChar *string, int len);
-
-    virtual int synthesized() const { return synthesisFlags; }
-
-    virtual Type type() const { return QFontEngine::Mac; }
-
-    void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight);
-
-    virtual FaceId faceId() const;
-    virtual QByteArray getSfntTable(uint tag) const;
-    virtual Properties properties() const;
-    virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
-    virtual QImage alphaMapForGlyph(glyph_t);
-    virtual QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, int margin, const QTransform &t);
-
-private:
-    QImage imageForGlyph(glyph_t glyph, int margin, bool colorful);
-
-    ATSUFontID fontID;
-    QCFType<CGFontRef> cgFont;
-    ATSUStyle style;
-    int synthesisFlags;
-    mutable QGlyphLayout kashidaGlyph;
-    QFontEngineMacMulti *multiEngine;
-    mutable const unsigned char *cmap;
-    mutable bool symbolCMap;
-    mutable QByteArray cmapTable;
-    CGAffineTransform transform;
-    QFixed m_ascent;
-    QFixed m_descent;
-    QFixed m_leading;
-    qreal m_maxCharWidth;
-    QFixed m_xHeight;
-    QFixed m_averageCharWidth;
-};
-
-class QFontEngineMacMulti : public QFontEngineMulti
-{
-    friend class QFontEngineMac;
-public:
-    // internal
-    struct ShaperItem
-    {
-        inline ShaperItem() : string(0), from(0), length(0),
-        log_clusters(0), charAttributes(0) {}
-
-        const QChar *string;
-        int from;
-        int length;
-        QGlyphLayout glyphs;
-        unsigned short *log_clusters;
-        const HB_CharAttributes *charAttributes;
-        QTextEngine::ShaperFlags flags;
-    };
-
-    QFontEngineMacMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning);
-    virtual ~QFontEngineMacMulti();
-
-    virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
-    bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags,
-                      unsigned short *logClusters, const HB_CharAttributes *charAttributes, QScriptItem *) const;
-
-    virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-    virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
-    virtual const char *name() const { return "ATSUI"; }
-
-    virtual bool canRender(const QChar *string, int len);
-
-    inline ATSUFontID macFontID() const { return fontID; }
-
-protected:
-    virtual void loadEngine(int at);
-
-private:
-    inline const QFontEngineMac *engineAt(int i) const
-    { return static_cast<const QFontEngineMac *>(engines.at(i)); }
-
-    bool stringToCMapInternal(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, ShaperItem *item) const;
-
-    int fontIndexForFontID(ATSUFontID id) const;
-
-    ATSUFontID fontID;
-    uint kerning : 1;
-
-    mutable ATSUTextLayout textLayout;
-    mutable ATSUStyle style;
-    CGAffineTransform transform;
-};
-
-QT_END_NAMESPACE
-
-#endif //!QT_MAC_USE_COCOA
-
-#endif // QFONTENGINE_MAC_P_H
diff --git a/src/gui/text/qfontengine_win.cpp b/src/gui/text/qfontengine_win.cpp
deleted file mode 100644 (file)
index d4782a6..0000000
+++ /dev/null
@@ -1,1379 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#if _WIN32_WINNT < 0x0500
-#undef _WIN32_WINNT
-#define _WIN32_WINNT 0x0500
-#endif
-
-#include "qfontengine_p.h"
-#include "qtextengine_p.h"
-#include <qglobal.h>
-#include "qt_windows.h"
-#include <qapplication_p.h>
-
-#include <qsystemlibrary_p.h>
-#include <qpaintdevice.h>
-#include <qpainter.h>
-#include <limits.h>
-
-#include <qendian.h>
-#include <qmath.h>
-#include <qthreadstorage.h>
-
-#include <qunicodetables_p.h>
-#include <qbitmap.h>
-
-#include <qpainter_p.h>
-#include "qpaintengine.h"
-#include <qpaintengine_raster_p.h>
-#include <qimage.h>
-
-#if defined(Q_WS_WINCE)
-#include "qguifunctions_wince.h"
-#endif
-
-//### mingw needed define
-#ifndef TT_PRIM_CSPLINE
-#define TT_PRIM_CSPLINE 3
-#endif
-
-#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)) \
-   )
-
-// common DC for all fonts
-
-QT_BEGIN_NAMESPACE
-
-class QtHDC
-{
-    HDC _hdc;
-public:
-    QtHDC()
-    {
-        HDC displayDC = GetDC(0);
-        _hdc = CreateCompatibleDC(displayDC);
-        ReleaseDC(0, displayDC);
-    }
-    ~QtHDC()
-    {
-        if (_hdc)
-            DeleteDC(_hdc);
-    }
-    HDC hdc() const
-    {
-        return _hdc;
-    }
-};
-
-#ifndef QT_NO_THREAD
-Q_GLOBAL_STATIC(QThreadStorage<QtHDC *>, local_shared_dc)
-HDC shared_dc()
-{
-    QtHDC *&hdc = local_shared_dc()->localData();
-    if (!hdc)
-        hdc = new QtHDC;
-    return hdc->hdc();
-}
-#else
-HDC shared_dc()
-{
-    return 0;
-}
-#endif
-
-#ifndef Q_WS_WINCE
-typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT);
-static PtrGetCharWidthI ptrGetCharWidthI = 0;
-static bool resolvedGetCharWidthI = false;
-
-static void resolveGetCharWidthI()
-{
-    if (resolvedGetCharWidthI)
-        return;
-
-    QSystemLibrary gdi32(QLatin1String("gdi32"));
-    ptrGetCharWidthI = (PtrGetCharWidthI)gdi32.resolve("GetCharWidthI");
-
-    resolvedGetCharWidthI = true;
-}
-#endif // !defined(Q_WS_WINCE)
-
-// defined in qtextengine_win.cpp
-typedef void *SCRIPT_CACHE;
-typedef HRESULT (WINAPI *fScriptFreeCache)(SCRIPT_CACHE *);
-extern fScriptFreeCache ScriptFreeCache;
-
-static inline quint32 getUInt(unsigned char *p)
-{
-    quint32 val;
-    val = *p++ << 24;
-    val |= *p++ << 16;
-    val |= *p++ << 8;
-    val |= *p;
-
-    return val;
-}
-
-static inline quint16 getUShort(unsigned char *p)
-{
-    quint16 val;
-    val = *p++ << 8;
-    val |= *p;
-
-    return val;
-}
-
-// general font engine
-
-QFixed QFontEngineWin::lineThickness() const
-{
-    if(lineWidth > 0)
-        return lineWidth;
-
-    return QFontEngine::lineThickness();
-}
-
-static OUTLINETEXTMETRIC *getOutlineTextMetric(HDC hdc)
-{
-    int size;
-    size = GetOutlineTextMetrics(hdc, 0, 0);
-    OUTLINETEXTMETRIC *otm = (OUTLINETEXTMETRIC *)malloc(size);
-    GetOutlineTextMetrics(hdc, size, otm);
-    return otm;
-}
-
-bool QFontEngineWin::hasCFFTable() const
-{
-    HDC hdc = shared_dc();
-    SelectObject(hdc, hfont);
-    return GetFontData(hdc, MAKE_TAG('C', 'F', 'F', ' '), 0, 0, 0) != GDI_ERROR;
-}
-
-bool QFontEngineWin::hasCMapTable() const
-{
-    HDC hdc = shared_dc();
-    SelectObject(hdc, hfont);
-    return GetFontData(hdc, MAKE_TAG('c', 'm', 'a', 'p'), 0, 0, 0) != GDI_ERROR;
-}
-
-void QFontEngineWin::getCMap()
-{
-    ttf = (bool)(tm.tmPitchAndFamily & TMPF_TRUETYPE) || hasCMapTable();
-
-    cffTable = hasCFFTable();
-
-    HDC hdc = shared_dc();
-    SelectObject(hdc, hfont);
-    bool symb = false;
-    if (ttf) {
-        cmapTable = getSfntTable(qbswap<quint32>(MAKE_TAG('c', 'm', 'a', 'p')));
-        int size = 0;
-        cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()),
-                       cmapTable.size(), &symb, &size);
-    }
-    if (!cmap) {
-        ttf = false;
-        symb = false;
-    }
-    symbol = symb;
-    designToDevice = 1;
-    _faceId.index = 0;
-    if(cmap) {
-        OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc);
-        designToDevice = QFixed((int)otm->otmEMSquare)/int(otm->otmTextMetrics.tmHeight);
-        unitsPerEm = otm->otmEMSquare;
-        x_height = (int)otm->otmsXHeight;
-        loadKerningPairs(designToDevice);
-        _faceId.filename = QString::fromWCharArray((wchar_t *)((char *)otm + (quintptr)otm->otmpFullName)).toLatin1();
-        lineWidth = otm->otmsUnderscoreSize;
-        fsType = otm->otmfsType;
-        free(otm);
-    } else {
-        unitsPerEm = tm.tmHeight;
-    }
-}
-
-
-inline unsigned int getChar(const QChar *str, int &i, const int len)
-{
-    uint ucs4 = str[i].unicode();
-    if (str[i].isHighSurrogate() && i < len-1 && str[i+1].isLowSurrogate()) {
-        ++i;
-        ucs4 = QChar::surrogateToUcs4(ucs4, str[i].unicode());
-    }
-    return ucs4;
-}
-
-int QFontEngineWin::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout *glyphs, bool mirrored) const
-{
-    int i = 0;
-    int glyph_pos = 0;
-    if (mirrored) {
-#if defined(Q_WS_WINCE)
-        {
-#else
-        if (symbol) {
-            for (; i < numChars; ++i, ++glyph_pos) {
-                unsigned int uc = getChar(str, i, numChars);
-                glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
-                if (!glyphs->glyphs[glyph_pos] && uc < 0x100)
-                    glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
-            }
-        } else if (ttf) {
-            for (; i < numChars; ++i, ++glyph_pos) {
-                unsigned int uc = getChar(str, i, numChars);
-                glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, QChar::mirroredChar(uc));
-            }
-        } else {
-#endif
-            wchar_t first = tm.tmFirstChar;
-            wchar_t last = tm.tmLastChar;
-
-            for (; i < numChars; ++i, ++glyph_pos) {
-                uint ucs = QChar::mirroredChar(getChar(str, i, numChars));
-                if (
-#ifdef Q_WS_WINCE
-                    tm.tmFirstChar > 60000 || // see line 375
-#endif
-                        ucs >= first && ucs <= last)
-                    glyphs->glyphs[glyph_pos] = ucs;
-                else
-                    glyphs->glyphs[glyph_pos] = 0;
-            }
-        }
-    } else {
-#if defined(Q_WS_WINCE)
-        {
-#else
-        if (symbol) {
-            for (; i < numChars; ++i, ++glyph_pos) {
-                unsigned int uc = getChar(str, i, numChars);
-                glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
-                if(!glyphs->glyphs[glyph_pos] && uc < 0x100)
-                    glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
-            }
-        } else if (ttf) {
-            for (; i < numChars; ++i, ++glyph_pos) {
-                unsigned int uc = getChar(str, i, numChars);
-                glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
-            }
-        } else {
-#endif
-            wchar_t first = tm.tmFirstChar;
-            wchar_t last = tm.tmLastChar;
-
-            for (; i < numChars; ++i, ++glyph_pos) {
-                uint uc = getChar(str, i, numChars);
-                if (
-#ifdef Q_WS_WINCE
-                    tm.tmFirstChar > 60000 || // see comment in QFontEngineWin
-#endif
-                        uc >= first && uc <= last)
-                    glyphs->glyphs[glyph_pos] = uc;
-                else
-                    glyphs->glyphs[glyph_pos] = 0;
-            }
-        }
-    }
-    glyphs->numGlyphs = glyph_pos;
-    return glyph_pos;
-}
-
-
-QFontEngineWin::QFontEngineWin(const QString &name, HFONT _hfont, bool stockFont, LOGFONT lf)
-{
-    //qDebug("regular windows font engine created: font='%s', size=%d", name, lf.lfHeight);
-
-    _name = name;
-
-    cmap = 0;
-    hfont = _hfont;
-    logfont = lf;
-    HDC hdc = shared_dc();
-    SelectObject(hdc, hfont);
-    this->stockFont = stockFont;
-    fontDef.pixelSize = -lf.lfHeight;
-
-    lbearing = SHRT_MIN;
-    rbearing = SHRT_MIN;
-    synthesized_flags = -1;
-    lineWidth = -1;
-    x_height = -1;
-
-    BOOL res = GetTextMetrics(hdc, &tm);
-    fontDef.fixedPitch = !(tm.tmPitchAndFamily & TMPF_FIXED_PITCH);
-    if (!res) {
-        qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
-        ZeroMemory(&tm, sizeof(TEXTMETRIC));
-    }
-
-    cache_cost = tm.tmHeight * tm.tmAveCharWidth * 2000;
-    getCMap();
-
-    widthCache = 0;
-    widthCacheSize = 0;
-    designAdvances = 0;
-    designAdvancesSize = 0;
-
-#ifndef Q_WS_WINCE
-    if (!resolvedGetCharWidthI)
-        resolveGetCharWidthI();
-#endif
-}
-
-QFontEngineWin::~QFontEngineWin()
-{
-    if (designAdvances)
-        free(designAdvances);
-
-    if (widthCache)
-        free(widthCache);
-
-    // make sure we aren't by accident still selected
-    SelectObject(shared_dc(), (HFONT)GetStockObject(SYSTEM_FONT));
-
-    if (!stockFont) {
-        if (!DeleteObject(hfont))
-            qErrnoWarning("QFontEngineWin: failed to delete non-stock font...");
-    }
-}
-
-HGDIOBJ QFontEngineWin::selectDesignFont() const
-{
-    LOGFONT f = logfont;
-    f.lfHeight = unitsPerEm;
-    f.lfWidth = 0;
-    HFONT designFont = CreateFontIndirect(&f);
-    return SelectObject(shared_dc(), designFont);
-}
-
-bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
-    if (*nglyphs < len) {
-        *nglyphs = len;
-        return false;
-    }
-
-    *nglyphs = getGlyphIndexes(str, len, glyphs, flags & QTextEngine::RightToLeft);
-
-    if (flags & QTextEngine::GlyphIndicesOnly)
-        return true;
-
-    recalcAdvances(glyphs, flags);
-    return true;
-}
-
-inline void calculateTTFGlyphWidth(HDC hdc, UINT glyph, int &width)
-{
-#if defined(Q_WS_WINCE)
-    GetCharWidth32(hdc, glyph, glyph, &width);
-#else
-    if (ptrGetCharWidthI)
-        ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
-#endif
-}
-
-void QFontEngineWin::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
-    HGDIOBJ oldFont = 0;
-    HDC hdc = shared_dc();
-    if (ttf && (flags & QTextEngine::DesignMetrics)) {
-        for(int i = 0; i < glyphs->numGlyphs; i++) {
-            unsigned int glyph = glyphs->glyphs[i];
-            if(int(glyph) >= designAdvancesSize) {
-                int newSize = (glyph + 256) >> 8 << 8;
-                designAdvances = q_check_ptr((QFixed *)realloc(designAdvances,
-                            newSize*sizeof(QFixed)));
-                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_x[i] = designAdvances[glyph];
-            glyphs->advances_y[i] = 0;
-        }
-        if(oldFont)
-            DeleteObject(SelectObject(hdc, oldFont));
-    } else {
-        for(int i = 0; i < glyphs->numGlyphs; i++) {
-            unsigned int glyph = glyphs->glyphs[i];
-
-            glyphs->advances_y[i] = 0;
-
-            if (glyph >= widthCacheSize) {
-                int newSize = (glyph + 256) >> 8 << 8;
-                widthCache = q_check_ptr((unsigned char *)realloc(widthCache,
-                            newSize*sizeof(QFixed)));
-                memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
-                widthCacheSize = newSize;
-            }
-            glyphs->advances_x[i] = widthCache[glyph];
-            // font-width cache failed
-            if (glyphs->advances_x[i] == 0) {
-                int width = 0;
-                if (!oldFont)
-                    oldFont = SelectObject(hdc, hfont);
-
-                if (!ttf) {
-                    QChar ch[2] = { ushort(glyph), 0 };
-                    int chrLen = 1;
-                    if (glyph > 0xffff) {
-                        ch[0] = QChar::highSurrogate(glyph);
-                        ch[1] = QChar::lowSurrogate(glyph);
-                        ++chrLen;
-                    }
-                    SIZE size = {0, 0};
-                    GetTextExtentPoint32(hdc, (wchar_t *)ch, chrLen, &size);
-                    width = size.cx;
-                } else {
-                    calculateTTFGlyphWidth(hdc, glyph, width);
-                }
-                glyphs->advances_x[i] = width;
-                // if glyph's within cache range, store it for later
-                if (width > 0 && width < 0x100)
-                    widthCache[glyph] = width;
-            }
-        }
-
-        if (oldFont)
-            SelectObject(hdc, oldFont);
-    }
-}
-
-glyph_metrics_t QFontEngineWin::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);
-}
-
-#ifndef Q_WS_WINCE
-bool QFontEngineWin::getOutlineMetrics(glyph_t glyph, const QTransform &t, glyph_metrics_t *metrics) const
-{
-    Q_ASSERT(metrics != 0);
-
-    HDC hdc = shared_dc();
-
-    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 = t.m11();
-        xform.eM12 = t.m12();
-        xform.eM21 = t.m21();
-        xform.eM22 = 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;
-    }
-}
-#endif
-
-glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph, const QTransform &t)
-{
-#ifndef Q_WS_WINCE
-    HDC hdc = shared_dc();
-    SelectObject(hdc, hfont);
-
-    glyph_metrics_t glyphMetrics;
-    bool success = getOutlineMetrics(glyph, t, &glyphMetrics);
-
-    if (!ttf && !success) {
-        // Bitmap fonts
-        wchar_t ch = 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;
-#else
-    HDC hdc = shared_dc();
-    HGDIOBJ oldFont = SelectObject(hdc, hfont);
-
-    ABC abc;
-    int width;
-    int advance;
-#ifdef GWES_MGTT    // true type fonts
-    if (GetCharABCWidths(hdc, glyph, glyph, &abc)) {
-        width = qAbs(abc.abcA) + abc.abcB + qAbs(abc.abcC);
-        advance = abc.abcA + abc.abcB + abc.abcC;
-    }
-    else
-#endif
-#if defined(GWES_MGRAST) || defined(GWES_MGRAST2)   // raster fonts
-    if (GetCharWidth32(hdc, glyph, glyph, &width)) {
-        advance = width;
-    }
-    else
-#endif
-    {   // fallback
-        width = tm.tmMaxCharWidth;
-        advance = width;
-    }
-
-    SelectObject(hdc, oldFont);
-    return glyph_metrics_t(0, -tm.tmAscent, width, tm.tmHeight, advance, 0).transformed(t);
-#endif
-}
-
-QFixed QFontEngineWin::ascent() const
-{
-    return tm.tmAscent;
-}
-
-QFixed QFontEngineWin::descent() const
-{
-    // ### we substract 1 to even out the historical +1 in QFontMetrics's
-    // ### height=asc+desc+1 equation. Fix in Qt5.
-    return tm.tmDescent - 1;
-}
-
-QFixed QFontEngineWin::leading() const
-{
-    return tm.tmExternalLeading;
-}
-
-
-QFixed QFontEngineWin::xHeight() const
-{
-    if(x_height >= 0)
-        return x_height;
-    return QFontEngine::xHeight();
-}
-
-QFixed QFontEngineWin::averageCharWidth() const
-{
-    return tm.tmAveCharWidth;
-}
-
-qreal QFontEngineWin::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 QFontEngineWin::getGlyphBearings(glyph_t glyph, qreal *leftBearing, qreal *rightBearing)
-{
-    HDC hdc = shared_dc();
-    SelectObject(hdc, hfont);
-
-#ifndef Q_WS_WINCE
-    if (ttf)
-#endif
-
-    {
-        ABC abcWidths;
-        GetCharABCWidthsI(hdc, glyph, 1, 0, &abcWidths);
-        if (leftBearing)
-            *leftBearing = abcWidths.abcA;
-        if (rightBearing)
-            *rightBearing = abcWidths.abcC;
-    }
-
-#ifndef Q_WS_WINCE
-    else {
-        QFontEngine::getGlyphBearings(glyph, leftBearing, rightBearing);
-    }
-#endif
-}
-#endif // Q_CC_MINGW
-
-qreal QFontEngineWin::minLeftBearing() const
-{
-    if (lbearing == SHRT_MIN)
-        minRightBearing(); // calculates both
-
-    return lbearing;
-}
-
-qreal QFontEngineWin::minRightBearing() const
-{
-#ifdef Q_WS_WINCE
-    if (rbearing == SHRT_MIN) {
-        int ml = 0;
-        int mr = 0;
-        HDC hdc = shared_dc();
-        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;
-        }
-        lbearing = ml;
-        rbearing = mr;
-    }
-
-    return rbearing;
-#else
-    if (rbearing == SHRT_MIN) {
-        int ml = 0;
-        int mr = 0;
-        HDC hdc = shared_dc();
-        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;
-#endif
-}
-
-
-const char *QFontEngineWin::name() const
-{
-    return 0;
-}
-
-bool QFontEngineWin::canRender(const QChar *string,  int len)
-{
-    if (symbol) {
-        for (int i = 0; i < len; ++i) {
-            unsigned int uc = getChar(string, i, len);
-            if (getTrueTypeGlyphIndex(cmap, uc) == 0) {
-                if (uc < 0x100) {
-                    if (getTrueTypeGlyphIndex(cmap, uc + 0xf000) == 0)
-                        return false;
-                } else {
-                    return false;
-                }
-            }
-        }
-    } else if (ttf) {
-        for (int i = 0; i < len; ++i) {
-            unsigned int uc = getChar(string, i, len);
-            if (getTrueTypeGlyphIndex(cmap, uc) == 0)
-                return false;
-        }
-    } else {
-        while(len--) {
-            if (tm.tmFirstChar > string->unicode() || tm.tmLastChar < string->unicode())
-                return false;
-        }
-    }
-    return true;
-}
-
-QFontEngine::Type QFontEngineWin::type() const
-{
-    return QFontEngine::Win;
-}
-
-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) {
-    return QPointF(qt_fixed_to_double(pt.x) * scale, -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)
-{
-#if defined(Q_WS_WINCE)
-    Q_UNUSED(glyph);
-    Q_UNUSED(hdc);
-#endif
-    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));
-
-#ifndef Q_OS_WINCE
-    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;
-        int res = GetGlyphOutline(hdc, glyph, format, &gMetric, 0, 0, &mat);
-        if (res == 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);
-    }
-#endif
-
-    uint glyphFormat = GGO_NATIVE;
-
-    if (ttf)
-        glyphFormat |= GGO_GLYPH_INDEX;
-
-    int bufferSize = GDI_ERROR;
-#if !defined(Q_WS_WINCE)
-    bufferSize = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
-#endif
-    if ((DWORD)bufferSize == GDI_ERROR) {
-        return false;
-    }
-
-    void *dataBuffer = new char[bufferSize];
-    DWORD ret = GDI_ERROR;
-#if !defined(Q_WS_WINCE)
-    ret = GetGlyphOutline(hdc, glyph, glyphFormat, &gMetric, bufferSize, dataBuffer, &mat);
-#endif
-    if (ret == GDI_ERROR) {
-        delete [](char *)dataBuffer;
-        return false;
-    }
-
-#ifdef Q_OS_WINCE
-    if (metric) {
-        // #### obey scale
-        *metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y,
-                                  (int)gMetric.gmBlackBoxX, (int)gMetric.gmBlackBoxY,
-                                  gMetric.gmCellIncX, gMetric.gmCellIncY);
-    }
-#endif
-
-    int offset = 0;
-    int headerOffset = 0;
-    TTPOLYGONHEADER *ttph = 0;
-
-    QPointF oset = position.toPointF();
-    while (headerOffset < bufferSize) {
-        ttph = (TTPOLYGONHEADER*)((char *)dataBuffer + headerOffset);
-
-        QPointF lastPoint(qt_to_qpointf(ttph->pfxStart, scale));
-        path->moveTo(lastPoint + oset);
-        offset += sizeof(TTPOLYGONHEADER);
-        TTPOLYCURVE *curve;
-        while (offset<int(headerOffset + ttph->cb)) {
-            curve = (TTPOLYCURVE*)((char*)(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) + 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) + oset;
-                    QPointF p2 = qt_to_qpointf(curve->apfx[i+1], scale) + 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) + oset;
-                    QPointF p3 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
-                    QPointF p4 = qt_to_qpointf(curve->apfx[i++], scale) + 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 [] (char*)dataBuffer;
-
-    return true;
-}
-
-void QFontEngineWin::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
-                                     QPainterPath *path, QTextItem::RenderFlags)
-{
-    LOGFONT lf = 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 = shared_dc();
-    HGDIOBJ oldfont = SelectObject(hdc, hf);
-
-    for(int i = 0; i < nglyphs; ++i) {
-        if (!addGlyphToPath(glyphs[i], positions[i], hdc, path, ttf, /*metric*/0,
-                            qreal(fontDef.pixelSize) / unitsPerEm)) {
-            // 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 QFontEngineWin::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
-                                      QPainterPath *path, QTextItem::RenderFlags flags)
-{
-#if !defined(Q_WS_WINCE)
-    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;
-        }
-    }
-#endif
-    QFontEngine::addBitmapFontToPath(x, y, glyphs, path, flags);
-}
-
-QFontEngine::FaceId QFontEngineWin::faceId() const
-{
-    return _faceId;
-}
-
-QT_BEGIN_INCLUDE_NAMESPACE
-#include <qdebug.h>
-QT_END_INCLUDE_NAMESPACE
-
-int QFontEngineWin::synthesized() const
-{
-    if(synthesized_flags == -1) {
-        synthesized_flags = 0;
-        if(ttf) {
-            const DWORD HEAD = MAKE_TAG('h', 'e', 'a', 'd');
-            HDC hdc = shared_dc();
-            SelectObject(hdc, hfont);
-            uchar data[4];
-            GetFontData(hdc, HEAD, 44, &data, 4);
-            USHORT macStyle = getUShort(data);
-            if (tm.tmItalic && !(macStyle & 2))
-                synthesized_flags = SynthesizedItalic;
-            if (fontDef.stretch != 100 && ttf)
-                synthesized_flags |= SynthesizedStretch;
-            if (tm.tmWeight >= 500 && !(macStyle & 1))
-                synthesized_flags |= SynthesizedBold;
-            //qDebug() << "font is" << _name <<
-            //    "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags;
-        }
-    }
-    return synthesized_flags;
-}
-
-QFixed QFontEngineWin::emSquareSize() const
-{
-    return unitsPerEm;
-}
-
-QFontEngine::Properties QFontEngineWin::properties() const
-{
-    LOGFONT lf = logfont;
-    lf.lfHeight = unitsPerEm;
-    HFONT hf = CreateFontIndirect(&lf);
-    HDC hdc = shared_dc();
-    HGDIOBJ oldfont = SelectObject(hdc, hf);
-    OUTLINETEXTMETRIC *otm = getOutlineTextMetric(hdc);
-    Properties p;
-    p.emSquare = unitsPerEm;
-    p.italicAngle = otm->otmItalicAngle;
-    p.postscriptName = QString::fromWCharArray((wchar_t *)((char *)otm + (quintptr)otm->otmpFamilyName)).toLatin1();
-    p.postscriptName += QString::fromWCharArray((wchar_t *)((char *)otm + (quintptr)otm->otmpStyleName)).toLatin1();
-    p.postscriptName = QFontEngine::convertToPostscriptFontFamilyName(p.postscriptName);
-    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 QFontEngineWin::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
-{
-    LOGFONT lf = logfont;
-    lf.lfHeight = unitsPerEm;
-    int flags = synthesized();
-    if(flags & SynthesizedItalic)
-        lf.lfItalic = false;
-    lf.lfWidth = 0;
-    HFONT hf = CreateFontIndirect(&lf);
-    HDC hdc = shared_dc();
-    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 QFontEngineWin::getSfntTableData(uint tag, uchar *buffer, uint *length) const
-{
-    if (!ttf && !cffTable)
-        return false;
-    HDC hdc = shared_dc();
-    SelectObject(hdc, hfont);
-    DWORD t = qbswap<quint32>(tag);
-    *length = GetFontData(hdc, t, 0, buffer, *length);
-    return *length != GDI_ERROR;
-}
-
-#if !defined(CLEARTYPE_QUALITY)
-#    define CLEARTYPE_QUALITY       5
-#endif
-
-extern bool qt_cleartype_enabled;
-
-QImage *QFontEngineWin::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 || iw <= 0)
-        return 0;
-
-    bool has_transformation = t.type() > QTransform::TxTranslate;
-
-#ifndef Q_WS_WINCE
-    unsigned int options = ttf ? ETO_GLYPH_INDEX : 0;
-    XFORM xform;
-
-    if (has_transformation) {
-        xform.eM11 = t.m11();
-        xform.eM12 = t.m12();
-        xform.eM21 = t.m21();
-        xform.eM22 = t.m22();
-        xform.eDx = margin;
-        xform.eDy = margin;
-
-        QtHDC qthdc;
-        HDC hdc = qthdc.hdc();
-
-        SetGraphicsMode(hdc, GM_ADVANCED);
-        SetWorldTransform(hdc, &xform);
-        HGDIOBJ old_font = SelectObject(hdc, font);
-
-        int 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;
-
-        if (GetGlyphOutline(hdc, glyph, ggo_options, &tgm, 0, 0, &mat) == GDI_ERROR) {
-            qWarning("QWinFontEngine: unable to query transformed glyph metrics...");
-            return 0;
-        }
-
-        iw = tgm.gmBlackBoxX;
-        ih = tgm.gmBlackBoxY;
-
-        xform.eDx -= tgm.gmptGlyphOrigin.x;
-        xform.eDy += tgm.gmptGlyphOrigin.y;
-
-        SetGraphicsMode(hdc, GM_COMPATIBLE);
-        SelectObject(hdc, old_font);
-    }
-#else // else winc
-    unsigned int options = 0;
-#ifdef DEBUG
-    Q_ASSERT(!has_transformation);
-#else
-    Q_UNUSED(has_transformation);
-#endif
-#endif
-
-    QImage *ni = new QImage(iw + 2 * margin + 4,
-                                        ih + 2 * margin + 4,
-                                        QImage::systemFormat(), !qt_cleartype_enabled);
-
-    /*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);
-
-#ifndef Q_OS_WINCE
-    if (has_transformation) {
-        SetGraphicsMode(hdc, GM_ADVANCED);
-        SetWorldTransform(hdc, &xform);
-        ExtTextOut(hdc, 0, 0, options, 0, (LPCWSTR) &glyph, 1, 0);
-    } else
-#endif
-    {
-        ExtTextOut(hdc, -gx + margin, -gy + margin, options, 0, (LPCWSTR) &glyph, 1, 0);
-    }
-    
-    SelectObject(hdc, old_font);
-    return ni;
-}
-
-
-extern uint qt_pow_gamma[256];
-
-QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph, const QTransform &xform)
-{
-    HFONT font = hfont;
-    if (qt_cleartype_enabled) {
-        LOGFONT lf = logfont;
-        lf.lfQuality = ANTIALIASED_QUALITY;
-        font = CreateFontIndirect(&lf);
-    }
-    QImage::Format mask_format = QImage::systemFormat();
-#ifndef Q_OS_WINCE
-    mask_format = QImage::Format_RGB32;
-#endif
-
-    QImage *mask = drawGDIGlyph(font, glyph, 0, xform, mask_format);
-    if (mask == 0)
-        return QImage();
-
-    QImage indexed(mask->width(), mask->height(), QImage::Format_Indexed8);
-
-    // ### This part is kinda pointless, but we'll crash later if we don't because some
-    // code paths expects there to be colortables for index8-bit...
-    QVector<QRgb> colors(256);
-    for (int i=0; i<256; ++i)
-        colors[i] = qRgba(0, 0, 0, i);
-    indexed.setColorTable(colors);
-
-    // 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 = indexed.scanLine(y);
-        if (mask->image.format() == QImage::Format_RGB16) {
-            const qint16 *src = (qint16 *) ((const QImage &) mask->image).scanLine(y);
-            for (int x=0; x<mask->width(); ++x)
-                dest[x] = 255 - qGray(src[x]);
-        } else {
-            const uint *src = (uint *) ((const QImage &) mask->image).scanLine(y);
-            for (int x=0; x<mask->width(); ++x) {
-#ifdef Q_OS_WINCE
-                dest[x] = 255 - qGray(src[x]);
-#else
-                if (QImage::systemFormat() == QImage::Format_RGB16)
-                    dest[x] = 255 - qGray(src[x]);
-                else
-                    dest[x] = 255 - (qt_pow_gamma[qGray(src[x])] * 255. / 2047.);
-#endif
-            }
-        }
-    }
-
-    // Cleanup...
-    delete mask;
-    if (qt_cleartype_enabled) {
-        DeleteObject(font);
-    }
-
-    return indexed;
-}
-
-#define SPI_GETFONTSMOOTHINGCONTRAST           0x200C
-#define SPI_SETFONTSMOOTHINGCONTRAST           0x200D
-
-QImage QFontEngineWin::alphaRGBMapForGlyph(glyph_t glyph, QFixed, int margin, const QTransform &t)
-{
-    HFONT font = hfont;
-
-    int contrast;
-    SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &contrast, 0);
-    SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, (void *) 1000, 0);
-
-    QImage *mask = drawGDIGlyph(font, glyph, margin, t, QImage::Format_RGB32);
-    SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, (void *) 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) {
-        uint *dest = (uint *) rgbMask.scanLine(y);
-        const uint *src = (uint *) source.scanLine(y);
-        for (int x=0; x<mask->width(); ++x) {
-            dest[x] = 0xffffffff - (0x00ffffff & src[x]);
-        }
-    }
-
-    delete mask;
-
-    return rgbMask;
-}
-
-// From qfontdatabase_win.cpp
-extern QFontEngine *qt_load_font_engine_win(const QFontDef &request);
-QFontEngine *QFontEngineWin::cloneWithSize(qreal pixelSize) const
-{
-    QFontDef request = fontDef;
-    QString actualFontName = request.family;
-    if (!uniqueFamilyName.isEmpty())
-        request.family = uniqueFamilyName;
-    request.pixelSize = pixelSize;
-
-    QFontEngine *fontEngine = qt_load_font_engine_win(request);
-    if (fontEngine != NULL)
-        fontEngine->fontDef.family = actualFontName;
-
-    return fontEngine;
-}
-
-// -------------------------------------- Multi font engine
-
-QFontEngineMultiWin::QFontEngineMultiWin(QFontEngine *first, const QStringList &fallbacks)
-        : QFontEngineMulti(fallbacks.size()+1),
-          fallbacks(fallbacks)
-{
-    engines[0] = first;
-    first->ref.ref();
-    fontDef = engines[0]->fontDef;
-    cache_cost = first->cache_cost;
-}
-
-void QFontEngineMultiWin::loadEngine(int at)
-{
-    Q_ASSERT(at < engines.size());
-    Q_ASSERT(engines.at(at) == 0);
-
-    QString fam = fallbacks.at(at-1);
-
-    LOGFONT lf = static_cast<QFontEngineWin *>(engines.at(0))->logfont;
-    memcpy(lf.lfFaceName, fam.utf16(), sizeof(wchar_t) * qMin(fam.length() + 1, 32));  // 32 = Windows hard-coded
-    HFONT hfont = CreateFontIndirect(&lf);
-
-    bool stockFont = false;
-    if (hfont == 0) {
-        hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
-        stockFont = true;
-    }
-    engines[at] = new QFontEngineWin(fam, hfont, stockFont, lf);
-    engines[at]->ref.ref();
-    engines[at]->fontDef = fontDef;
-
-    // TODO: increase cost in QFontCache for the font engine loaded here
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/text/qfontengine_win_p.h b/src/gui/text/qfontengine_win_p.h
deleted file mode 100644 (file)
index ba48973..0000000
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QFONTENGINE_WIN_P_H
-#define QFONTENGINE_WIN_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/qconfig.h>
-
-QT_BEGIN_NAMESPACE
-
-class QFontEngineWin : public QFontEngine
-{
-public:
-    QFontEngineWin(const QString &name, HFONT, bool, LOGFONT);
-    ~QFontEngineWin();
-
-    virtual QFixed lineThickness() const;
-    virtual Properties properties() const;
-    virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
-    virtual FaceId faceId() const;
-    virtual bool getSfntTableData(uint tag, uchar *buffer, uint *length) const;
-    virtual int synthesized() const;
-    virtual QFixed emSquareSize() const;
-
-    virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
-    virtual void recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags) const;
-
-    virtual void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags);
-    virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
-                         QPainterPath *path, QTextItem::RenderFlags flags);
-
-    HGDIOBJ selectDesignFont() const;
-
-    virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
-    virtual glyph_metrics_t boundingBox(glyph_t g) { return boundingBox(g, QTransform()); }
-    virtual glyph_metrics_t boundingBox(glyph_t g, const QTransform &t);
-
-
-    virtual QFixed ascent() const;
-    virtual QFixed descent() const;
-    virtual QFixed leading() const;
-    virtual QFixed xHeight() const;
-    virtual QFixed averageCharWidth() const;
-    virtual qreal maxCharWidth() const;
-    virtual qreal minLeftBearing() const;
-    virtual qreal minRightBearing() const;
-
-    virtual const char *name() const;
-
-    bool canRender(const QChar *string, int len);
-
-    Type type() const;
-
-    virtual QImage alphaMapForGlyph(glyph_t t) { return alphaMapForGlyph(t, QTransform()); }
-    virtual QImage alphaMapForGlyph(glyph_t, const QTransform &xform);
-    virtual QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, int margin, const QTransform &xform);
-
-    virtual QFontEngine *cloneWithSize(qreal pixelSize) const;
-
-#ifndef Q_CC_MINGW
-    virtual void getGlyphBearings(glyph_t glyph, qreal *leftBearing = 0, qreal *rightBearing = 0);
-#endif
-
-    int getGlyphIndexes(const QChar *ch, int numChars, QGlyphLayout *glyphs, bool mirrored) const;
-    void getCMap();
-
-#ifndef Q_WS_WINCE
-    bool getOutlineMetrics(glyph_t glyph, const QTransform &t, glyph_metrics_t *metrics) const;
-#endif
-
-    QString     _name;
-    QString     uniqueFamilyName;
-    HFONT       hfont;
-    LOGFONT     logfont;
-    uint        stockFont  : 1;
-    uint        ttf        : 1;
-    uint        hasOutline : 1;
-    uint        cffTable   : 1;
-    TEXTMETRIC  tm;
-    int         lw;
-    const unsigned char *cmap;
-    QByteArray cmapTable;
-    mutable qreal lbearing;
-    mutable qreal rbearing;
-    QFixed designToDevice;
-    int unitsPerEm;
-    QFixed x_height;
-    FaceId _faceId;
-
-    mutable int synthesized_flags;
-    mutable QFixed lineWidth;
-    mutable unsigned char *widthCache;
-    mutable uint widthCacheSize;
-    mutable QFixed *designAdvances;
-    mutable int designAdvancesSize;
-
-private:
-    bool hasCFFTable() const;
-    bool hasCMapTable() const;
-    QImage *drawGDIGlyph(HFONT font, glyph_t, int margin, const QTransform &xform,
-                               QImage::Format mask_format);
-
-};
-
-class QFontEngineMultiWin : public QFontEngineMulti
-{
-public:
-    QFontEngineMultiWin(QFontEngine *first, const QStringList &fallbacks);
-    void loadEngine(int at);
-
-    QStringList fallbacks;
-};
-
-QT_END_NAMESPACE
-
-#endif // QFONTENGINE_WIN_P_H
diff --git a/src/gui/text/qrawfont_mac.cpp b/src/gui/text/qrawfont_mac.cpp
deleted file mode 100644 (file)
index fdc548f..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the test suite 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QtCore/qglobal.h>
-
-#if !defined(QT_NO_RAWFONT)
-
-#include "qrawfont_p.h"
-#include "qfontengine_coretext_p.h"
-
-QT_BEGIN_NAMESPACE
-
-void QRawFontPrivate::platformCleanUp()
-{
-}
-
-static void releaseFontData(void* info, const void* data, size_t size)
-{
-    Q_UNUSED(data);
-    Q_UNUSED(size);
-    delete (QByteArray*)info;
-}
-
-extern int qt_defaultDpi();
-
-void QRawFontPrivate::platformLoadFromData(const QByteArray &fontData,
-                                           qreal pixelSize,
-                                           QFont::HintingPreference hintingPreference)
-{
-    // Mac OS X ignores it
-    Q_UNUSED(hintingPreference);
-
-    QByteArray* fontDataCopy = new QByteArray(fontData);
-    QCFType<CGDataProviderRef> dataProvider = CGDataProviderCreateWithData(fontDataCopy,
-            fontDataCopy->constData(), fontDataCopy->size(), releaseFontData);
-
-    CGFontRef cgFont = CGFontCreateWithDataProvider(dataProvider);
-
-    if (cgFont == NULL) {
-        qWarning("QRawFont::platformLoadFromData: CGFontCreateWithDataProvider failed");
-    } else {
-        QFontDef def;
-        def.pixelSize = pixelSize;
-        def.pointSize = pixelSize * 72.0 / qt_defaultDpi();
-        fontEngine = new QCoreTextFontEngine(cgFont, def);
-        CFRelease(cgFont);
-        fontEngine->ref.ref();
-    }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_RAWFONT
diff --git a/src/gui/text/qrawfont_win.cpp b/src/gui/text/qrawfont_win.cpp
deleted file mode 100644 (file)
index 65639a3..0000000
+++ /dev/null
@@ -1,701 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the test suite 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qrawfont_p.h"
-
-#if !defined(QT_NO_RAWFONT)
-
-#include <qsystemlibrary_p.h>
-
-#if !defined(QT_NO_DIRECTWRITE)
-#  include "qfontenginedirectwrite_p.h"
-#  include <dwrite.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-namespace {
-
-    template<typename T>
-    struct BigEndian
-    {
-        quint8 data[sizeof(T)];
-
-        operator T() const
-        {
-            T littleEndian = 0;
-            for (int i = 0; i < int(sizeof(T)); ++i)
-                littleEndian |= data[i] << ((sizeof(T) - i - 1) * 8);
-
-            return littleEndian;
-        }
-
-        BigEndian<T> &operator=(const T &t)
-        {
-            for (int i = 0; i < int(sizeof(T)); ++i)
-                data[i] = ((t >> (sizeof(T) - i - 1) * 8) & 0xff);
-
-            return *this;
-        }
-    };
-
-#   pragma pack(1)
-
-    // Common structure for all formats of the "name" table
-    struct NameTable
-    {
-        BigEndian<quint16> format;
-        BigEndian<quint16> count;
-        BigEndian<quint16> stringOffset;
-    };
-
-    struct NameRecord
-    {
-        BigEndian<quint16> platformID;
-        BigEndian<quint16> encodingID;
-        BigEndian<quint16> languageID;
-        BigEndian<quint16> nameID;
-        BigEndian<quint16> length;
-        BigEndian<quint16> offset;
-    };
-
-    struct OffsetSubTable
-    {
-        BigEndian<quint32> scalerType;
-        BigEndian<quint16> numTables;
-        BigEndian<quint16> searchRange;
-        BigEndian<quint16> entrySelector;
-        BigEndian<quint16> rangeShift;
-    };
-
-    struct TableDirectory
-    {
-        BigEndian<quint32> identifier;
-        BigEndian<quint32> checkSum;
-        BigEndian<quint32> offset;
-        BigEndian<quint32> length;
-    };
-
-    struct OS2Table
-    {
-        BigEndian<quint16> version;
-        BigEndian<qint16>  avgCharWidth;
-        BigEndian<quint16> weightClass;
-        BigEndian<quint16> widthClass;
-        BigEndian<quint16> type;
-        BigEndian<qint16>  subscriptXSize;
-        BigEndian<qint16>  subscriptYSize;
-        BigEndian<qint16>  subscriptXOffset;
-        BigEndian<qint16>  subscriptYOffset;
-        BigEndian<qint16>  superscriptXSize;
-        BigEndian<qint16>  superscriptYSize;
-        BigEndian<qint16>  superscriptXOffset;
-        BigEndian<qint16>  superscriptYOffset;
-        BigEndian<qint16>  strikeOutSize;
-        BigEndian<qint16>  strikeOutPosition;
-        BigEndian<qint16>  familyClass;
-        quint8             panose[10];
-        BigEndian<quint32> unicodeRanges[4];
-        quint8             vendorID[4];
-        BigEndian<quint16> selection;
-        BigEndian<quint16> firstCharIndex;
-        BigEndian<quint16> lastCharIndex;
-        BigEndian<qint16>  typoAscender;
-        BigEndian<qint16>  typoDescender;
-        BigEndian<qint16>  typoLineGap;
-        BigEndian<quint16> winAscent;
-        BigEndian<quint16> winDescent;
-        BigEndian<quint32> codepageRanges[2];
-        BigEndian<qint16>  height;
-        BigEndian<qint16>  capHeight;
-        BigEndian<quint16> defaultChar;
-        BigEndian<quint16> breakChar;
-        BigEndian<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);
-
-        const BigEndian<quint32> *tagIdPtr =
-                reinterpret_cast<const BigEndian<quint32> *>(tagName.constData());
-        quint32 tagId = *tagIdPtr;
-
-        OffsetSubTable *offsetSubTable = reinterpret_cast<OffsetSubTable *>(m_fontData.data());
-        TableDirectory *tableDirectory = reinterpret_cast<TableDirectory *>(offsetSubTable + 1);
-
-        TableDirectory *nameTableDirectoryEntry = 0;
-        for (int i=0; i<offsetSubTable->numTables; ++i, ++tableDirectory) {
-            if (tableDirectory->identifier == tagId) {
-                nameTableDirectoryEntry = tableDirectory;
-                break;
-            }
-        }
-
-        return nameTableDirectoryEntry;
-    }
-
-    QString EmbeddedFont::familyName(TableDirectory *nameTableDirectoryEntry)
-    {
-        QString name;
-
-        if (nameTableDirectoryEntry == 0)
-            nameTableDirectoryEntry = tableDirectoryEntry("name");
-
-        if (nameTableDirectoryEntry != 0) {
-            NameTable *nameTable = reinterpret_cast<NameTable *>(m_fontData.data()
-                                                                 + nameTableDirectoryEntry->offset);
-            NameRecord *nameRecord = reinterpret_cast<NameRecord *>(nameTable + 1);
-            for (int i=0; i<nameTable->count; ++i, ++nameRecord) {
-                if (nameRecord->nameID == 1
-                 && nameRecord->platformID == 3 // Windows
-                 && nameRecord->languageID == 0x0409) { // US English
-                    const void *ptr = reinterpret_cast<const quint8 *>(nameTable)
-                                                        + nameTable->stringOffset
-                                                        + nameRecord->offset;
-
-                    const BigEndian<quint16> *s = reinterpret_cast<const BigEndian<quint16> *>(ptr);
-                    const BigEndian<quint16> *e = s + nameRecord->length / sizeof(quint16);
-                    while (s != e)
-                        name += QChar(*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() * sizeof(quint16);
-
-        const QString regularString = QString::fromLatin1("Regular");
-        int regularStringSize = regularString.size() * 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 = requiredRecordCount;
-            nameTable->stringOffset = sizeOfHeader;
-
-            NameRecord *nameRecord = reinterpret_cast<NameRecord *>(nameTable + 1);
-            for (int i=0; i<requiredRecordCount; ++i, nameRecord++) {
-                nameRecord->nameID = nameIds[i];
-                nameRecord->encodingID = 1;
-                nameRecord->languageID = 0x0409;
-                nameRecord->platformID = 3;
-                nameRecord->length = newFamilyNameSize;
-
-                // Special case for sub-family
-                if (nameIds[i] == 4) {
-                    nameRecord->offset = newFamilyNameSize;
-                    nameRecord->length = regularStringSize;
-                }
-            }
-
-            // nameRecord now points to string data
-            BigEndian<quint16> *stringStorage = reinterpret_cast<BigEndian<quint16> *>(nameRecord);
-            const quint16 *sourceString = newFamilyName.utf16();
-            for (int i=0; i<newFamilyName.size(); ++i)
-                stringStorage[i] = sourceString[i];
-            stringStorage += newFamilyName.size();
-
-            sourceString = regularString.utf16();
-            for (int i=0; i<regularString.size(); ++i)
-                stringStorage[i] = sourceString[i];
-        }
-
-        quint32 *p = reinterpret_cast<quint32 *>(newNameTable.data());
-        quint32 *tableEnd = reinterpret_cast<quint32 *>(newNameTable.data() + fullSize);
-
-        quint32 checkSum = 0;
-        while (p < tableEnd)
-            checkSum += *(p++);
-
-        nameTableDirectoryEntry->checkSum = checkSum;
-        nameTableDirectoryEntry->offset = m_fontData.size();
-        nameTableDirectoryEntry->length = fullSize;
-
-        m_fontData.append(newNameTable);
-
-        return oldFamilyName;
-    }
-
-#if !defined(QT_NO_DIRECTWRITE)
-
-    class DirectWriteFontFileStream: public IDWriteFontFileStream
-    {
-    public:
-        DirectWriteFontFileStream(const QByteArray &fontData)
-            : m_fontData(fontData)
-            , m_referenceCount(0)
-        {
-        }
-
-        ~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 (fragmentSize + fileOffset <= 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) {}
-
-        ~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("DirectWriteFontFileLoader::CreateStreamFromKey: Wrong key size");
-            return E_FAIL;
-        }
-
-        const void *key = *reinterpret_cast<void * const *>(fontFileReferenceKey);
-        *fontFileStream = NULL;
-        if (!m_fontDatas.contains(key))
-            return E_FAIL;
-
-        QByteArray fontData = m_fontDatas.value(key);
-        DirectWriteFontFileStream *stream = new DirectWriteFontFileStream(fontData);
-        stream->AddRef();
-        *fontFileStream = stream;
-
-        return S_OK;
-    }
-
-    class CustomFontFileLoader
-    {
-    public:
-        CustomFontFileLoader() : m_directWriteFactory(0), m_directWriteFontFileLoader(0)
-        {
-            HRESULT hres = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,
-                                               __uuidof(IDWriteFactory),
-                                               reinterpret_cast<IUnknown **>(&m_directWriteFactory));
-            if (FAILED(hres)) {
-                qErrnoWarning(hres, "CustomFontFileLoader::CustomFontFileLoader: "
-                                    "DWriteCreateFactory failed.");
-            } else {
-                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
-
-
-// From qfontdatabase_win.cpp
-extern QFontEngine *qt_load_font_engine_win(const QFontDef &request);
-// From qfontdatabase.cpp
-extern QFont::Weight weightFromInteger(int weight);
-
-typedef HANDLE (WINAPI *PtrAddFontMemResourceEx)(PVOID, DWORD, PVOID, DWORD *);
-static PtrAddFontMemResourceEx ptrAddFontMemResourceEx = 0;
-typedef BOOL (WINAPI *PtrRemoveFontMemResourceEx)(HANDLE);
-static PtrRemoveFontMemResourceEx ptrRemoveFontMemResourceEx = 0;
-
-static void resolveGdi32()
-{
-    static bool triedResolve = false;
-    if (!triedResolve) {
-        QSystemLibrary gdi32(QLatin1String("gdi32"));
-        if (gdi32.load()) {
-            ptrAddFontMemResourceEx = (PtrAddFontMemResourceEx)gdi32.resolve("AddFontMemResourceEx");
-            ptrRemoveFontMemResourceEx = (PtrRemoveFontMemResourceEx)gdi32.resolve("RemoveFontMemResourceEx");
-        }
-
-        triedResolve = true;
-    }
-}
-
-void QRawFontPrivate::platformCleanUp()
-{
-    if (fontHandle != NULL) {
-        if (ptrRemoveFontMemResourceEx)
-            ptrRemoveFontMemResourceEx(fontHandle);
-        fontHandle = NULL;
-    }
-}
-
-void QRawFontPrivate::platformLoadFromData(const QByteArray &fontData,
-                                           qreal pixelSize,
-                                           QFont::HintingPreference hintingPreference)
-{
-    EmbeddedFont font(fontData);
-
-#if !defined(QT_NO_DIRECTWRITE)
-    if (hintingPreference == QFont::PreferDefaultHinting
-        || hintingPreference == QFont::PreferFullHinting)
-#endif
-    {
-        GUID guid;
-        CoCreateGuid(&guid);
-
-        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);
-
-        QString actualFontName = font.changeFamilyName(uniqueFamilyName);
-        if (actualFontName.isEmpty()) {
-            qWarning("QRawFont::platformLoadFromData: Can't change family name of font");
-            return;
-        }
-
-        Q_ASSERT(fontHandle == NULL);
-        resolveGdi32();
-        if (ptrAddFontMemResourceEx && ptrRemoveFontMemResourceEx) {
-            DWORD count = 0;
-            QByteArray newFontData = font.data();
-            fontHandle = ptrAddFontMemResourceEx((void *)newFontData.constData(), newFontData.size(),
-                                                 0, &count);
-            if (count == 0 && fontHandle != NULL) {
-                ptrRemoveFontMemResourceEx(fontHandle);
-                fontHandle = NULL;
-            }
-        }
-
-        if (fontHandle == NULL) {
-            qWarning("QRawFont::platformLoadFromData: AddFontMemResourceEx failed");
-        } else {
-            QFontDef request;
-            request.family = uniqueFamilyName;
-            request.pixelSize = pixelSize;
-            request.styleStrategy = QFont::NoFontMerging | QFont::PreferMatch;
-            request.hintingPreference = hintingPreference;
-
-            fontEngine = qt_load_font_engine_win(request);
-            if (request.family != fontEngine->fontDef.family) {
-                qWarning("QRawFont::platformLoadFromData: Failed to load font. "
-                         "Got fallback instead: %s", qPrintable(fontEngine->fontDef.family));
-                if (fontEngine->ref == 0)
-                    delete fontEngine;
-                fontEngine = 0;
-            } else {
-                Q_ASSERT(fontEngine->ref == 0);
-
-                // Override the generated font name
-                static_cast<QFontEngineWin *>(fontEngine)->uniqueFamilyName = uniqueFamilyName;
-                fontEngine->fontDef.family = actualFontName;
-                fontEngine->ref.ref();
-            }
-        }
-    }
-#if !defined(QT_NO_DIRECTWRITE)
-    else {
-        CustomFontFileLoader fontFileLoader;
-        fontFileLoader.addKey(this, fontData);
-
-        IDWriteFactory *factory = NULL;
-        HRESULT hres = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED,
-                                           __uuidof(IDWriteFactory),
-                                           reinterpret_cast<IUnknown **>(&factory));
-        if (FAILED(hres)) {
-            qErrnoWarning(hres, "QRawFont::platformLoadFromData: DWriteCreateFactory failed");
-            return;
-        }
-
-        IDWriteFontFile *fontFile = NULL;
-        void *key = this;
-
-        hres = factory->CreateCustomFontFileReference(&key, sizeof(void *),
-                                                      fontFileLoader.loader(), &fontFile);
-        if (FAILED(hres)) {
-            qErrnoWarning(hres, "QRawFont::platformLoadFromData: "
-                                "CreateCustomFontFileReference failed");
-            factory->Release();
-            return;
-        }
-
-        BOOL isSupportedFontType;
-        DWRITE_FONT_FILE_TYPE fontFileType;
-        DWRITE_FONT_FACE_TYPE fontFaceType;
-        UINT32 numberOfFaces;
-        fontFile->Analyze(&isSupportedFontType, &fontFileType, &fontFaceType, &numberOfFaces);
-        if (!isSupportedFontType) {
-            fontFile->Release();
-            factory->Release();
-            return;
-        }
-
-        IDWriteFontFace *directWriteFontFace = NULL;
-        hres = factory->CreateFontFace(fontFaceType, 1, &fontFile, 0, DWRITE_FONT_SIMULATIONS_NONE,
-                                       &directWriteFontFace);
-        if (FAILED(hres)) {
-            qErrnoWarning(hres, "QRawFont::platformLoadFromData: CreateFontFace failed");
-            fontFile->Release();
-            factory->Release();
-            return;
-        }
-
-        fontFile->Release();
-
-        fontEngine = new QFontEngineDirectWrite(factory, directWriteFontFace, pixelSize);
-
-        // Get font family from font data
-        fontEngine->fontDef.family = font.familyName();
-        fontEngine->ref.ref();
-
-        directWriteFontFace->Release();
-        factory->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()
-                                                       + os2TableEntry->offset);
-
-            bool italic = os2Table->selection & 1;
-            bool oblique = os2Table->selection & 128;
-
-            if (italic)
-                fontEngine->fontDef.style = QFont::StyleItalic;
-            else if (oblique)
-                fontEngine->fontDef.style = QFont::StyleOblique;
-            else
-                fontEngine->fontDef.style = QFont::StyleNormal;
-
-            fontEngine->fontDef.weight = weightFromInteger(os2Table->weightClass);
-        }
-    }
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_RAWFONT
index 2705bd2..f7fef7d 100644 (file)
@@ -886,21 +886,6 @@ void QTextEngine::shapeLine(const QScriptLine &line)
     }
 }
 
-#if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC) && defined(Q_WS_MAC)
-static bool enableHarfBuzz()
-{
-    static enum { Yes, No, Unknown } status = Unknown;
-
-    if (status == Unknown) {
-        QByteArray v = qgetenv("QT_ENABLE_HARFBUZZ");
-        bool value = !v.isEmpty() && v != "0" && v != "false";
-        if (value) status = Yes;
-        else status = No;
-    }
-    return status == Yes;
-}
-#endif
-
 void QTextEngine::shapeText(int item) const
 {
     Q_ASSERT(item < layoutData->items.size());
@@ -909,30 +894,7 @@ void QTextEngine::shapeText(int item) const
     if (si.num_glyphs)
         return;
 
-#if defined(Q_WS_MAC)
-#if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC)
-    if (enableHarfBuzz()) {
-#endif
-        QFontEngine *actualFontEngine = fontEngine(si, &si.ascent, &si.descent, &si.leading);
-        if (actualFontEngine->type() == QFontEngine::Multi)
-            actualFontEngine = static_cast<QFontEngineMulti *>(actualFontEngine)->engine(0);
-
-        HB_Face face = actualFontEngine->harfbuzzFace();
-        HB_Script script = (HB_Script) si.analysis.script;
-        if (face->supported_scripts[script])
-            shapeTextWithHarfbuzz(item);
-        else
-            shapeTextMac(item);
-#if !defined(QT_ENABLE_HARFBUZZ_FOR_MAC)
-    } else {
-        shapeTextMac(item);
-    }
-#endif
-#elif defined(Q_WS_WINCE)
-    shapeTextWithCE(item);
-#else
     shapeTextWithHarfbuzz(item);
-#endif
 
     si.width = 0;
 
diff --git a/src/gui/text/qtextengine_mac.cpp b/src/gui/text/qtextengine_mac.cpp
deleted file mode 100644 (file)
index 0dfadb5..0000000
+++ /dev/null
@@ -1,665 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qtextengine_p.h"
-
-#include <qfontengine_coretext_p.h>
-#include <qfontengine_mac_p.h>
-
-QT_BEGIN_NAMESPACE
-
-// set the glyph attributes heuristically. Assumes a 1 to 1 relationship between chars and glyphs
-// and no reordering.
-// also computes logClusters heuristically
-static void heuristicSetGlyphAttributes(const QChar *uc, int length, QGlyphLayout *glyphs, unsigned short *logClusters, int num_glyphs)
-{
-    // ### zeroWidth and justification are missing here!!!!!
-
-    Q_UNUSED(num_glyphs);
-
-//     qDebug("QScriptEngine::heuristicSetGlyphAttributes, num_glyphs=%d", item->num_glyphs);
-
-    const bool symbolFont = false; // ####
-    glyphs->attributes[0].mark = false;
-    glyphs->attributes[0].clusterStart = true;
-    glyphs->attributes[0].dontPrint = (!symbolFont && uc[0].unicode() == 0x00ad) || qIsControlChar(uc[0].unicode());
-
-    int pos = 0;
-    int lastCat = QChar::category(uc[0].unicode());
-    for (int i = 1; i < length; ++i) {
-        if (logClusters[i] == pos)
-            // same glyph
-            continue;
-        ++pos;
-        while (pos < logClusters[i]) {
-            ++pos;
-        }
-        // hide soft-hyphens by default
-        if ((!symbolFont && uc[i].unicode() == 0x00ad) || qIsControlChar(uc[i].unicode()))
-            glyphs->attributes[pos].dontPrint = true;
-        const QUnicodeTables::Properties *prop = QUnicodeTables::properties(uc[i].unicode());
-        int cat = prop->category;
-
-        // one gets an inter character justification point if the current char is not a non spacing mark.
-        // as then the current char belongs to the last one and one gets a space justification point
-        // after the space char.
-        if (lastCat == QChar::Separator_Space)
-            glyphs->attributes[pos-1].justification = HB_Space;
-        else if (cat != QChar::Mark_NonSpacing)
-            glyphs->attributes[pos-1].justification = HB_Character;
-        else
-            glyphs->attributes[pos-1].justification = HB_NoJustification;
-
-        lastCat = cat;
-    }
-    pos = logClusters[length-1];
-    if (lastCat == QChar::Separator_Space)
-        glyphs->attributes[pos].justification = HB_Space;
-    else
-        glyphs->attributes[pos].justification = HB_Character;
-}
-
-struct QArabicProperties {
-    unsigned char shape;
-    unsigned char justification;
-};
-Q_DECLARE_TYPEINFO(QArabicProperties, Q_PRIMITIVE_TYPE);
-
-enum QArabicShape {
-    XIsolated,
-    XFinal,
-    XInitial,
-    XMedial,
-    // intermediate state
-    XCausing
-};
-
-
-// these groups correspond to the groups defined in the Unicode standard.
-// Some of these groups are equal with regards to both joining and line breaking behaviour,
-// and thus have the same enum value
-//
-// I'm not sure the mapping of syriac to arabic enums is correct with regards to justification, but as
-// I couldn't find any better document I'll hope for the best.
-enum ArabicGroup {
-    // NonJoining
-    ArabicNone,
-    ArabicSpace,
-    // Transparent
-    Transparent,
-    // Causing
-    Center,
-    Kashida,
-
-    // Arabic
-    // Dual
-    Beh,
-    Noon,
-    Meem = Noon,
-    Heh = Noon,
-    KnottedHeh = Noon,
-    HehGoal = Noon,
-    SwashKaf = Noon,
-    Yeh,
-    Hah,
-    Seen,
-    Sad = Seen,
-    Tah,
-    Kaf = Tah,
-    Gaf = Tah,
-    Lam = Tah,
-    Ain,
-    Feh = Ain,
-    Qaf = Ain,
-    // Right
-    Alef,
-    Waw,
-    Dal,
-    TehMarbuta = Dal,
-    Reh,
-    HamzaOnHehGoal,
-    YehWithTail = HamzaOnHehGoal,
-    YehBarre = HamzaOnHehGoal,
-
-    // Syriac
-    // Dual
-    Beth = Beh,
-    Gamal = Ain,
-    Heth = Noon,
-    Teth = Hah,
-    Yudh = Noon,
-    Kaph = Noon,
-    Lamadh = Lam,
-    Mim = Noon,
-    Nun = Noon,
-    Semakh = Noon,
-    FinalSemakh = Noon,
-    SyriacE = Ain,
-    Pe = Ain,
-    ReversedPe = Hah,
-    Qaph = Noon,
-    Shin = Noon,
-    Fe = Ain,
-
-    // Right
-    Alaph = Alef,
-    Dalath = Dal,
-    He = Dal,
-    SyriacWaw = Waw,
-    Zain = Alef,
-    YudhHe = Waw,
-    Sadhe = HamzaOnHehGoal,
-    Taw = Dal,
-
-    // Compiler bug? Otherwise ArabicGroupsEnd would be equal to Dal + 1.
-    Dummy = HamzaOnHehGoal,
-    ArabicGroupsEnd
-};
-
-static const unsigned char arabic_group[0x150] = {
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, Transparent, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
-    ArabicNone, ArabicNone, Alef, Alef,
-    Waw, Alef, Yeh, Alef,
-    Beh, TehMarbuta, Beh, Beh,
-    Hah, Hah, Hah, Dal,
-
-    Dal, Reh, Reh, Seen,
-    Seen, Sad, Sad, Tah,
-    Tah, Ain, Ain, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
-    // 0x640
-    Kashida, Feh, Qaf, Kaf,
-    Lam, Meem, Noon, Heh,
-    Waw, Yeh, Yeh, Transparent,
-    Transparent, Transparent, Transparent, Transparent,
-
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, Beh, Qaf,
-
-    Transparent, Alef, Alef, Alef,
-    ArabicNone, Alef, Waw, Waw,
-    Yeh, Beh, Beh, Beh,
-    Beh, Beh, Beh, Beh,
-
-    // 0x680
-    Beh, Hah, Hah, Hah,
-    Hah, Hah, Hah, Hah,
-    Dal, Dal, Dal, Dal,
-    Dal, Dal, Dal, Dal,
-
-    Dal, Reh, Reh, Reh,
-    Reh, Reh, Reh, Reh,
-    Reh, Reh, Seen, Seen,
-    Seen, Sad, Sad, Tah,
-
-    Ain, Feh, Feh, Feh,
-    Feh, Feh, Feh, Qaf,
-    Qaf, Gaf, SwashKaf, Gaf,
-    Kaf, Kaf, Kaf, Gaf,
-
-    Gaf, Gaf, Gaf, Gaf,
-    Gaf, Lam, Lam, Lam,
-    Lam, Noon, Noon, Noon,
-    Noon, Noon, KnottedHeh, Hah,
-
-    // 0x6c0
-    TehMarbuta, HehGoal, HamzaOnHehGoal, HamzaOnHehGoal,
-    Waw, Waw, Waw, Waw,
-    Waw, Waw, Waw, Waw,
-    Yeh, YehWithTail, Yeh, Waw,
-
-    Yeh, Yeh, YehBarre, YehBarre,
-    ArabicNone, TehMarbuta, Transparent, Transparent,
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, ArabicNone, ArabicNone, Transparent,
-
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, ArabicNone, ArabicNone, Transparent,
-    Transparent, ArabicNone, Transparent, Transparent,
-    Transparent, Transparent, Dal, Reh,
-
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, Seen, Sad,
-    Ain, ArabicNone, ArabicNone, KnottedHeh,
-
-    // 0x700
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-    ArabicNone, ArabicNone, ArabicNone, ArabicNone,
-
-    Alaph, Transparent, Beth, Gamal,
-    Gamal, Dalath, Dalath, He,
-    SyriacWaw, Zain, Heth, Teth,
-    Teth, Yudh, YudhHe, Kaph,
-
-    Lamadh, Mim, Nun, Semakh,
-    FinalSemakh, SyriacE, Pe, ReversedPe,
-    Sadhe, Qaph, Dalath, Shin,
-    Taw, Beth, Gamal, Dalath,
-
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, Transparent, Transparent, Transparent,
-
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, Transparent, Transparent, Transparent,
-    Transparent, Transparent, Transparent, ArabicNone,
-    ArabicNone, Zain, Kaph, Fe,
-};
-
-static inline ArabicGroup arabicGroup(unsigned short uc)
-{
-    if (uc >= 0x0600 && uc < 0x750)
-        return (ArabicGroup) arabic_group[uc-0x600];
-    else if (uc == 0x200d)
-        return Center;
-    else if (QChar::category(uc) == QChar::Separator_Space)
-        return ArabicSpace;
-    else
-        return ArabicNone;
-}
-
-
-/*
-   Arabic shaping obeys a number of rules according to the joining classes (see Unicode book, section on
-   arabic).
-
-   Each unicode char has a joining class (right, dual (left&right), center (joincausing) or transparent).
-   transparent joining is not encoded in QChar::joining(), but applies to all combining marks and format marks.
-
-   Right join-causing: dual + center
-   Left join-causing: dual + right + center
-
-   Rules are as follows (for a string already in visual order, as we have it here):
-
-   R1 Transparent characters do not affect joining behaviour.
-   R2 A right joining character, that has a right join-causing char on the right will get form XRight
-   (R3 A left joining character, that has a left join-causing char on the left will get form XLeft)
-   Note: the above rule is meaningless, as there are no pure left joining characters defined in Unicode
-   R4 A dual joining character, that has a left join-causing char on the left and a right join-causing char on
-             the right will get form XMedial
-   R5  A dual joining character, that has a right join causing char on the right, and no left join causing char on the left
-         will get form XRight
-   R6 A dual joining character, that has a  left join causing char on the left, and no right join causing char on the right
-         will get form XLeft
-   R7 Otherwise the character will get form XIsolated
-
-   Additionally we have to do the minimal ligature support for lam-alef ligatures:
-
-   L1 Transparent characters do not affect ligature behaviour.
-   L2 Any sequence of Alef(XRight) + Lam(XMedial) will form the ligature Alef.Lam(XLeft)
-   L3 Any sequence of Alef(XRight) + Lam(XLeft) will form the ligature Alef.Lam(XIsolated)
-
-   The state table below handles rules R1-R7.
-*/
-
-enum Joining {
-    JNone,
-    JCausing,
-    JDual,
-    JRight,
-    JTransparent
-};
-
-static const Joining joining_for_group[ArabicGroupsEnd] = {
-    // NonJoining
-    JNone, // ArabicNone
-    JNone, // ArabicSpace
-    // Transparent
-    JTransparent, // Transparent
-    // Causing
-    JCausing, // Center
-    JCausing, // Kashida
-    // Dual
-    JDual, // Beh
-    JDual, // Noon
-    JDual, // Yeh
-    JDual, // Hah
-    JDual, // Seen
-    JDual, // Tah
-    JDual, // Ain
-    // Right
-    JRight, // Alef
-    JRight, // Waw
-    JRight, // Dal
-    JRight, // Reh
-    JRight  // HamzaOnHehGoal
-};
-
-
-struct JoiningPair {
-    QArabicShape form1;
-    QArabicShape form2;
-};
-
-static const JoiningPair joining_table[5][4] =
-// None, Causing, Dual, Right
-{
-    { { XIsolated, XIsolated }, { XIsolated, XCausing }, { XIsolated, XInitial }, { XIsolated, XIsolated } }, // XIsolated
-    { { XFinal, XIsolated }, { XFinal, XCausing }, { XFinal, XInitial }, { XFinal, XIsolated } }, // XFinal
-    { { XIsolated, XIsolated }, { XInitial, XCausing }, { XInitial, XMedial }, { XInitial, XFinal } }, // XInitial
-    { { XFinal, XIsolated }, { XMedial, XCausing }, { XMedial, XMedial }, { XMedial, XFinal } }, // XMedial
-    { { XIsolated, XIsolated }, { XIsolated, XCausing }, { XIsolated, XMedial }, { XIsolated, XFinal } }, // XCausing
-};
-
-
-/*
-According to http://www.microsoft.com/middleeast/Arabicdev/IE6/KBase.asp
-
-1. Find the priority of the connecting opportunities in each word
-2. Add expansion at the highest priority connection opportunity
-3. If more than one connection opportunity have the same highest value,
-   use the opportunity closest to the end of the word.
-
-Following is a chart that provides the priority for connection
-opportunities and where expansion occurs. The character group names
-are those in table 6.6 of the UNICODE 2.0 book.
-
-
-PrioritY        Glyph                   Condition                                       Kashida Location
-
-Arabic_Kashida        User inserted Kashida   The user entered a Kashida in a position.       After the user
-                (Shift+j or Shift+[E with hat])    Thus, it is the highest priority to insert an   inserted kashida
-                                        automatic kashida.
-
-Arabic_Seen        Seen, Sad               Connecting to the next character.               After the character.
-                                        (Initial or medial form).
-
-Arabic_HaaDal        Teh Marbutah, Haa, Dal  Connecting to previous character.               Before the final form
-                                                                                        of these characters.
-
-Arabic_Alef     Alef, Tah, Lam,         Connecting to previous character.               Before the final form
-                Kaf and Gaf                                                             of these characters.
-
-Arabic_BaRa     Reh, Yeh                Connected to medial Beh                         Before preceding medial Baa
-
-Arabic_Waw        Waw, Ain, Qaf, Feh      Connecting to previous character.               Before the final form of
-                                                                                        these characters.
-
-Arabic_Normal   Other connecting        Connecting to previous character.               Before the final form
-                characters                                                              of these characters.
-
-
-
-This seems to imply that we have at most one kashida point per arabic word.
-
-*/
-
-void qt_getArabicProperties(const unsigned short *chars, int len, QArabicProperties *properties)
-{
-//     qDebug("arabicSyriacOpenTypeShape: properties:");
-    int lastPos = 0;
-    int lastGroup = ArabicNone;
-
-    ArabicGroup group = arabicGroup(chars[0]);
-    Joining j = joining_for_group[group];
-    QArabicShape shape = joining_table[XIsolated][j].form2;
-    properties[0].justification = HB_NoJustification;
-
-    for (int i = 1; i < len; ++i) {
-        // #### fix handling for spaces and punktuation
-        properties[i].justification = HB_NoJustification;
-
-        group = arabicGroup(chars[i]);
-        j = joining_for_group[group];
-
-        if (j == JTransparent) {
-            properties[i].shape = XIsolated;
-            continue;
-        }
-
-        properties[lastPos].shape = joining_table[shape][j].form1;
-        shape = joining_table[shape][j].form2;
-
-        switch(lastGroup) {
-        case Seen:
-            if (properties[lastPos].shape == XInitial || properties[lastPos].shape == XMedial)
-                properties[i-1].justification = HB_Arabic_Seen;
-            break;
-        case Hah:
-            if (properties[lastPos].shape == XFinal)
-                properties[lastPos-1].justification = HB_Arabic_HaaDal;
-            break;
-        case Alef:
-            if (properties[lastPos].shape == XFinal)
-                properties[lastPos-1].justification = HB_Arabic_Alef;
-            break;
-        case Ain:
-            if (properties[lastPos].shape == XFinal)
-                properties[lastPos-1].justification = HB_Arabic_Waw;
-            break;
-        case Noon:
-            if (properties[lastPos].shape == XFinal)
-                properties[lastPos-1].justification = HB_Arabic_Normal;
-            break;
-        case ArabicNone:
-            break;
-
-        default:
-            Q_ASSERT(false);
-        }
-
-        lastGroup = ArabicNone;
-
-        switch(group) {
-        case ArabicNone:
-        case Transparent:
-        // ### Center should probably be treated as transparent when it comes to justification.
-        case Center:
-            break;
-        case ArabicSpace:
-            properties[i].justification = HB_Arabic_Space;
-            break;
-        case Kashida:
-            properties[i].justification = HB_Arabic_Kashida;
-            break;
-        case Seen:
-            lastGroup = Seen;
-            break;
-
-        case Hah:
-        case Dal:
-            lastGroup = Hah;
-            break;
-
-        case Alef:
-        case Tah:
-            lastGroup = Alef;
-            break;
-
-        case Yeh:
-        case Reh:
-            if (properties[lastPos].shape == XMedial && arabicGroup(chars[lastPos]) == Beh)
-                properties[lastPos-1].justification = HB_Arabic_BaRa;
-            break;
-
-        case Ain:
-        case Waw:
-            lastGroup = Ain;
-            break;
-
-        case Noon:
-        case Beh:
-        case HamzaOnHehGoal:
-            lastGroup = Noon;
-            break;
-        case ArabicGroupsEnd:
-            Q_ASSERT(false);
-        }
-
-        lastPos = i;
-    }
-    properties[lastPos].shape = joining_table[shape][JNone].form1;
-
-
-//     for (int i = 0; i < len; ++i)
-//         qDebug("arabic properties(%d): uc=%x shape=%d, justification=%d", i, chars[i], properties[i].shape, properties[i].justification);
-}
-
-void QTextEngine::shapeTextMac(int item) const
-{
-    QScriptItem &si = layoutData->items[item];
-
-    si.glyph_data_offset = layoutData->used;
-
-    QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading);
-    if (font->type() != QFontEngine::Multi) {
-        shapeTextWithHarfbuzz(item);
-        return;
-    }
-    
-#ifndef QT_MAC_USE_COCOA
-    QFontEngineMacMulti *fe = static_cast<QFontEngineMacMulti *>(font);
-#else
-    QCoreTextFontEngineMulti *fe = static_cast<QCoreTextFontEngineMulti *>(font);
-#endif
-    QTextEngine::ShaperFlags flags;
-    if (si.analysis.bidiLevel % 2)
-        flags |= RightToLeft;
-    if (option.useDesignMetrics())
-       flags |= DesignMetrics;
-
-    attributes(); // pre-initialize char attributes
-
-    const int len = length(item);
-    int num_glyphs = length(item);
-    const QChar *str = layoutData->string.unicode() + si.position;
-    ushort upperCased[256];
-    if (si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
-            || si.analysis.flags == QScriptAnalysis::Lowercase) {
-        ushort *uc = upperCased;
-        if (len > 256)
-            uc = new ushort[len];
-        for (int i = 0; i < len; ++i) {
-            if(si.analysis.flags == QScriptAnalysis::Lowercase)
-                uc[i] = str[i].toLower().unicode();
-            else
-                uc[i] = str[i].toUpper().unicode();
-        }
-        str = reinterpret_cast<const QChar *>(uc);
-    }
-
-    ensureSpace(num_glyphs);
-    num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used;
-
-    QGlyphLayout g = availableGlyphs(&si);
-    g.numGlyphs = num_glyphs;
-    unsigned short *log_clusters = logClusters(&si);
-
-    bool stringToCMapFailed = false;
-    // Skip shaping of line or paragraph separators since we are not
-    // going to draw them anyway
-    if (si.analysis.flags == QScriptAnalysis::LineOrParagraphSeparator
-        && !(option.flags() & QTextOption::ShowLineAndParagraphSeparators)) {
-        memset(log_clusters, 0, len * sizeof(unsigned short));
-        goto cleanUp;
-    }
-
-    if (!fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters, attributes(), &si)) {
-        ensureSpace(num_glyphs);
-        g = availableGlyphs(&si);
-        stringToCMapFailed = !fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters,
-                                               attributes(), &si);
-    }
-
-    if (!stringToCMapFailed) {
-        heuristicSetGlyphAttributes(str, len, &g, log_clusters, num_glyphs);
-
-        si.num_glyphs = num_glyphs;
-
-        layoutData->used += si.num_glyphs;
-
-        QGlyphLayout g = shapedGlyphs(&si);
-
-        if (si.analysis.script == QUnicodeTables::Arabic) {
-            QVarLengthArray<QArabicProperties> props(len + 2);
-            QArabicProperties *properties = props.data();
-            int f = si.position;
-            int l = len;
-            if (f > 0) {
-                --f;
-                ++l;
-                ++properties;
-            }
-            if (f + l < layoutData->string.length()) {
-                ++l;
-            }
-            qt_getArabicProperties((const unsigned short *)(layoutData->string.unicode()+f), l, props.data());
-
-            unsigned short *log_clusters = logClusters(&si);
-
-            for (int i = 0; i < len; ++i) {
-                int gpos = log_clusters[i];
-                g.attributes[gpos].justification = properties[i].justification;
-            }
-        }
-    }
-
-cleanUp:
-    const ushort *uc = reinterpret_cast<const ushort *>(str);
-
-    if ((si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase
-         || si.analysis.flags == QScriptAnalysis::Lowercase)
-        && uc != upperCased)
-        delete [] uc;
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/util/qdesktopservices_blackberry.cpp b/src/gui/util/qdesktopservices_blackberry.cpp
deleted file mode 100644 (file)
index abaa71a..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2011 - 2012 Research In Motion <blackberry-qt@qnx.com>
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtCore 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QT_NO_DESKTOPSERVICES
-
-#include <qurl.h>
-#include <bps/navigator.h>
-#include <qdir.h>
-
-QT_BEGIN_NAMESPACE
-
-static bool navigatorInvoke(const QUrl &url)
-{
-    if (!url.isValid() || url.isRelative())
-        return false;
-
-    int ret = navigator_invoke(url.toString().toUtf8(), 0);
-
-    return (ret == BPS_SUCCESS);
-}
-
-static bool launchWebBrowser(const QUrl &url)
-{
-    return navigatorInvoke(url);
-}
-
-static bool openDocument(const QUrl &file)
-{
-    return navigatorInvoke(file);
-}
-
-QString QDesktopServices::storageLocation(StandardLocation type)
-{
-    if (type == QDesktopServices::TempLocation)
-        return QDir::tempPath();
-    if (type == QDesktopServices::CacheLocation)
-        return QDir::homePath() + QLatin1String("/Cache");
-
-    QString path;
-
-    const int index = QDir::homePath().lastIndexOf("/data");
-
-    const QString sharedRoot = QDir::homePath().replace(index,
-            QDir::homePath().length() - index, "/shared");
-
-    switch (type) {
-    case DataLocation:
-    case DesktopLocation:
-    case HomeLocation:
-        path = QDir::homePath();
-        break;
-    case DocumentsLocation:
-        path = sharedRoot + QLatin1String("/documents");
-       break;
-    case PicturesLocation:
-        path = sharedRoot + QLatin1String("/photos");
-        break;
-    case MusicLocation:
-        path = sharedRoot + QLatin1String("/music");
-        break;
-    case MoviesLocation:
-        path = sharedRoot + QLatin1String("/videos");
-        break;
-    default:
-        break;
-    }
-
-    return path;
-}
-
-QString QDesktopServices::displayName(StandardLocation type)
-{
-    return storageLocation(type);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DESKTOPSERVICES
diff --git a/src/gui/util/qdesktopservices_mac.cpp b/src/gui/util/qdesktopservices_mac.cpp
deleted file mode 100644 (file)
index edaeb00..0000000
+++ /dev/null
@@ -1,188 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QT_NO_DESKTOPSERVICES
-
-#include <qprocess.h>
-#include <qstringlist.h>
-#include <qdir.h>
-#include <qurl.h>
-#include <qstringlist.h>
-#include <qcore_mac_p.h>
-#include <qcoreapplication.h>
-
-#include <ApplicationServices/ApplicationServices.h>
-
-QT_BEGIN_NAMESPACE
-
-/*
-    Translates a QDesktopServices::StandardLocation into the mac equivalent.
-*/
-OSType translateLocation(QDesktopServices::StandardLocation type)
-{
-    switch (type) {
-    case QDesktopServices::DesktopLocation:
-        return kDesktopFolderType; break;
-
-    case QDesktopServices::DocumentsLocation:
-        return kDocumentsFolderType; break;
-
-    case QDesktopServices::FontsLocation:
-        // There are at least two different font directories on the mac: /Library/Fonts and ~/Library/Fonts.
-        // To select a specific one we have to specify a different first parameter when calling FSFindFolder.
-        return kFontsFolderType; break;
-
-    case QDesktopServices::ApplicationsLocation:
-        return kApplicationsFolderType; break;
-
-    case QDesktopServices::MusicLocation:
-        return kMusicDocumentsFolderType; break;
-
-    case QDesktopServices::MoviesLocation:
-        return kMovieDocumentsFolderType; break;
-
-    case QDesktopServices::PicturesLocation:
-        return kPictureDocumentsFolderType; break;
-
-    case QDesktopServices::TempLocation:
-        return kTemporaryFolderType; break;
-
-    case QDesktopServices::DataLocation:
-        return kApplicationSupportFolderType; break;
-
-    case QDesktopServices::CacheLocation:
-        return kCachedDataFolderType; break;
-
-    default:
-        return kDesktopFolderType; break;
-    }
-}
-
-static bool lsOpen(const QUrl &url)
-{
-    if (!url.isValid() || url.scheme().isEmpty())
-        return false;
-
-    QCFType<CFURLRef> cfUrl = CFURLCreateWithString(0, QCFString(QString::fromLatin1(url.toEncoded())), 0);
-    if (cfUrl == 0)
-        return false;
-
-    const OSStatus err = LSOpenCFURLRef(cfUrl, 0);
-    return (err == noErr);
-}
-
-static bool launchWebBrowser(const QUrl &url)
-{
-    return lsOpen(url);
-}
-
-static bool openDocument(const QUrl &file)
-{
-    if (!file.isValid())
-        return false;
-
-   // LSOpen does not work in this case, use QProcess open instead.
-   return QProcess::startDetached(QLatin1String("open"), QStringList() << file.toLocalFile());
-}
-
-/*
-    Constructs a full unicode path from a FSRef.
-*/
-static QString getFullPath(const FSRef &ref)
-{
-    QByteArray ba(2048, 0);
-    if (FSRefMakePath(&ref, reinterpret_cast<UInt8 *>(ba.data()), ba.size()) == noErr)
-        return QString::fromUtf8(ba).normalized(QString::NormalizationForm_C);
-    return QString();
-}
-
-QString QDesktopServices::storageLocation(StandardLocation type)
-{
-     if (type == HomeLocation)
-        return QDir::homePath();
-
-     if (type == TempLocation)
-         return QDir::tempPath();
-
-    short domain = kOnAppropriateDisk;
-
-    if (type == DataLocation || type == CacheLocation)
-        domain = kUserDomain;
-
-     // http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/Reference/reference.html
-     FSRef ref;
-     OSErr err = FSFindFolder(domain, translateLocation(type), false, &ref);
-     if (err)
-        return QString();
-
-    QString path = getFullPath(ref);
-
-    if (type == DataLocation || type == CacheLocation) {
-        if (QCoreApplication::organizationName().isEmpty() == false)
-            path += QLatin1Char('/') + QCoreApplication::organizationName();
-        if (QCoreApplication::applicationName().isEmpty() == false)
-            path += QLatin1Char('/') + QCoreApplication::applicationName();
-    }
-
-    return path;
-}
-
-QString QDesktopServices::displayName(StandardLocation type)
-{
-    if (QDesktopServices::HomeLocation == type)
-        return QObject::tr("Home");
-
-    FSRef ref;
-    OSErr err = FSFindFolder(kOnAppropriateDisk, translateLocation(type), false, &ref);
-    if (err)
-        return QString();
-
-    QCFString displayName;
-    err = LSCopyDisplayNameForRef(&ref, &displayName);
-    if (err)
-        return QString();
-
-    return static_cast<QString>(displayName);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DESKTOPSERVICES
diff --git a/src/gui/util/qdesktopservices_win.cpp b/src/gui/util/qdesktopservices_win.cpp
deleted file mode 100644 (file)
index 1cab8c1..0000000
+++ /dev/null
@@ -1,272 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qsettings.h>
-#include <qdir.h>
-#include <qsystemlibrary_p.h>
-#include <qurl.h>
-#include <qstringlist.h>
-#include <qprocess.h>
-#include <qtemporaryfile.h>
-#include <qcoreapplication.h>
-
-#include <qt_windows.h>
-#include <shlobj.h>
-#if !defined(Q_OS_WINCE)
-#  include <intshcut.h>
-#else
-#  include <qguifunctions_wince.h>
-#endif
-
-#ifndef CSIDL_MYMUSIC
-#define CSIDL_MYMUSIC  13
-#define CSIDL_MYVIDEO  14
-#endif
-
-#ifndef QT_NO_DESKTOPSERVICES
-
-QT_BEGIN_NAMESPACE
-
-static inline bool shellExecute(const QUrl &url)
-{
-#ifndef Q_OS_WINCE
-    if (!url.isValid())
-        return false;
-
-    const QString nativeFilePath =
-            url.isLocalFile() ? QDir::toNativeSeparators(url.toLocalFile()) : url.toString();
-    const quintptr result = (quintptr)ShellExecute(0, 0, (wchar_t*)nativeFilePath.utf16(), 0, 0, SW_SHOWNORMAL);
-    // ShellExecute returns a value greater than 32 if successful
-    if (result <= 32) {
-        qWarning("ShellExecute '%s' failed (error %s).", qPrintable(url.toString()), qPrintable(QString::number(result)));
-        return false;
-    }
-    return true;
-#else
-    Q_UNUSED(url);
-    return false;
-#endif
-}
-
-static bool openDocument(const QUrl &file)
-{
-    return shellExecute(file);
-}
-
-static QString expandEnvStrings(const QString &command)
-{
-#if defined(Q_OS_WINCE)
-    return command;
-#else
-    wchar_t buffer[MAX_PATH];
-    if (ExpandEnvironmentStrings((wchar_t*)command.utf16(), buffer, MAX_PATH))
-        return QString::fromWCharArray(buffer);
-    else
-        return command;
-#endif
-}
-
-static bool launchWebBrowser(const QUrl &url)
-{
-    if (url.scheme() == QLatin1String("mailto")) {
-        //Retrieve the commandline for the default mail client
-        //the default key used below is the command line for the mailto: shell command
-        DWORD  bufferSize = sizeof(wchar_t) * MAX_PATH;
-        long  returnValue =  -1;
-        QString command;
-
-        HKEY handle;
-        LONG res;
-        wchar_t keyValue[MAX_PATH] = {0};
-        QString keyName(QLatin1String("mailto"));
-
-        //Check if user has set preference, otherwise use default.
-        res = RegOpenKeyEx(HKEY_CURRENT_USER,
-                           L"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\mailto\\UserChoice",
-                           0, KEY_READ, &handle);
-        if (res == ERROR_SUCCESS) {
-            returnValue = RegQueryValueEx(handle, L"Progid", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize);
-            if (!returnValue)
-                keyName = QString::fromUtf16((const ushort*)keyValue);
-            RegCloseKey(handle);
-        }
-        keyName += QLatin1String("\\Shell\\Open\\Command");
-        res = RegOpenKeyExW(HKEY_CLASSES_ROOT, (const wchar_t*)keyName.utf16(), 0, KEY_READ, &handle);
-        if (res != ERROR_SUCCESS)
-            return false;
-
-        bufferSize = sizeof(wchar_t) * MAX_PATH;
-        returnValue = RegQueryValueEx(handle, L"", 0, 0, reinterpret_cast<unsigned char*>(keyValue), &bufferSize);
-        if (!returnValue)
-            command = QString::fromRawData((QChar*)keyValue, bufferSize);
-        RegCloseKey(handle);
-
-        if (returnValue)
-            return false;
-
-        command = expandEnvStrings(command);
-        command = command.trimmed();
-        //Make sure the path for the process is in quotes
-        int index = -1 ;
-        if (command[0]!= QLatin1Char('\"')) {
-            index = command.indexOf(QLatin1String(".exe "), 0, Qt::CaseInsensitive);
-            command.insert(index+4, QLatin1Char('\"'));
-            command.insert(0, QLatin1Char('\"'));
-        }
-        //pass the url as the parameter
-        index =  command.lastIndexOf(QLatin1String("%1"));
-        if (index != -1){
-            command.replace(index, 2, url.toString());
-        }
-        //start the process
-        PROCESS_INFORMATION pi;
-        ZeroMemory(&pi, sizeof(pi));
-        STARTUPINFO si;
-        ZeroMemory(&si, sizeof(si));
-        si.cb = sizeof(si);
-
-        returnValue = CreateProcess(NULL, (wchar_t*)command.utf16(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
-
-        if (!returnValue)
-            return false;
-
-        CloseHandle(pi.hProcess);
-        CloseHandle(pi.hThread);
-        return true;
-    }
-
-    return shellExecute(url);
-}
-
-QString QDesktopServices::storageLocation(StandardLocation type)
-{
-    QString result;
-
-#ifndef Q_OS_WINCE
-        QSystemLibrary library(QLatin1String("shell32"));
-#else
-        QSystemLibrary library(QLatin1String("coredll"));
-#endif // Q_OS_WINCE
-    typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPWSTR, int, BOOL);
-    static GetSpecialFolderPath SHGetSpecialFolderPath =
-            (GetSpecialFolderPath)library.resolve("SHGetSpecialFolderPathW");
-    if (!SHGetSpecialFolderPath)
-        return QString();
-
-    wchar_t path[MAX_PATH];
-
-    switch (type) {
-    case DataLocation:
-#if defined Q_WS_WINCE
-        if (SHGetSpecialFolderPath(0, path, CSIDL_APPDATA, FALSE)) {
-#else
-        if (SHGetSpecialFolderPath(0, path, CSIDL_LOCAL_APPDATA, FALSE)) {
-#endif
-            result = QString::fromWCharArray(path);
-            if (!QCoreApplication::organizationName().isEmpty())
-                result += QLatin1String("\\") + QCoreApplication::organizationName();
-            if (!QCoreApplication::applicationName().isEmpty())
-                result += QLatin1String("\\") + QCoreApplication::applicationName();
-        }
-        break;
-
-    case DesktopLocation:
-        if (SHGetSpecialFolderPath(0, path, CSIDL_DESKTOPDIRECTORY, FALSE))
-            result = QString::fromWCharArray(path);
-        break;
-
-    case DocumentsLocation:
-        if (SHGetSpecialFolderPath(0, path, CSIDL_PERSONAL, FALSE))
-            result = QString::fromWCharArray(path);
-        break;
-
-    case FontsLocation:
-        if (SHGetSpecialFolderPath(0, path, CSIDL_FONTS, FALSE))
-            result = QString::fromWCharArray(path);
-        break;
-
-    case ApplicationsLocation:
-        if (SHGetSpecialFolderPath(0, path, CSIDL_PROGRAMS, FALSE))
-            result = QString::fromWCharArray(path);
-        break;
-
-    case MusicLocation:
-        if (SHGetSpecialFolderPath(0, path, CSIDL_MYMUSIC, FALSE))
-            result = QString::fromWCharArray(path);
-        break;
-
-    case MoviesLocation:
-        if (SHGetSpecialFolderPath(0, path, CSIDL_MYVIDEO, FALSE))
-            result = QString::fromWCharArray(path);
-        break;
-
-    case PicturesLocation:
-        if (SHGetSpecialFolderPath(0, path, CSIDL_MYPICTURES, FALSE))
-            result = QString::fromWCharArray(path);
-        break;
-
-    case CacheLocation:
-        // Although Microsoft has a Cache key it is a pointer to IE's cache, not a cache
-        // location for everyone.  Most applications seem to be using a
-        // cache directory located in their AppData directory
-        return storageLocation(DataLocation) + QLatin1String("\\cache");
-
-    case QDesktopServices::HomeLocation:
-        return QDir::homePath(); break;
-
-    case QDesktopServices::TempLocation:
-        return QDir::tempPath(); break;
-
-    default:
-        break;
-    }
-    return result;
-}
-
-QString QDesktopServices::displayName(StandardLocation type)
-{
-    Q_UNUSED(type);
-    return QString();
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_DESKTOPSERVICES
diff --git a/src/gui/util/qsystemtrayicon_mac.mm b/src/gui/util/qsystemtrayicon_mac.mm
deleted file mode 100644 (file)
index 19131e2..0000000
+++ /dev/null
@@ -1,626 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/****************************************************************************
-**
-** Copyright (c) 2007-2008, Apple, Inc.
-**
-** All rights reserved.
-**
-** Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are met:
-**
-**   * Redistributions of source code must retain the above copyright notice,
-**     this list of conditions and the following disclaimer.
-**
-**   * Redistributions in binary form must reproduce the above copyright notice,
-**     this list of conditions and the following disclaimer in the documentation
-**     and/or other materials provided with the distribution.
-**
-**   * Neither the name of Apple, Inc. nor the names of its contributors
-**     may be used to endorse or promote products derived from this software
-**     without specific prior written permission.
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-**
-****************************************************************************/
-
-#define QT_MAC_SYSTEMTRAY_USE_GROWL
-
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qsystemtrayicon_p.h>
-#include <qtemporaryfile.h>
-#include <qimagewriter.h>
-#include <qapplication.h>
-#include <qdebug.h>
-#include <qstyle.h>
-
-#include <qt_mac_p.h>
-#import <AppKit/AppKit.h>
-
-QT_BEGIN_NAMESPACE
-extern bool qt_mac_execute_apple_script(const QString &script, AEDesc *ret); //qapplication_mac.cpp
-extern void qtsystray_sendActivated(QSystemTrayIcon *i, int r); //qsystemtrayicon.cpp
-extern NSString *keySequenceToKeyEqivalent(const QKeySequence &accel); // qmenu_mac.mm
-extern NSUInteger keySequenceModifierMask(const QKeySequence &accel);  // qmenu_mac.mm
-extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum);
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-@class QT_MANGLE_NAMESPACE(QNSMenu);
-@class QT_MANGLE_NAMESPACE(QNSImageView);
-
-@interface QT_MANGLE_NAMESPACE(QNSStatusItem) : NSObject
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
-    <NSUserNotificationCenterDelegate>
-#endif
-{
-    NSStatusItem *item;
-    QSystemTrayIcon *icon;
-    QSystemTrayIconPrivate *iconPrivate;
-    QT_MANGLE_NAMESPACE(QNSImageView) *imageCell;
-}
--(id)initWithIcon:(QSystemTrayIcon*)icon iconPrivate:(QSystemTrayIconPrivate *)iprivate;
--(void)dealloc;
--(QSystemTrayIcon*)icon;
--(NSStatusItem*)item;
--(QRectF)geometry;
-- (void)triggerSelector:(id)sender button:(Qt::MouseButton)mouseButton;
-- (void)doubleClickSelector:(id)sender;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
-- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification;
-- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification;
-#endif
-@end
-
-@interface QT_MANGLE_NAMESPACE(QNSImageView) : NSImageView {
-    BOOL down;
-    QT_MANGLE_NAMESPACE(QNSStatusItem) *parent;
-}
--(id)initWithParent:(QT_MANGLE_NAMESPACE(QNSStatusItem)*)myParent;
--(QSystemTrayIcon*)icon;
--(void)menuTrackingDone:(NSNotification*)notification;
--(void)mousePressed:(NSEvent *)mouseEvent button:(Qt::MouseButton)mouseButton;
-@end
-
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-
-@protocol NSMenuDelegate <NSObject>
--(void)menuNeedsUpdate:(NSMenu*)menu;
-@end
-#endif
-
-
-@interface QT_MANGLE_NAMESPACE(QNSMenu) : NSMenu <NSMenuDelegate> {
-    QMenu *qmenu;
-}
--(QMenu*)menu;
--(id)initWithQMenu:(QMenu*)qmenu;
--(void)selectedAction:(id)item;
-@end
-
-QT_BEGIN_NAMESPACE
-class QSystemTrayIconSys
-{
-public:
-    QSystemTrayIconSys(QSystemTrayIcon *icon, QSystemTrayIconPrivate *d) {
-        QMacCocoaAutoReleasePool pool;
-        item = [[QT_MANGLE_NAMESPACE(QNSStatusItem) alloc] initWithIcon:icon iconPrivate:d];
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
-        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_8) {
-            [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:item];
-        }
-#endif
-    }
-    ~QSystemTrayIconSys() {
-        QMacCocoaAutoReleasePool pool;
-        [[[item item] view] setHidden: YES];
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
-        if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_8) {
-            [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:nil];
-        }
-#endif
-        [item release];
-    }
-
-    void emitMessageClicked() {
-        emit [item icon]->messageClicked();
-    }
-
-    QT_MANGLE_NAMESPACE(QNSStatusItem) *item;
-};
-
-void QSystemTrayIconPrivate::install_sys()
-{
-    Q_Q(QSystemTrayIcon);
-    if (!sys) {
-        sys = new QSystemTrayIconSys(q, this);
-        updateIcon_sys();
-        updateMenu_sys();
-        updateToolTip_sys();
-    }
-}
-
-QRect QSystemTrayIconPrivate::geometry_sys() const
-{
-    if(sys) {
-        const QRectF geom = [sys->item geometry];
-        if(!geom.isNull())
-            return geom.toRect();
-    }
-    return QRect();
-}
-
-void QSystemTrayIconPrivate::remove_sys()
-{
-    delete sys;
-    sys = 0;
-}
-
-void QSystemTrayIconPrivate::updateIcon_sys()
-{
-    if(sys && !icon.isNull()) {
-        QMacCocoaAutoReleasePool pool;
-#ifndef QT_MAC_USE_COCOA
-        const short scale = GetMBarHeight()-4;
-#else
-        CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
-        const short scale = hgt - 4;
-#endif
-        NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(icon.pixmap(QSize(scale, scale))));
-        [(NSImageView*)[[sys->item item] view] setImage: nsimage];
-        [nsimage release];
-    }
-}
-
-void QSystemTrayIconPrivate::updateMenu_sys()
-{
-    if(sys) {
-        QMacCocoaAutoReleasePool pool;
-        if(menu && !menu->isEmpty()) {
-            [[sys->item item] setHighlightMode:YES];
-        } else {
-            [[sys->item item] setHighlightMode:NO];
-        }
-    }
-}
-
-void QSystemTrayIconPrivate::updateToolTip_sys()
-{
-    if(sys) {
-        QMacCocoaAutoReleasePool pool;
-        QCFString string(toolTip);
-        [[[sys->item item] view] setToolTip:(NSString*)static_cast<CFStringRef>(string)];
-    }
-}
-
-bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
-{
-    return true;
-}
-
-bool QSystemTrayIconPrivate::supportsMessages_sys()
-{
-    return true;
-}
-
-void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon icon, int)
-{
-    if (!sys)
-        return;
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
-    if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_8) {
-        NSUserNotification *notification = [[NSUserNotification alloc] init];
-        notification.title = [NSString stringWithUTF8String:title.toUtf8().data()];
-        notification.informativeText = [NSString stringWithUTF8String:message.toUtf8().data()];
-
-        [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
-
-        return;
-    }
-#endif
-
-#ifdef QT_MAC_SYSTEMTRAY_USE_GROWL
-    // Make sure that we have Growl installed on the machine we are running on.
-    QCFType<CFURLRef> cfurl;
-    OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator,
-                                              CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
-    if (status == kLSApplicationNotFoundErr)
-        return;
-    QCFType<CFBundleRef> bundle = CFBundleCreate(0, cfurl);
-
-    if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"),
-                kCFCompareCaseInsensitive |  kCFCompareBackwards) != kCFCompareEqualTo)
-        return;
-
-    QPixmap notificationIconPixmap;
-    if (icon == QSystemTrayIcon::Information)
-        notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxInformation);
-    else if (icon == QSystemTrayIcon::Warning)
-        notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxWarning);
-    else if (icon == QSystemTrayIcon::Critical)
-        notificationIconPixmap = QApplication::style()->standardPixmap(QStyle::SP_MessageBoxCritical);
-
-    QTemporaryFile notificationIconFile;
-    QString notificationType(QLatin1String("Notification")), notificationIcon, notificationApp(QApplication::applicationName());
-    if (notificationApp.isEmpty())
-        notificationApp = QLatin1String("Application");
-    if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
-        QImageWriter writer(&notificationIconFile, "PNG");
-        if (writer.write(notificationIconPixmap.toImage()))
-            notificationIcon = QLatin1String("image from location \"file://") + notificationIconFile.fileName() + QLatin1String("\"");
-    }
-    const QString script(QLatin1String(
-        "tell application \"System Events\"\n"
-        "set isRunning to (count of (every process whose bundle identifier is \"com.Growl.GrowlHelperApp\")) > 0\n"
-        "end tell\n"
-        "if isRunning\n"
-        "tell application id \"com.Growl.GrowlHelperApp\"\n"
-        "-- Make a list of all the notification types (all)\n"
-        "set the allNotificationsList to {\"") + notificationType + QLatin1String("\"}\n"
-
-        "-- Make a list of the notifications (enabled)\n"
-        "set the enabledNotificationsList to {\"") + notificationType + QLatin1String("\"}\n"
-
-        "-- Register our script with growl.\n"
-        "register as application \"") + notificationApp + QLatin1String("\" all notifications allNotificationsList default notifications enabledNotificationsList\n"
-
-        "-- Send a Notification...\n") +
-        QLatin1String("notify with name \"") + notificationType +
-        QLatin1String("\" title \"") + title +
-        QLatin1String("\" description \"") + message +
-        QLatin1String("\" application name \"") + notificationApp +
-        QLatin1String("\" ")  + notificationIcon +
-        QLatin1String("\nend tell\nend if"));
-    qt_mac_execute_apple_script(script, 0);
-#else
-    Q_UNUSED(icon);
-    Q_UNUSED(title);
-    Q_UNUSED(message);
-#endif
-
-}
-QT_END_NAMESPACE
-
-@implementation NSStatusItem (Qt)
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSImageView)
--(id)initWithParent:(QT_MANGLE_NAMESPACE(QNSStatusItem)*)myParent {
-    self = [super init];
-    parent = myParent;
-    down = NO;
-    return self;
-}
-
--(QSystemTrayIcon*)icon {
-    return [parent icon];
-}
-
--(void)menuTrackingDone:(NSNotification*)notification
-{
-    Q_UNUSED(notification);
-    down = NO;
-
-    if( ![self icon]->icon().isNull() ) {
-#ifndef QT_MAC_USE_COCOA
-        const short scale = GetMBarHeight()-4;
-#else
-        CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
-        const short scale = hgt - 4;
-#endif
-        NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage([self icon]->icon().pixmap(QSize(scale, scale))));
-        [self setImage: nsimage];
-        [nsimage release];
-    }
-
-    if([self icon]->contextMenu())
-        [self icon]->contextMenu()->hide();
-
-    [self setNeedsDisplay:YES];
-}
-
--(void)mousePressed:(NSEvent *)mouseEvent button:(Qt::MouseButton)mouseButton
-{
-    down = YES;
-    int clickCount = [mouseEvent clickCount];  
-    [self setNeedsDisplay:YES];
-
-#ifndef QT_MAC_USE_COCOA
-    const short scale = GetMBarHeight()-4;
-#else
-    CGFloat hgt = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
-    const short scale = hgt - 4;
-#endif
-
-    if (![self icon]->icon().isNull() ) {
-        NSImage *nsaltimage = static_cast<NSImage *>(qt_mac_create_nsimage([self icon]->icon().pixmap(QSize(scale, scale), QIcon::Selected)));
-        [self setImage: nsaltimage];
-        [nsaltimage release];
-    }
-
-    if (clickCount == 2) {
-        [self menuTrackingDone:nil];
-        [parent doubleClickSelector:self];
-    } else {
-        [parent triggerSelector:self button:mouseButton];
-    }
-}
-
--(void)mouseDown:(NSEvent *)mouseEvent
-{
-    [self mousePressed:mouseEvent button:Qt::LeftButton];
-}
-
--(void)mouseUp:(NSEvent *)mouseEvent
-{
-    Q_UNUSED(mouseEvent);
-    [self menuTrackingDone:nil];
-}
-
-- (void)rightMouseDown:(NSEvent *)mouseEvent
-{
-    [self mousePressed:mouseEvent button:Qt::RightButton];
-}
-
--(void)rightMouseUp:(NSEvent *)mouseEvent
-{
-    Q_UNUSED(mouseEvent);
-    [self menuTrackingDone:nil];
-}
-
-- (void)otherMouseDown:(NSEvent *)mouseEvent
-{
-    [self mousePressed:mouseEvent button:cocoaButton2QtButton([mouseEvent buttonNumber])];
-}
-
--(void)otherMouseUp:(NSEvent *)mouseEvent
-{
-    Q_UNUSED(mouseEvent);
-    [self menuTrackingDone:nil];
-}
-
--(void)drawRect:(NSRect)rect {
-    [[parent item] drawStatusBarBackgroundInRect:rect withHighlight:down];
-    [super drawRect:rect];
-}
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSStatusItem)
-
--(id)initWithIcon:(QSystemTrayIcon*)i iconPrivate:(QSystemTrayIconPrivate *)iPrivate
-{
-    self = [super init];
-    if(self) {
-        icon = i;
-        iconPrivate = iPrivate;
-        item = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain];
-        imageCell = [[QT_MANGLE_NAMESPACE(QNSImageView) alloc] initWithParent:self];
-        [item setView: imageCell];
-    }
-    return self;
-}
--(void)dealloc {
-    [[NSStatusBar systemStatusBar] removeStatusItem:item];
-    [imageCell release];
-    [item release];
-    [super dealloc];
-
-}
-
--(QSystemTrayIcon*)icon {
-    return icon;
-}
-
--(NSStatusItem*)item {
-    return item;
-}
--(QRectF)geometry {
-    if(NSWindow *window = [[item view] window]) {
-        NSRect screenRect = [[window screen] frame];
-        NSRect windowRect = [window frame];
-        return QRectF(windowRect.origin.x, screenRect.size.height-windowRect.origin.y-windowRect.size.height, windowRect.size.width, windowRect.size.height);
-    }
-    return QRectF();
-}
-
-- (void)triggerSelector:(id)sender button:(Qt::MouseButton)mouseButton {
-    Q_UNUSED(sender);
-    if (!icon)
-        return;
-
-    if (mouseButton == Qt::MidButton)
-        qtsystray_sendActivated(icon, QSystemTrayIcon::MiddleClick);
-    else
-        qtsystray_sendActivated(icon, QSystemTrayIcon::Trigger);
-
-    if (icon->contextMenu()) {
-#ifndef QT_MAC_USE_COCOA
-        [[[self item] view] removeAllToolTips];
-        iconPrivate->updateToolTip_sys();
-#endif
-        NSMenu *m = [[QT_MANGLE_NAMESPACE(QNSMenu) alloc] initWithQMenu:icon->contextMenu()];
-        [m setAutoenablesItems: NO];
-        [[NSNotificationCenter defaultCenter] addObserver:imageCell
-         selector:@selector(menuTrackingDone:)
-             name:NSMenuDidEndTrackingNotification
-                 object:m];
-        [item popUpStatusItemMenu: m];
-        [m release];
-    }
-}
-
-- (void)doubleClickSelector:(id)sender {
-    Q_UNUSED(sender);
-    if(!icon)
-        return;
-    qtsystray_sendActivated(icon, QSystemTrayIcon::DoubleClick);
-}
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
-- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification {
-    Q_UNUSED(center);
-    Q_UNUSED(notification);
-    return YES;
-}
-
-- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification {
-    Q_UNUSED(center);
-    Q_UNUSED(notification);
-    emit iconPrivate->sys->emitMessageClicked();
-}
-#endif
-
-@end
-
-class QSystemTrayIconQMenu : public QMenu
-{
-public:
-    void doAboutToShow() { emit aboutToShow(); }
-private:
-    QSystemTrayIconQMenu();
-};
-
-@implementation QT_MANGLE_NAMESPACE(QNSMenu)
--(id)initWithQMenu:(QMenu*)qm {
-    self = [super init];
-    if(self) {
-        self->qmenu = qm;
-        [self setDelegate:self];
-    }
-    return self;
-}
--(QMenu*)menu {
-    return qmenu;
-}
--(void)menuNeedsUpdate:(NSMenu*)nsmenu {
-    QT_MANGLE_NAMESPACE(QNSMenu) *menu = static_cast<QT_MANGLE_NAMESPACE(QNSMenu) *>(nsmenu);
-    emit static_cast<QSystemTrayIconQMenu*>(menu->qmenu)->doAboutToShow();
-    for(int i = [menu numberOfItems]-1; i >= 0; --i)
-        [menu removeItemAtIndex:i];
-    QList<QAction*> actions = menu->qmenu->actions();;
-    for(int i = 0; i < actions.size(); ++i) {
-        const QAction *action = actions[i];
-        if(!action->isVisible())
-            continue;
-
-        NSMenuItem *item = 0;
-        bool needRelease = false;
-        if(action->isSeparator()) {
-            item = [NSMenuItem separatorItem];
-        } else {
-            item = [[NSMenuItem alloc] init];
-            needRelease = true;
-            QString text = action->text();
-            QKeySequence accel = action->shortcut();
-            {
-                int st = text.lastIndexOf(QLatin1Char('\t'));
-                if(st != -1) {
-                    accel = QKeySequence(text.right(text.length()-(st+1)));
-                    text.remove(st, text.length()-st);
-                }
-            }
-            if(accel.count() > 1)
-                text += QLatin1String(" (****)"); //just to denote a multi stroke shortcut
-
-            [item setTitle:(NSString*)QCFString::toCFStringRef(qt_mac_removeMnemonics(text))];
-            [item setEnabled:menu->qmenu->isEnabled() && action->isEnabled()];
-            [item setState:action->isChecked() ? NSOnState : NSOffState];
-            [item setToolTip:(NSString*)QCFString::toCFStringRef(action->toolTip())];
-            const QIcon icon = action->icon();
-            if (!icon.isNull() && action->isIconVisibleInMenu()) {
-#ifndef QT_MAC_USE_COCOA
-                const short scale = GetMBarHeight();
-#else
-                const short scale = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
-#endif
-                NSImage *nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(icon.pixmap(QSize(scale, scale))));
-                [item setImage: nsimage];
-                [nsimage release];
-            }
-            if(action->menu()) {
-                QT_MANGLE_NAMESPACE(QNSMenu) *sub = [[QT_MANGLE_NAMESPACE(QNSMenu) alloc] initWithQMenu:action->menu()];
-                [item setSubmenu:sub];
-            } else {
-                [item setAction:@selector(selectedAction:)];
-                [item setTarget:self];
-            }
-            if(!accel.isEmpty()) {
-                [item setKeyEquivalent:keySequenceToKeyEqivalent(accel)];
-                [item setKeyEquivalentModifierMask:keySequenceModifierMask(accel)];
-            }
-        }
-        if(item)
-            [menu addItem:item];
-        if (needRelease)
-            [item release];
-    }
-}
--(void)selectedAction:(id)a {
-    const int activated = [self indexOfItem:a];
-    QAction *action = 0;
-    QList<QAction*> actions = qmenu->actions();
-    for(int i = 0, cnt = 0; i < actions.size(); ++i) {
-        if(actions.at(i)->isVisible() && (cnt++) == activated) {
-            action = actions.at(i);
-            break;
-        }
-    }
-    if(action) {
-        action->activate(QAction::Trigger);
-    }
-}
-@end
-
diff --git a/src/gui/util/qsystemtrayicon_win.cpp b/src/gui/util/qsystemtrayicon_win.cpp
deleted file mode 100644 (file)
index f02d1fd..0000000
+++ /dev/null
@@ -1,524 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsystemtrayicon_p.h"
-#ifndef QT_NO_SYSTEMTRAYICON
-
-#ifndef _WIN32_WINNT
-#define _WIN32_WINNT 0x0600
-#endif
-
-#ifndef _WIN32_IE
-#define _WIN32_IE 0x600
-#endif
-
-#include <qt_windows.h>
-#include <windowsx.h>
-#include <commctrl.h>
-
-#include <qsystemlibrary_p.h>
-#include <QApplication>
-#include <QSettings>
-
-QT_BEGIN_NAMESPACE
-
-static const UINT q_uNOTIFYICONID = 0;
-
-static uint MYWM_TASKBARCREATED = 0;
-#define MYWM_NOTIFYICON (WM_APP+101)
-
-struct Q_NOTIFYICONIDENTIFIER {
-    DWORD cbSize;
-    HWND hWnd;
-    UINT uID;
-    GUID guidItem;
-};
-
-#ifndef NOTIFYICON_VERSION_4
-#define NOTIFYICON_VERSION_4 4
-#endif
-
-#ifndef NIN_SELECT
-#define NIN_SELECT (WM_USER + 0)
-#endif
-
-#ifndef NIN_KEYSELECT
-#define NIN_KEYSELECT (WM_USER + 1)
-#endif
-
-#ifndef NIN_BALLOONTIMEOUT
-#define NIN_BALLOONTIMEOUT (WM_USER + 4)
-#endif
-
-#ifndef NIN_BALLOONUSERCLICK
-#define NIN_BALLOONUSERCLICK (WM_USER + 5)
-#endif
-
-#ifndef NIF_SHOWTIP
-#define NIF_SHOWTIP 0x00000080
-#endif
-
-#define Q_MSGFLT_ALLOW 1
-
-typedef HRESULT (WINAPI *PtrShell_NotifyIconGetRect)(const Q_NOTIFYICONIDENTIFIER* identifier, RECT* iconLocation);
-typedef BOOL (WINAPI *PtrChangeWindowMessageFilter)(UINT message, DWORD dwFlag);
-typedef BOOL (WINAPI *PtrChangeWindowMessageFilterEx)(HWND hWnd, UINT message, DWORD action, void* pChangeFilterStruct);
-
-class QSystemTrayIconSys : QWidget
-{
-public:
-    QSystemTrayIconSys(QSystemTrayIcon *object);
-    ~QSystemTrayIconSys();
-    bool winEvent( MSG *m, long *result );
-    bool trayMessage(DWORD msg);
-    void setIconContents(NOTIFYICONDATA &data);
-    bool showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs);
-    QRect findIconGeometry(const int a_iButtonID);
-    void createIcon();
-    HICON hIcon;
-    QPoint globalPos;
-    QSystemTrayIcon *q;
-private:
-    uint notifyIconSize;
-    int maxTipLength;
-    int version;
-    bool ignoreNextMouseRelease;
-};
-
-static bool allowsMessages()
-{
-#ifndef QT_NO_SETTINGS
-    QSettings settings(QLatin1String("HKEY_CURRENT_USER\\Software\\Microsoft"
-                                      "\\Windows\\CurrentVersion\\Explorer\\Advanced"), QSettings::NativeFormat);
-    return settings.value(QLatin1String("EnableBalloonTips"), true).toBool();
-#else
-    return false;
-#endif
-}
-
-QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *object)
-    : hIcon(0), q(object), ignoreNextMouseRelease(false)
-
-{
-    if (QSysInfo::windowsVersion() >= QSysInfo::WV_VISTA) {
-        notifyIconSize = sizeof(NOTIFYICONDATA);
-        version = NOTIFYICON_VERSION_4;
-    } else {
-        notifyIconSize = NOTIFYICONDATA_V2_SIZE;
-        version = NOTIFYICON_VERSION;
-    }
-
-    maxTipLength = 128;
-
-    // For restoring the tray icon after explorer crashes
-    if (!MYWM_TASKBARCREATED) {
-        MYWM_TASKBARCREATED = RegisterWindowMessage(L"TaskbarCreated");
-    }
-
-    // Allow the WM_TASKBARCREATED message through the UIPI filter on Windows Vista and higher
-    static PtrChangeWindowMessageFilterEx pChangeWindowMessageFilterEx =
-        (PtrChangeWindowMessageFilterEx)QSystemLibrary::resolve(QLatin1String("user32"), "ChangeWindowMessageFilterEx");
-
-    if (pChangeWindowMessageFilterEx) {
-        // Call the safer ChangeWindowMessageFilterEx API if available
-        pChangeWindowMessageFilterEx(winId(), MYWM_TASKBARCREATED, Q_MSGFLT_ALLOW, 0);
-    } else {
-        static PtrChangeWindowMessageFilter pChangeWindowMessageFilter =
-            (PtrChangeWindowMessageFilter)QSystemLibrary::resolve(QLatin1String("user32"), "ChangeWindowMessageFilter");
-
-        if (pChangeWindowMessageFilter) {
-            // Call the deprecated ChangeWindowMessageFilter API otherwise
-            pChangeWindowMessageFilter(MYWM_TASKBARCREATED, Q_MSGFLT_ALLOW);
-        }
-    }
-}
-
-QSystemTrayIconSys::~QSystemTrayIconSys()
-{
-    if (hIcon)
-        DestroyIcon(hIcon);
-}
-
-void QSystemTrayIconSys::setIconContents(NOTIFYICONDATA &tnd)
-{
-    tnd.uFlags |= NIF_MESSAGE | NIF_ICON | NIF_TIP;
-    tnd.uCallbackMessage = MYWM_NOTIFYICON;
-    tnd.hIcon = hIcon;
-    QString tip = q->toolTip();
-
-    if (!tip.isNull()) {
-        tip = tip.left(maxTipLength - 1) + QChar();
-        memcpy(tnd.szTip, tip.utf16(), qMin(tip.length() + 1, maxTipLength) * sizeof(wchar_t));
-    }
-}
-
-static int iconFlag( QSystemTrayIcon::MessageIcon icon )
-{
-    switch (icon) {
-        case QSystemTrayIcon::Information:
-            return NIIF_INFO;
-        case QSystemTrayIcon::Warning:
-            return NIIF_WARNING;
-        case QSystemTrayIcon::Critical:
-            return NIIF_ERROR;
-        case QSystemTrayIcon::NoIcon:
-            return NIIF_NONE;
-        default:
-            Q_ASSERT_X(false, "QSystemTrayIconSys::showMessage", "Invalid QSystemTrayIcon::MessageIcon value");
-            return NIIF_NONE;
-    }
-}
-
-bool QSystemTrayIconSys::showMessage(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, uint uSecs)
-{
-    NOTIFYICONDATA tnd;
-    memset(&tnd, 0, notifyIconSize);
-
-    memcpy(tnd.szInfo, message.utf16(), qMin(message.length() + 1, 256) * sizeof(wchar_t));
-    memcpy(tnd.szInfoTitle, title.utf16(), qMin(title.length() + 1, 64) * sizeof(wchar_t));
-
-    tnd.uID = q_uNOTIFYICONID;
-    tnd.dwInfoFlags = iconFlag(type);
-    tnd.cbSize = notifyIconSize;
-    tnd.hWnd = winId();
-    tnd.uTimeout = uSecs;
-    tnd.uFlags = NIF_INFO | NIF_SHOWTIP;
-
-    Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
-    return Shell_NotifyIcon(NIM_MODIFY, &tnd);
-}
-
-bool QSystemTrayIconSys::trayMessage(DWORD msg)
-{
-    NOTIFYICONDATA tnd;
-    memset(&tnd, 0, notifyIconSize);
-
-    tnd.uID = q_uNOTIFYICONID;
-    tnd.cbSize = notifyIconSize;
-    tnd.hWnd = winId();
-    tnd.uFlags = NIF_SHOWTIP;
-    tnd.uVersion = version;
-
-    Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
-    if (msg == NIM_ADD || msg == NIM_MODIFY) {
-        setIconContents(tnd);
-    }
-
-    bool success = Shell_NotifyIcon(msg, &tnd);
-
-    if (msg == NIM_ADD)
-        return success && Shell_NotifyIcon(NIM_SETVERSION, &tnd);
-    else
-        return success;
-}
-
-void QSystemTrayIconSys::createIcon()
-{
-    hIcon = 0;
-    QIcon icon = q->icon();
-    if (icon.isNull())
-        return;
-
-    const int iconSizeX = GetSystemMetrics(SM_CXSMICON);
-    const int iconSizeY = GetSystemMetrics(SM_CYSMICON);
-    QSize size = icon.actualSize(QSize(iconSizeX, iconSizeY));
-    QPixmap pm = icon.pixmap(size);
-    if (pm.isNull())
-        return;
-
-    hIcon = pm.toWinHICON();
-}
-
-bool QSystemTrayIconSys::winEvent( MSG *m, long *result )
-{
-    switch(m->message) {
-    case MYWM_NOTIFYICON:
-        {
-            int message = 0;
-            QPoint gpos;
-
-            if (version == NOTIFYICON_VERSION_4) {
-                Q_ASSERT(q_uNOTIFYICONID == HIWORD(m->lParam));
-                message = LOWORD(m->lParam);
-                gpos = QPoint(GET_X_LPARAM(m->wParam), GET_Y_LPARAM(m->wParam));
-            } else {
-                Q_ASSERT(q_uNOTIFYICONID == m->wParam);
-                message = m->lParam;
-                gpos = QCursor::pos();
-            }
-
-            switch (message) {
-            case NIN_SELECT:
-            case NIN_KEYSELECT:
-                if (ignoreNextMouseRelease)
-                    ignoreNextMouseRelease = false;
-                else 
-                    emit q->activated(QSystemTrayIcon::Trigger);
-                break;
-
-            case WM_LBUTTONDBLCLK:
-                ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse 
-                                               // release we must ignore it
-                emit q->activated(QSystemTrayIcon::DoubleClick);
-                break;
-
-            case WM_CONTEXTMENU:
-                if (q->contextMenu()) {
-                    q->contextMenu()->popup(gpos);
-                    q->contextMenu()->activateWindow();
-                }
-                emit q->activated(QSystemTrayIcon::Context);
-                break;
-
-            case NIN_BALLOONUSERCLICK:
-                emit q->messageClicked();
-                break;
-
-            case WM_MBUTTONUP:
-                emit q->activated(QSystemTrayIcon::MiddleClick);
-                break;
-
-            default:
-                break;
-            }
-            break;
-        }
-    default:
-        if (m->message == MYWM_TASKBARCREATED)
-            trayMessage(NIM_ADD);
-        else
-            return QWidget::winEvent(m, result);
-        break;
-    }
-    return 0;
-}
-
-void QSystemTrayIconPrivate::install_sys()
-{
-    Q_Q(QSystemTrayIcon);
-    if (!sys) {
-        sys = new QSystemTrayIconSys(q);
-        sys->createIcon();
-        sys->trayMessage(NIM_ADD);
-    }
-}
-
-/*
-* This function tries to determine the icon geometry from the tray
-*
-* If it fails an invalid rect is returned.
-*/
-QRect QSystemTrayIconSys::findIconGeometry(const int iconId)
-{
-    static PtrShell_NotifyIconGetRect Shell_NotifyIconGetRect =
-        (PtrShell_NotifyIconGetRect)QSystemLibrary::resolve(QLatin1String("shell32"), "Shell_NotifyIconGetRect");
-
-    if (Shell_NotifyIconGetRect) {
-        Q_NOTIFYICONIDENTIFIER nid;
-        memset(&nid, 0, sizeof(nid));
-        nid.cbSize = sizeof(nid);
-        nid.hWnd = winId();
-        nid.uID = iconId;
-
-        RECT rect;
-        HRESULT hr = Shell_NotifyIconGetRect(&nid, &rect);
-        if (SUCCEEDED(hr)) {
-            return QRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top);
-        }
-    }
-
-    QRect ret;
-
-    TBBUTTON buttonData;
-    DWORD processID = 0;
-    HWND trayHandle = FindWindow(L"Shell_TrayWnd", NULL);
-
-    //find the toolbar used in the notification area
-    if (trayHandle) {
-        trayHandle = FindWindowEx(trayHandle, NULL, L"TrayNotifyWnd", NULL);
-        if (trayHandle) {
-            HWND hwnd = FindWindowEx(trayHandle, NULL, L"SysPager", NULL);
-            if (hwnd) {
-                hwnd = FindWindowEx(hwnd, NULL, L"ToolbarWindow32", NULL);
-                if (hwnd)
-                    trayHandle = hwnd;
-            }
-        }
-    }
-
-    if (!trayHandle)
-        return ret;
-
-    GetWindowThreadProcessId(trayHandle, &processID);
-    if (processID <= 0)
-        return ret;
-
-    HANDLE trayProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ, 0, processID);
-    if (!trayProcess)
-        return ret;
-
-    int buttonCount = SendMessage(trayHandle, TB_BUTTONCOUNT, 0, 0);
-    LPVOID data = VirtualAllocEx(trayProcess, NULL, sizeof(TBBUTTON), MEM_COMMIT, PAGE_READWRITE);
-
-    if ( buttonCount < 1 || !data ) {
-        CloseHandle(trayProcess);
-        return ret;
-    }
-
-    //search for our icon among all toolbar buttons
-    for (int toolbarButton = 0; toolbarButton  < buttonCount; ++toolbarButton ) {
-        SIZE_T numBytes = 0;
-        DWORD appData[2] = { 0, 0 };
-        SendMessage(trayHandle, TB_GETBUTTON, toolbarButton , (LPARAM)data);
-
-        if (!ReadProcessMemory(trayProcess, data, &buttonData, sizeof(TBBUTTON), &numBytes))
-            continue;
-
-        if (!ReadProcessMemory(trayProcess, (LPVOID) buttonData.dwData, appData, sizeof(appData), &numBytes))
-            continue;
-
-        int currentIconId = appData[1];
-        HWND currentIconHandle = (HWND) appData[0];
-        bool isHidden = buttonData.fsState & TBSTATE_HIDDEN;
-
-        if (currentIconHandle == winId() &&
-            currentIconId == iconId && !isHidden) {
-            SendMessage(trayHandle, TB_GETITEMRECT, toolbarButton , (LPARAM)data);
-            RECT iconRect = {0, 0, 0, 0};
-            if(ReadProcessMemory(trayProcess, data, &iconRect, sizeof(RECT), &numBytes)) {
-                MapWindowPoints(trayHandle, NULL, (LPPOINT)&iconRect, 2);
-                QRect geometry(iconRect.left + 1, iconRect.top + 1,
-                                iconRect.right - iconRect.left - 2,
-                                iconRect.bottom - iconRect.top - 2);
-                if (geometry.isValid())
-                    ret = geometry;
-                break;
-            }
-        }
-    }
-    VirtualFreeEx(trayProcess, data, 0, MEM_RELEASE);
-    CloseHandle(trayProcess);
-    return ret;
-}
-
-void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, int timeOut)
-{
-    if (!sys || !allowsMessages())
-        return;
-
-    uint uSecs = 0;
-    if ( timeOut < 0)
-        uSecs = 10000; //10 sec default
-    else uSecs = (int)timeOut;
-
-    //message is limited to 255 chars + NULL
-    QString messageString;
-    if (message.isEmpty() && !title.isEmpty())
-        messageString = QLatin1Char(' '); //ensures that the message shows when only title is set
-    else
-        messageString = message.left(255) + QChar();
-
-    //title is limited to 63 chars + NULL
-    QString titleString = title.left(63) + QChar();
-
-    sys->showMessage(titleString, messageString, type, uSecs);
-}
-
-QRect QSystemTrayIconPrivate::geometry_sys() const
-{
-    if (!sys)
-        return QRect();
-
-    return sys->findIconGeometry(q_uNOTIFYICONID);
-}
-
-void QSystemTrayIconPrivate::remove_sys()
-{
-    if (!sys)
-        return;
-
-    sys->trayMessage(NIM_DELETE);
-    delete sys;
-    sys = 0;
-}
-
-void QSystemTrayIconPrivate::updateIcon_sys()
-{
-    if (!sys)
-        return;
-
-    HICON hIconToDestroy = sys->hIcon;
-
-    sys->createIcon();
-    sys->trayMessage(NIM_MODIFY);
-
-    if (hIconToDestroy)
-        DestroyIcon(hIconToDestroy);
-}
-
-void QSystemTrayIconPrivate::updateMenu_sys()
-{
-
-}
-
-void QSystemTrayIconPrivate::updateToolTip_sys()
-{
-    if (!sys)
-        return;
-
-    sys->trayMessage(NIM_MODIFY);
-}
-
-bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
-{
-    return true;
-}
-
-bool QSystemTrayIconPrivate::supportsMessages_sys()
-{
-    return allowsMessages();
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/util/qsystemtrayicon_wince.cpp b/src/gui/util/qsystemtrayicon_wince.cpp
deleted file mode 100644 (file)
index 5700fd8..0000000
+++ /dev/null
@@ -1,293 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qsystemtrayicon_p.h"
-#ifndef QT_NO_SYSTEMTRAYICON
-#define _WIN32_IE 0x0600 //required for NOTIFYICONDATA_V2_SIZE
-
-#include <qt_windows.h>
-#include <shlwapi.h>
-#include <QApplication>
-
-QT_BEGIN_NAMESPACE
-
-static const UINT q_uNOTIFYICONID = 13;     // IDs from 0 to 12 are reserved on WinCE.
-#define MYWM_NOTIFYICON (WM_APP+101)
-
-struct Q_NOTIFYICONIDENTIFIER {
-    DWORD cbSize;
-    HWND hWnd;
-    UINT uID;
-    GUID guidItem;
-};
-
-class QSystemTrayIconSys : QWidget
-{
-public:
-    QSystemTrayIconSys(QSystemTrayIcon *object);
-    ~QSystemTrayIconSys();
-    bool winEvent( MSG *m, long *result );
-    bool trayMessage(DWORD msg);
-    void setIconContents(NOTIFYICONDATA &data);
-    void createIcon();
-    QRect findTrayGeometry();
-    HICON hIcon;
-    QPoint globalPos;
-    QSystemTrayIcon *q;
-private:
-    uint notifyIconSize;
-    int maxTipLength;
-    bool ignoreNextMouseRelease;
-};
-
-QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *object)
-    : hIcon(0), q(object), ignoreNextMouseRelease(false)
-
-{
-    notifyIconSize = FIELD_OFFSET(NOTIFYICONDATA, szTip[64]); // NOTIFYICONDATAW_V1_SIZE;
-    maxTipLength = 64;
-}
-
-QSystemTrayIconSys::~QSystemTrayIconSys()
-{
-    if (hIcon)
-        DestroyIcon(hIcon);
-}
-
-QRect QSystemTrayIconSys::findTrayGeometry()
-{
-    // Use lower right corner as fallback
-    QPoint brCorner = qApp->desktop()->screenGeometry().bottomRight();
-    QRect ret(brCorner.x() - 10, brCorner.y() - 10, 10, 10);
-    return ret;
-}
-
-void QSystemTrayIconSys::setIconContents(NOTIFYICONDATA &tnd)
-{
-    tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
-    tnd.uCallbackMessage = MYWM_NOTIFYICON;
-    tnd.hIcon = hIcon;
-    QString tip = q->toolTip();
-
-    if (!tip.isNull()) {
-        tip = tip.left(maxTipLength - 1) + QChar();
-        memcpy(tnd.szTip, tip.utf16(), qMin(tip.length() + 1, maxTipLength) * sizeof(wchar_t));
-    }
-}
-
-bool QSystemTrayIconSys::trayMessage(DWORD msg)
-{
-    NOTIFYICONDATA tnd;
-    memset(&tnd, 0, notifyIconSize);
-    tnd.uID = q_uNOTIFYICONID;
-    tnd.cbSize = notifyIconSize;
-    tnd.hWnd = winId();
-
-    Q_ASSERT(testAttribute(Qt::WA_WState_Created));
-
-    if (msg != NIM_DELETE) {
-        setIconContents(tnd);
-    }
-
-    return Shell_NotifyIcon(msg, &tnd);
-}
-
-void QSystemTrayIconSys::createIcon()
-{
-    hIcon = 0;
-    QIcon icon = q->icon();
-    if (icon.isNull())
-        return;
-
-    //const QSize preferredSize(GetSystemMetrics(SM_CXSMICON) * 2, GetSystemMetrics(SM_CYSMICON) * 2);
-    const QSize preferredSize(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
-    QPixmap pm = icon.pixmap(preferredSize);
-    if (pm.isNull())
-        return;
-
-    hIcon = pm.toWinHICON();
-}
-
-bool QSystemTrayIconSys::winEvent( MSG *m, long *result )
-{
-    switch(m->message) {
-    case WM_CREATE:
-        SetWindowLong(winId(), GWL_USERDATA, (LONG)((CREATESTRUCTW*)m->lParam)->lpCreateParams);
-        break;
-
-    case MYWM_NOTIFYICON:
-        {
-            QPoint gpos = QCursor::pos();
-
-            switch (m->lParam) {
-            case WM_LBUTTONUP:
-                if (ignoreNextMouseRelease)
-                    ignoreNextMouseRelease = false;
-                else
-                    emit q->activated(QSystemTrayIcon::Trigger);
-                break;
-
-            case WM_LBUTTONDBLCLK:
-                ignoreNextMouseRelease = true; // Since DBLCLICK Generates a second mouse 
-                                               // release we must ignore it
-                emit q->activated(QSystemTrayIcon::DoubleClick);
-                break;
-
-            case WM_RBUTTONUP:
-                if (q->contextMenu()) {
-                    q->contextMenu()->popup(gpos);
-
-                    // We must ensure that the popup menu doesn't show up behind the task bar.
-                    QRect desktopRect = qApp->desktop()->availableGeometry();
-                    int maxY = desktopRect.y() + desktopRect.height() - q->contextMenu()->height();
-                    if (gpos.y() > maxY) {
-                        gpos.ry() = maxY;
-                        q->contextMenu()->move(gpos);
-                    }
-                }
-                emit q->activated(QSystemTrayIcon::Context);
-                break;
-
-            case WM_MBUTTONUP:
-                emit q->activated(QSystemTrayIcon::MiddleClick);
-                break;
-
-            default:
-                break;
-            }
-            break;
-        }
-    default:
-        return QWidget::winEvent(m, result);
-    }
-    return 0;
-}
-
-void QSystemTrayIconPrivate::install_sys()
-{
-    Q_Q(QSystemTrayIcon);
-    if (!sys) {
-        sys = new QSystemTrayIconSys(q);
-        sys->createIcon();
-        sys->trayMessage(NIM_ADD);
-    }
-}
-
-void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString &message, QSystemTrayIcon::MessageIcon type, int timeOut)
-{
-    if (!sys)
-        return;
-
-    uint uSecs = 0;
-    if ( timeOut < 0)
-        uSecs = 10000; //10 sec default
-    else uSecs = (int)timeOut;
-
-    //message is limited to 255 chars + NULL
-    QString messageString;
-    if (message.isEmpty() && !title.isEmpty())
-        messageString = QLatin1Char(' '); //ensures that the message shows when only title is set
-    else
-        messageString = message.left(255) + QChar();
-
-    //title is limited to 63 chars + NULL
-    QString titleString = title.left(63) + QChar();
-
-    //show QBalloonTip
-    QRect trayRect = sys->findTrayGeometry();
-    QBalloonTip::showBalloon(type, title, message, sys->q, QPoint(trayRect.left(),
-                             trayRect.center().y()), uSecs, false);
-}
-
-QRect QSystemTrayIconPrivate::geometry_sys() const
-{
-    return QRect();
-}
-
-void QSystemTrayIconPrivate::remove_sys()
-{
-    if (!sys)
-        return;
-
-    sys->trayMessage(NIM_DELETE);
-    delete sys;
-    sys = 0;
-}
-
-void QSystemTrayIconPrivate::updateIcon_sys()
-{
-    if (!sys)
-        return;
-
-    HICON hIconToDestroy = sys->hIcon;
-
-    sys->createIcon();
-    sys->trayMessage(NIM_MODIFY);
-
-    if (hIconToDestroy)
-        DestroyIcon(hIconToDestroy);
-}
-
-void QSystemTrayIconPrivate::updateMenu_sys()
-{
-
-}
-
-void QSystemTrayIconPrivate::updateToolTip_sys()
-{
-    // Calling sys->trayMessage(NIM_MODIFY) on an existing icon is broken on Windows CE.
-    // So we need to call updateIcon_sys() which creates a new icon handle.
-    updateIcon_sys();
-}
-
-bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
-{
-    return true;
-}
-
-bool QSystemTrayIconPrivate::supportsMessages_sys()
-{
-    return true;
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/widgets/qcocoamenu_mac.mm b/src/gui/widgets/qcocoamenu_mac.mm
deleted file mode 100644 (file)
index dcfb63d..0000000
+++ /dev/null
@@ -1,244 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmacdefines_mac.h"
-#include "qapplication.h"
-#ifdef QT_MAC_USE_COCOA
-#import <qcocoamenu_mac_p.h>
-#import <qcocoamenuloader_mac_p.h>
-#import <qcocoaapplication_mac_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qapplication_p.h>
-#include <qaction_p.h>
-#include <qcocoaapplication_mac_p.h>
-
-#include <QtGui/QMenu>
-
-QT_FORWARD_DECLARE_CLASS(QAction)
-QT_FORWARD_DECLARE_CLASS(QWidget)
-QT_FORWARD_DECLARE_CLASS(QApplication)
-QT_FORWARD_DECLARE_CLASS(QCoreApplication)
-QT_FORWARD_DECLARE_CLASS(QApplicationPrivate)
-QT_FORWARD_DECLARE_CLASS(QKeyEvent)
-QT_FORWARD_DECLARE_CLASS(QEvent)
-
-QT_BEGIN_NAMESPACE
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); //qapplication.cpp
-extern NSString *qt_mac_removePrivateUnicode(NSString* string);
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaMenu)
-
-- (id)initWithQMenu:(QMenu*)menu
-{
-    self = [super init];
-    if (self) {
-        qmenu = menu;
-        previousAction = 0;
-        [self setAutoenablesItems:NO];
-        [self setDelegate:self];
-    }
-    return self;
-}
-
-- (void)menu:(NSMenu*)menu willHighlightItem:(NSMenuItem*)item
-{
-    Q_UNUSED(menu);
-
-    if (!item) {
-        if (previousAction) {
-            qt_mac_clear_status_text(previousAction);
-            previousAction = 0;
-        }
-        return;
-    }
-
-    if (QAction *action = reinterpret_cast<QAction *>([item tag])) {
-        QMenu *qtmenu = static_cast<QT_MANGLE_NAMESPACE(QCocoaMenu) *>(menu)->qmenu;
-        previousAction = action;
-        action->activate(QAction::Hover);
-        qt_mac_menu_emit_hovered(qtmenu, action);
-        action->showStatusText(0); // 0 widget -> action's parent
-    }
-}
-
-- (void)menuWillOpen:(NSMenu*)menu
-{
-    while (QWidget *popup
-                = QApplication::activePopupWidget())
-        popup->close();
-    QMenu *qtmenu = static_cast<QT_MANGLE_NAMESPACE(QCocoaMenu) *>(menu)->qmenu;
-    qt_mac_emit_menuSignals(qtmenu, true);
-    qt_mac_menu_collapseSeparators(menu, qtmenu->separatorsCollapsible());
-}
-
-- (void)menuDidClose:(NSMenu*)menu
-{
-    qt_mac_emit_menuSignals(((QT_MANGLE_NAMESPACE(QCocoaMenu) *)menu)->qmenu, false);
-    if (previousAction) {
-        qt_mac_clear_status_text(previousAction);
-        previousAction = 0;
-    }
-}
-
-- (BOOL)hasShortcut:(NSMenu *)menu forKey:(NSString *)key forModifiers:(NSUInteger)modifier
-  whichItem:(NSMenuItem**)outItem
-{
-    for (NSMenuItem *item in [menu itemArray]) {
-        if (![item isEnabled] || [item isHidden] || [item isSeparatorItem])
-            continue;
-        if ([item hasSubmenu]) {
-            if ([self hasShortcut:[item submenu]
-                           forKey:key
-                     forModifiers:modifier whichItem:outItem]) {
-                if (outItem)
-                    *outItem = item;
-                return YES;
-            }
-        }
-        NSString *menuKey = [item keyEquivalent];
-        if (menuKey && NSOrderedSame == [menuKey compare:key]
-            && (modifier == [item keyEquivalentModifierMask])) {
-            if (outItem)
-                *outItem = item;
-            return YES;
-        }
-    }
-    if (outItem)
-        *outItem = 0;
-    return NO;
-}
-
-- (BOOL)menuHasKeyEquivalent:(NSMenu *)menu forEvent:(NSEvent *)event target:(id *)target action:(SEL *)action
-{
-    // Check if the menu actually has a keysequence defined for this key event.
-    // If it does, then we will first send the key sequence to the QWidget that has focus
-    // since (in Qt's eyes) it needs to a chance at the key event first. If the widget
-    // accepts the key event, we then return YES, but set the target and action to be nil,
-    // which means that the action should not be triggered, and instead dispatch the event ourselves.
-    // In every other case we return NO, which means that Cocoa can do as it pleases
-    // (i.e., fire the menu action).
-    NSMenuItem *whichItem;
-    // Change the private unicode keys to the ones used in setting the "Key Equivalents"
-    NSString *characters = qt_mac_removePrivateUnicode([event characters]);
-    if ([self hasShortcut:menu
-            forKey:characters
-            // Interested only in Shift, Cmd, Ctrl & Alt Keys, so ignoring masks like, Caps lock, Num Lock ...
-            forModifiers:([event modifierFlags] & (NSShiftKeyMask | NSControlKeyMask | NSCommandKeyMask | NSAlternateKeyMask))
-            whichItem:&whichItem]) {
-        QWidget *widget = 0;
-        QAction *qaction = 0;
-        if (whichItem && [whichItem tag]) {
-            qaction = reinterpret_cast<QAction *>([whichItem tag]);
-        }
-        if (qApp->activePopupWidget())
-            widget = (qApp->activePopupWidget()->focusWidget() ?
-                      qApp->activePopupWidget()->focusWidget() : qApp->activePopupWidget());
-        else if (QApplicationPrivate::focus_widget)
-            widget = QApplicationPrivate::focus_widget;
-        // If we could not find any receivers, pass it to the active window
-        if (!widget)
-            widget = qApp->activeWindow();
-        if (qaction && widget) {
-            int key = qaction->shortcut();
-            QKeyEvent accel_ev(QEvent::ShortcutOverride, (key & (~Qt::KeyboardModifierMask)),
-                               Qt::KeyboardModifiers(key & Qt::KeyboardModifierMask));
-            accel_ev.ignore();
-            qt_sendSpontaneousEvent(widget, &accel_ev);
-            if (accel_ev.isAccepted()) {
-                qt_dispatchKeyEvent(event, widget);
-                *target = nil;
-                *action = nil;
-                return YES;
-            }
-        }
-    }
-    return NO;
-}
-
-- (NSInteger)indexOfItemWithTarget:(id)anObject andAction:(SEL)actionSelector
-{
-     NSInteger index = [super indexOfItemWithTarget:anObject andAction:actionSelector];
-     static SEL selForOFCP = NSSelectorFromString(@"orderFrontCharacterPalette:");
-     if (index == -1 && selForOFCP == actionSelector) {
-         // Check if the 'orderFrontCharacterPalette' SEL exists for QCocoaMenuLoader object
-         QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = [[NSApplication sharedApplication] QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)];
-         return [super indexOfItemWithTarget:loader andAction:actionSelector];
-     }
-     return index;
-}
-
-@end
-
-QT_BEGIN_NAMESPACE
-extern int qt_mac_menus_open_count; // qmenu_mac.mm
-
-void qt_mac_emit_menuSignals(QMenu *menu, bool show)
-{
-    if (!menu)
-        return;
-    int delta;
-    if (show) {
-        emit menu->aboutToShow();
-        delta = 1;
-    } else {
-        emit menu->aboutToHide();
-        delta = -1;
-    }
-    qt_mac_menus_open_count += delta;
-}
-
-void qt_mac_clear_status_text(QAction *action)
-{
-    action->d_func()->showStatusText(0, QString());
-}
-
-void qt_mac_menu_emit_hovered(QMenu *menu, QAction *action)
-{
-    emit menu->hovered(action);
-}
-
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/gui/widgets/qcocoamenu_mac_p.h b/src/gui/widgets/qcocoamenu_mac_p.h
deleted file mode 100644 (file)
index d3f8cbc..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_FORWARD_DECLARE_CLASS(QMenu)
-QT_FORWARD_DECLARE_CLASS(QAction)
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5
-
-@protocol NSMenuDelegate <NSObject>
-- (void)menu:(NSMenu*)menu willHighlightItem:(NSMenuItem*)item;
-- (void)menuWillOpen:(NSMenu*)menu;
-- (void)menuDidClose:(NSMenu*)menu;
-- (BOOL)hasShortcut:(NSMenu *)menu forKey:(NSString *)key forModifiers:(NSUInteger)modifier
-  whichItem:(NSMenuItem**)outItem;
-@end
-
-#endif
-
-@interface QT_MANGLE_NAMESPACE(QCocoaMenu) : NSMenu <NSMenuDelegate>
-{
-    QMenu *qmenu;
-    QAction *previousAction;
-}
-- (id)initWithQMenu:(QMenu*)menu;
-- (BOOL)menuHasKeyEquivalent:(NSMenu *)menu forEvent:(NSEvent *)event target:(id *)target action:(SEL *)action;
-- (NSInteger)indexOfItemWithTarget:(id)anObject andAction:(SEL)actionSelector;
-@end
-#endif
-
diff --git a/src/gui/widgets/qcocoatoolbardelegate_mac.mm b/src/gui/widgets/qcocoatoolbardelegate_mac.mm
deleted file mode 100644 (file)
index 2edd3c0..0000000
+++ /dev/null
@@ -1,153 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#import <qcocoatoolbardelegate_mac_p.h>
-#ifdef QT_MAC_USE_COCOA
-#include <qmainwindowlayout_p.h>
-#include <qt_mac_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qcocoaview_mac_p.h>
-#include <qwidget_p.h>
-#include <qtoolbar.h>
-#include <qlayout.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-extern QWidgetPrivate *qt_widget_private(QWidget *widget);
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QMainWindowLayout);
-QT_FORWARD_DECLARE_CLASS(QToolBar);
-QT_FORWARD_DECLARE_CLASS(QCFString);
-
-@implementation QT_MANGLE_NAMESPACE(QCocoaToolBarDelegate)
-
-- (id)initWithMainWindowLayout:(QMainWindowLayout *)layout
-{
-    self = [super init];
-    if (self) {
-        mainWindowLayout = layout;
-    }
-    return self;
-}
-
-- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
-{
-    Q_UNUSED(toolbar);
-    return [NSArray arrayWithObject:@"com.trolltech.qt.nstoolbar-qtoolbar"];
-}
-
-- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
-{
-    return [self toolbarAllowedItemIdentifiers:toolbar];
-}
-
-- (void)toolbarDidRemoveItem:(NSNotification *)notification
-{
-    NSToolbarItem *item = [[notification userInfo] valueForKey:@"item"];
-    mainWindowLayout->unifiedToolbarHash.remove(item);
-    for (int i = 0; i < mainWindowLayout->toolbarItemsCopy.size(); ++i) {
-        if (mainWindowLayout->toolbarItemsCopy.at(i) == item) {
-            // I know about it, so release it.
-            mainWindowLayout->toolbarItemsCopy.removeAt(i);
-            mainWindowLayout->qtoolbarsInUnifiedToolbarList.removeAt(i);
-            [item release];
-            break;
-        }
-    }
-}
-
-- (NSToolbarItem *)toolbar:(NSToolbar *)nstoolbar itemForItemIdentifier:(NSString *)itemIdentifier
-    willBeInsertedIntoToolbar:(BOOL)flag
-{
-    Q_UNUSED(flag);
-    Q_UNUSED(nstoolbar);
-    QToolBar *tb = mainWindowLayout->cocoaItemIDToToolbarHash.value(
-            QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)(itemIdentifier));
-    NSToolbarItem *item = nil;
-    if (tb) {
-        item = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
-        mainWindowLayout->unifiedToolbarHash.insert(item, tb);
-    }
-    return item;
-}
-
-- (void)toolbarWillAddItem:(NSNotification *)notification
-{
-    NSToolbarItem *item = [[notification userInfo] valueForKey:@"item"];
-    QToolBar *tb = mainWindowLayout->cocoaItemIDToToolbarHash.value(
-            QT_PREPEND_NAMESPACE(qt_mac_NSStringToQString)([item itemIdentifier]));
-    if (!tb)
-        return; // I can't really do anything about this.
-    [item retain];
-    [item setView:QT_PREPEND_NAMESPACE(qt_mac_nativeview_for)(tb)];
-
-    NSArray *items = [[qt_mac_window_for(mainWindowLayout->layoutState.mainWindow->window()) toolbar] items];
-    int someIndex = 0;
-    for (NSToolbarItem *i in items) {
-        if (i == item)
-            break;
-        ++someIndex;
-    }
-    mainWindowLayout->toolbarItemsCopy.insert(someIndex, item);
-
-    // This is synchronization code that was needed in Carbon, but may not be needed anymore here.
-    QToolBar *toolbar = mainWindowLayout->unifiedToolbarHash.value(item);
-    if (toolbar) {
-        int toolbarIndex = mainWindowLayout->qtoolbarsInUnifiedToolbarList.indexOf(toolbar);
-        if (someIndex != toolbarIndex) {
-            // Dang, we must be out of sync, rebuild it from the "toolbarItemsCopy"
-            mainWindowLayout->qtoolbarsInUnifiedToolbarList.clear();
-            for (int i = 0; i < mainWindowLayout->toolbarItemsCopy.size(); ++i) {
-                // This will either append the correct toolbar or an
-                // null toolbar. This is fine because this list
-                // is really only kept to make sure that things are but in the right order.
-                mainWindowLayout->qtoolbarsInUnifiedToolbarList.append(
-                                  mainWindowLayout->unifiedToolbarHash.value(mainWindowLayout->
-                                                                        toolbarItemsCopy.at(i)));
-            }
-        }
-        toolbar->update();
-    }
-}
-
-@end
-#endif // QT_MAC_USE_COCOA
diff --git a/src/gui/widgets/qcocoatoolbardelegate_mac_p.h b/src/gui/widgets/qcocoatoolbardelegate_mac_p.h
deleted file mode 100644 (file)
index 5cf43a8..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#include "qmacdefines_mac.h"
-#ifdef QT_MAC_USE_COCOA
-#import <Cocoa/Cocoa.h>
-
-QT_BEGIN_NAMESPACE
-class QMainWindowLayout;
-class QToolBar;
-QT_END_NAMESPACE
-
-@class NSToolbarItem;
-
-@interface QT_MANGLE_NAMESPACE(QCocoaToolBarDelegate) : NSObject {
-    QT_PREPEND_NAMESPACE(QMainWindowLayout) *mainWindowLayout;
-    NSToolbarItem *toolbarItem;
-}
-
-- (id)initWithMainWindowLayout:(QT_PREPEND_NAMESPACE(QMainWindowLayout) *)layout;
-@end
-#endif
diff --git a/src/gui/widgets/qmaccocoaviewcontainer_mac.h b/src/gui/widgets/qmaccocoaviewcontainer_mac.h
deleted file mode 100644 (file)
index 2e38699..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QCOCOAVIEWCONTAINER_H
-#define QCOCOAVIEWCONTAINER_H
-
-#include <QtGui/QWidget>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-
-class QMacCocoaViewContainerPrivate;
-
-class Q_GUI_EXPORT QMacCocoaViewContainer : public QWidget
-{
-    Q_OBJECT
-public:
-    QMacCocoaViewContainer(void *cocoaViewToWrap, QWidget *parent = 0);
-    virtual ~QMacCocoaViewContainer();
-
-    void setCocoaView(void *cocoaViewToWrap);
-    void *cocoaView() const;
-
-private:
-    Q_DECLARE_PRIVATE(QMacCocoaViewContainer)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QCOCOAVIEWCONTAINER_H
diff --git a/src/gui/widgets/qmaccocoaviewcontainer_mac.mm b/src/gui/widgets/qmaccocoaviewcontainer_mac.mm
deleted file mode 100644 (file)
index dbba021..0000000
+++ /dev/null
@@ -1,192 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#import <Cocoa/Cocoa.h>
-#include <qwidget_p.h>
-#include "qmaccocoaviewcontainer_mac.h"
-#include <qt_mac_p.h>
-
-/*!
-    \class QMacCocoaViewContainer
-    \since 4.5
-
-    \brief The QMacCocoaViewContainer class provides a widget for Mac OS X that can be used to wrap arbitrary
-    Cocoa views (i.e., NSView subclasses) and insert them into Qt hierarchies.
-
-    \ingroup advanced
-
-    While Qt offers a lot of classes for writing your application, Apple's
-    Cocoa framework offers lots of functionality that is not currently in Qt or
-    may never end up in Qt. Using QMacCocoaViewContainer, it is possible to put an
-    arbitrary NSView-derived class from Cocoa and put it in a Qt hierarchy.
-    Depending on how comfortable you are with using objective-C, you can use
-    QMacCocoaViewContainer directly, or subclass it to wrap further functionality
-    of the underlying NSView.
-
-    QMacCocoaViewContainer works regardless if Qt is built against Carbon or
-    Cocoa. However, QCocoaContainerView requires Mac OS X 10.5 or better to be
-    used with Carbon.
-
-    It should be also noted that at the low level on Mac OS X, there is a
-    difference between windows (top-levels) and view (widgets that are inside a
-    window). For this reason, make sure that the NSView that you are wrapping
-    doesn't end up as a top-level. The best way to ensure this is to make sure
-    you always have a parent and not set the parent to 0.
-
-    If you are using QMacCocoaViewContainer as a sub-class and are mixing and
-    matching objective-C with C++ (a.k.a. objective-C++). It is probably
-    simpler to have your file end with \tt{.mm} than \tt{.cpp}. Most Apple tools will
-    correctly identify the source as objective-C++.
-
-    QMacCocoaViewContainer requires knowledge of how Cocoa works, especially in
-    regard to its reference counting (retain/release) nature. It is noted in
-    the functions below if there is any change in the reference count. Cocoa
-    views often generate temporary objects that are released by an autorelease
-    pool. If this is done outside of a running event loop, it is up to the
-    developer to provide the autorelease pool.
-
-    The following is a snippet of subclassing QMacCocoaViewContainer to wrap a NSSearchField.
-    \snippet demos/macmainwindow/macmainwindow.mm 0
-
-*/
-
-QT_BEGIN_NAMESPACE
-
-class QMacCocoaViewContainerPrivate : public QWidgetPrivate
-{
-    Q_DECLARE_PUBLIC(QMacCocoaViewContainer)
-public:
-    NSView *nsview;
-#ifndef QT_MAC_USE_COCOA
-    HIViewRef wrapperView;
-#endif
-    QMacCocoaViewContainerPrivate();
-    ~QMacCocoaViewContainerPrivate();
-};
-
-QMacCocoaViewContainerPrivate::QMacCocoaViewContainerPrivate()
-     : nsview(0)
-#ifndef QT_MAC_USE_COCOA
-       , wrapperView(0)
-#endif
-{
-}
-
-QMacCocoaViewContainerPrivate::~QMacCocoaViewContainerPrivate()
-{
-    [nsview release];
-#ifndef QT_MAC_USE_COCOA
-    if (wrapperView)
-        CFRelease(wrapperView);
-#endif
-}
-
-/*!
-    \fn QMacCocoaViewContainer::QMacCocoaViewContainer(void *cocoaViewToWrap, QWidget *parent)
-    Create a new QMacCocoaViewContainer using the NSView pointer in \a
-    cocoaViewToWrap with parent, \a parent. QMacCocoaViewContainer will
-    retain \a cocoaViewToWrap.
-
-    \a cocoaViewToWrap is a void pointer that allows the header to be included
-    with C++ source.
-*/
-QMacCocoaViewContainer::QMacCocoaViewContainer(void *cocoaViewToWrap, QWidget *parent)
-   : QWidget(*new QMacCocoaViewContainerPrivate, parent, 0)
-{
-    if (cocoaViewToWrap)
-        setCocoaView(cocoaViewToWrap);
-
-    // QMacCocoaViewContainer requires a native window handle.
-    setAttribute(Qt::WA_NativeWindow);
-}
-
-/*!
-    Destroy the QMacCocoaViewContainer and release the wrapped view.
-*/
-QMacCocoaViewContainer::~QMacCocoaViewContainer()
-{
-}
-
-/*!
-    Returns the NSView that has been set on this container.  The returned view
-    has been autoreleased, so you will need to retain it if you want to make
-    use of it.
-*/
-void *QMacCocoaViewContainer::cocoaView() const
-{
-    Q_D(const QMacCocoaViewContainer);
-    return [[d->nsview retain] autorelease];
-}
-
-/*!
-    Sets the NSView to contain to be \a cocoaViewToWrap and retains it. If this
-    container already had a view set, it will release the previously set view.
-*/
-void QMacCocoaViewContainer::setCocoaView(void *cocoaViewToWrap)
-{
-    Q_D(QMacCocoaViewContainer);
-    QMacCocoaAutoReleasePool pool;
-    NSView *view = static_cast<NSView *>(cocoaViewToWrap);
-    NSView *oldView = d->nsview;
-    destroy(true, true);
-    [view retain];
-    d->nsview = view;
-#ifndef QT_MAC_USE_COCOA
-    if (QSysInfo::MacintoshVersion < QSysInfo::MV_10_5) {
-        qWarning("QMacCocoaViewContainer::setCocoaView: You cannot use this class with Carbon on versions of Mac OS X less than 10.5.");
-        return;
-    }
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-    if (d->wrapperView)
-        CFRelease(d->wrapperView);
-    HICocoaViewCreate(d->nsview, 0, &d->wrapperView);
-    create(WId(d->wrapperView), false, true);
-#endif
-#else
-    create(WId(d->nsview), false, true);
-#endif
-    [oldView release];
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qmaccocoaviewcontainer_mac.h"
diff --git a/src/gui/widgets/qmacnativewidget_mac.h b/src/gui/widgets/qmacnativewidget_mac.h
deleted file mode 100644 (file)
index 267ae1c..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QMACNATIVEWIDGET_H
-#define QMACNATIVEWIDGET_H
-
-#include <QtGui/QWidget>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-
-class QMacNativeWidgetPrivate;
-class Q_GUI_EXPORT QMacNativeWidget : public QWidget
-{
-    Q_OBJECT
-public:
-    QMacNativeWidget(void *parentRef = 0);
-    ~QMacNativeWidget();
-
-    QSize sizeHint() const;
-
-protected:
-    bool event(QEvent *ev);
-
-private:
-    Q_DECLARE_PRIVATE(QMacNativeWidget)
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QMACNATIVEWIDGET_H
diff --git a/src/gui/widgets/qmacnativewidget_mac.mm b/src/gui/widgets/qmacnativewidget_mac.mm
deleted file mode 100644 (file)
index 5261f1f..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#import <Cocoa/Cocoa.h>
-#import <qcocoaview_mac_p.h>
-#include "qmacnativewidget_mac.h"
-#include <qwidget_p.h>
-
-/*!
-    \class QMacNativeWidget
-    \since 4.5
-    \brief The QMacNativeWidget class provides a widget for Mac OS X that provides a way to put Qt widgets into Carbon
-    or Cocoa hierarchies depending on how Qt was configured.
-
-    \ingroup advanced
-
-    On Mac OS X, there is a difference between a window and view;
-    normally expressed as widgets in Qt.  Qt makes assumptions about its
-    parent-child hierarchy that make it complex to put an arbitrary Qt widget
-    into a hierarchy of "normal" views from Apple frameworks. QMacNativeWidget
-    bridges the gap between views and windows and makes it possible to put a
-    hierarchy of Qt widgets into a non-Qt window or view.
-
-    QMacNativeWidget pretends it is a window (i.e. isWindow() will return true),
-    but it cannot be shown on its own. It needs to be put into a window
-    when it is created or later through a native call.
-
-    QMacNativeWidget works for either Carbon or Cocoa depending on how Qt was configured. If Qt is
-    using Carbon, QMacNativeWidget will embed into Carbon hierarchies. If Qt is
-    using Cocoa, QMacNativeWidget embeds into Cocoa hierarchies.
-
-    Here is an example of putting a QPushButton into a NSWindow:
-
-    \snippet doc/src/snippets/qmacnativewidget/main.mm 0
-
-    On Carbon, this would do the equivalent:
-
-    \snippet doc/src/snippets/qmacnativewidget/main.mm 1
-
-    Note that QMacNativeWidget requires knowledge of Carbon or Cocoa. All it
-    does is get the Qt hierarchy into a window not owned by Qt. It is then up
-    to the programmer to ensure it is placed correctly in the window and
-    responds correctly to events.
-*/
-
-QT_BEGIN_NAMESPACE
-
-class QMacNativeWidgetPrivate : public QWidgetPrivate
-{
-};
-
-extern OSViewRef qt_mac_create_widget(QWidget *widget, QWidgetPrivate *widgetPrivate, OSViewRef parent);
-
-
-/*!
-    Create a QMacNativeWidget with \a parentView as its "superview" (i.e.,
-    parent). The \a parentView is either an HIViewRef if Qt is using Carbon or
-    a NSView pointer if Qt is using Cocoa.
-*/
-QMacNativeWidget::QMacNativeWidget(void *parentView)
-    : QWidget(*new QMacNativeWidgetPrivate, 0, Qt::Window)
-{
-    Q_D(QMacNativeWidget);
-    OSViewRef myView = qt_mac_create_widget(this, d, OSViewRef(parentView));
-
-    d->topData()->embedded = true;
-    create(WId(myView), false, false);
-    setPalette(QPalette(Qt::transparent));
-    setAttribute(Qt::WA_SetPalette, false);
-    setAttribute(Qt::WA_LayoutUsesWidgetRect);
-}
-
-/*!
-    Destroy the QMacNativeWidget.
-*/
-QMacNativeWidget::~QMacNativeWidget()
-{
-}
-
-/*!
-    \reimp
-*/
-QSize QMacNativeWidget::sizeHint() const
-{
-    return QSize(200, 200);
-}
-/*!
-    \reimp
-*/
-bool QMacNativeWidget::event(QEvent *ev)
-{
-    return QWidget::event(ev);
-}
-
-QT_END_NAMESPACE
-
-#include "moc_qmacnativewidget_mac.h"
diff --git a/src/gui/widgets/qmainwindowlayout_mac.mm b/src/gui/widgets/qmainwindowlayout_mac.mm
deleted file mode 100644 (file)
index ff0dae8..0000000
+++ /dev/null
@@ -1,608 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qmainwindowlayout_p.h>
-#include <qtoolbar.h>
-#include <qtoolbarlayout_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <qtoolbar_p.h>
-
-#ifndef QT_MAC_USE_COCOA
-#include <Carbon/Carbon.h>
-#else
-#include <quuid.h>
-#include <qcocoatoolbardelegate_mac_p.h>
-#import  <qcocoawindowdelegate_mac_p.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-#ifdef QT_NAMESPACE
-
-// namespace up the stuff
-#define SS(x) #x
-#define S0(x) SS(x)
-#define S "com.trolltech.qt-" S0(QT_NAMESPACE) ".qmainwindow.qtoolbarInHIToolbar"
-#define SToolbar "com.trolltech.qt-" S0(QT_NAMESPACE) ".hitoolbar-qtoolbar"
-#define SNSToolbar "com.trolltech.qt-" S0(QT_NAMESPACE) ".qtoolbarInNSToolbar"
-#define MacToolbar "com.trolltech.qt-" S0(QT_NAMESPACE) ".qmainwindow.mactoolbar"
-
-#ifndef QT_MAC_USE_COCOA
-static CFStringRef kQToolBarHIToolbarItemClassID = CFSTR(S);
-static CFStringRef kQToolBarHIToolbarIdentifier = CFSTR(SToolbar);
-#else
-static NSString *kQToolBarNSToolbarIdentifier = @SNSToolbar;
-#endif
-static CFStringRef kQMainWindowMacToolbarID = CFSTR(MacToolbar);
-#undef SS
-#undef S0
-#undef S
-#undef SToolbar
-#undef SNSToolbar
-#undef MacToolbar
-
-#else
-#ifndef QT_MAC_USE_COCOA
-static CFStringRef kQToolBarHIToolbarItemClassID = CFSTR("com.trolltech.qt.qmainwindow.qtoolbarInHIToolbar");
-static CFStringRef kQToolBarHIToolbarIdentifier = CFSTR("com.trolltech.qt.hitoolbar-qtoolbar");
-#else
-static NSString *kQToolBarNSToolbarIdentifier = @"com.trolltech.qt.qmainwindow.qtoolbarInNSToolbar";
-#endif
-static CFStringRef kQMainWindowMacToolbarID = CFSTR("com.trolltech.qt.qmainwindow.mactoolbar");
-#endif // QT_NAMESPACE
-
-#ifndef QT_MAC_USE_COCOA
-
-static const int kEventParamQToolBar = 'QTBR';
-static const int kEventParamQMainWindowLayout = 'QMWL';
-
-const EventTypeSpec qtoolbarEvents[] =
-{
-    { kEventClassHIObject, kEventHIObjectConstruct },
-    { kEventClassHIObject, kEventHIObjectDestruct },
-    { kEventClassHIObject, kEventHIObjectInitialize },
-    { kEventClassToolbarItem, kEventToolbarItemCreateCustomView }
-};
-
-struct QToolBarInHIToolbarInfo
-{
-    QToolBarInHIToolbarInfo(HIToolbarItemRef item)
-        : toolbarItem(item), mainWindowLayout(0)
-    {}
-    HIToolbarItemRef toolbarItem;
-    QMainWindowLayout *mainWindowLayout;
-};
-
-OSStatus QMainWindowLayout::qtoolbarInHIToolbarHandler(EventHandlerCallRef inCallRef,
-                                                       EventRef event, void *data)
-{
-    OSStatus result = eventNotHandledErr;
-    QToolBarInHIToolbarInfo *object = static_cast<QToolBarInHIToolbarInfo *>(data);
-
-    switch (GetEventClass(event)) {
-        case kEventClassHIObject:
-            switch (GetEventKind(event)) {
-                case kEventHIObjectConstruct:
-                {
-                    HIObjectRef toolbarItem;
-                    GetEventParameter(event, kEventParamHIObjectInstance, typeHIObjectRef,
-                                      0, sizeof( HIObjectRef ), 0, &toolbarItem);
-
-                    QToolBarInHIToolbarInfo *item = new QToolBarInHIToolbarInfo(toolbarItem);
-                    SetEventParameter(event, kEventParamHIObjectInstance, typeVoidPtr,
-                                      sizeof(void *), &item);
-                    result = noErr;
-                }
-                    break;
-                case kEventHIObjectInitialize:
-                    result = CallNextEventHandler(inCallRef, event);
-                    if (result == noErr) {
-                        QToolBar *toolbar = 0;
-                        QMainWindowLayout *layout = 0;
-                        GetEventParameter(event, kEventParamQToolBar, typeVoidPtr,
-                                          0, sizeof(void *), 0, &toolbar);
-                        GetEventParameter(event, kEventParamQMainWindowLayout, typeVoidPtr,
-                                          0, sizeof(void *), 0, &layout);
-                        object->mainWindowLayout = layout;
-                        object->mainWindowLayout->unifiedToolbarHash.insert(object->toolbarItem, toolbar);
-                        HIToolbarItemChangeAttributes(object->toolbarItem,
-                                                      kHIToolbarItemLabelDisabled, 0);
-                    }
-                    break;
-
-                case kEventHIObjectDestruct:
-                    delete object;
-                    result = noErr;
-                    break;
-            }
-            break;
-
-        case kEventClassToolbarItem:
-            switch (GetEventKind(event))
-        {
-            case kEventToolbarItemCreateCustomView:
-            {
-                QToolBar *toolbar
-                = object->mainWindowLayout->unifiedToolbarHash.value(object->toolbarItem);
-                if (toolbar) {
-                    HIViewRef hiview = HIViewRef(toolbar->winId());
-                    SetEventParameter(event, kEventParamControlRef, typeControlRef,
-                                      sizeof(HIViewRef), &hiview);
-                    result = noErr;
-                }
-            }
-                break;
-        }
-            break;
-    }
-    return result;
-}
-
-void QMainWindowLayout::qtMacHIToolbarRegisterQToolBarInHIToolborItemClass()
-{
-    static bool registered = false;
-
-    if (!registered) {
-        HIObjectRegisterSubclass( kQToolBarHIToolbarItemClassID,
-                                 kHIToolbarItemClassID, 0, QMainWindowLayout::qtoolbarInHIToolbarHandler,
-                                 GetEventTypeCount(qtoolbarEvents), qtoolbarEvents, 0, 0 );
-        registered = true;
-    }
-}
-
-static void GetToolbarAllowedItems(CFMutableArrayRef array)
-{
-    CFArrayAppendValue(array, kQToolBarHIToolbarIdentifier);
-}
-
-HIToolbarItemRef QMainWindowLayout::createQToolBarInHIToolbarItem(QToolBar *toolbar,
-                                                                  QMainWindowLayout *layout)
-{
-    QMainWindowLayout::qtMacHIToolbarRegisterQToolBarInHIToolborItemClass();
-
-    EventRef event;
-    HIToolbarItemRef result = 0;
-
-    CFStringRef identifier = kQToolBarHIToolbarIdentifier;
-    UInt32 options = kHIToolbarItemAllowDuplicates;
-
-    CreateEvent(0, kEventClassHIObject, kEventHIObjectInitialize,
-                GetCurrentEventTime(), 0, &event);
-    SetEventParameter(event, kEventParamToolbarItemIdentifier, typeCFStringRef,
-                      sizeof(CFStringRef), &identifier);
-    SetEventParameter(event, kEventParamAttributes, typeUInt32, sizeof(UInt32), &options);
-    SetEventParameter(event, kEventParamQToolBar, typeVoidPtr, sizeof(void *), &toolbar);
-    SetEventParameter(event, kEventParamQMainWindowLayout, typeVoidPtr, sizeof(void *), &layout);
-
-    HIObjectCreate(kQToolBarHIToolbarItemClassID, event,
-                   static_cast<HIObjectRef *>(&result));
-
-    ReleaseEvent(event);
-    return result;
-
-}
-
-HIToolbarItemRef QMainWindowLayout::CreateToolbarItemForIdentifier(CFStringRef identifier,
-                                                                   CFTypeRef data)
-{
-    HIToolbarItemRef item = 0;
-    if (CFStringCompare(kQToolBarHIToolbarIdentifier, identifier,
-                        kCFCompareBackwards) == kCFCompareEqualTo) {
-        if (data && CFGetTypeID(data) == CFArrayGetTypeID()) {
-            CFArrayRef array = static_cast<CFArrayRef>(data);
-            QToolBar *toolbar = static_cast<QToolBar *>(const_cast<void *>(CFArrayGetValueAtIndex(array, 0)));
-            QMainWindowLayout *layout = static_cast<QMainWindowLayout *>(const_cast<void *>(CFArrayGetValueAtIndex(array, 1)));
-            item = createQToolBarInHIToolbarItem(toolbar, layout);
-        }
-    }
-    return item;
-}
-
-static const EventTypeSpec kToolbarEvents[] = {
-{ kEventClassToolbar, kEventToolbarGetDefaultIdentifiers },
-{ kEventClassToolbar, kEventToolbarGetAllowedIdentifiers },
-{ kEventClassToolbar, kEventToolbarCreateItemWithIdentifier },
-{ kEventClassToolbar, kEventToolbarItemAdded },
-{ kEventClassToolbar, kEventToolbarItemRemoved }
-};
-
-OSStatus QMainWindowLayout::qtmacToolbarDelegate(EventHandlerCallRef, EventRef event, void *data)
-{
-    QMainWindowLayout *mainWindowLayout = static_cast<QMainWindowLayout *>(data);
-    OSStatus            result = eventNotHandledErr;
-    CFMutableArrayRef   array;
-    CFStringRef         identifier;
-    switch (GetEventKind(event)) {
-        case kEventToolbarGetDefaultIdentifiers:
-        case kEventToolbarGetAllowedIdentifiers:
-            GetEventParameter(event, kEventParamMutableArray, typeCFMutableArrayRef, 0,
-                              sizeof(CFMutableArrayRef), 0, &array);
-            GetToolbarAllowedItems(array);
-            result = noErr;
-            break;
-        case kEventToolbarCreateItemWithIdentifier: {
-            HIToolbarItemRef item;
-            CFTypeRef data = 0;
-            OSStatus err = GetEventParameter(event, kEventParamToolbarItemIdentifier, typeCFStringRef,
-                                             0, sizeof(CFStringRef), 0, &identifier);
-            err = GetEventParameter(event, kEventParamToolbarItemConfigData, typeCFTypeRef,
-                                    0, sizeof(CFTypeRef), 0, &data);
-            item = CreateToolbarItemForIdentifier(identifier, data);
-            if (item) {
-                result = SetEventParameter(event, kEventParamToolbarItem, typeHIToolbarItemRef,
-                                           sizeof(HIToolbarItemRef), &item );
-            }
-            break;
-        }
-        case kEventToolbarItemAdded: {
-            // Double check that our "view" of the toolbar is similar.
-            HIToolbarItemRef item;
-            CFIndex index;
-            if (GetEventParameter(event, kEventParamToolbarItem, typeHIToolbarItemRef,
-                                  0, sizeof(HIToolbarItemRef), 0, &item) == noErr
-                && GetEventParameter(event, kEventParamIndex, typeCFIndex, 0,
-                                     sizeof(CFIndex), 0, &index) == noErr) {
-                CFRetain(item); // We will watch this until it's removed from the list (or bust).
-                mainWindowLayout->toolbarItemsCopy.insert(index, item);
-                QToolBar *toolbar = mainWindowLayout->unifiedToolbarHash.value(item);
-                if (toolbar) {
-                    int toolbarIndex = mainWindowLayout->qtoolbarsInUnifiedToolbarList.indexOf(toolbar);
-                    if (index != toolbarIndex) {
-                        // Dang, we must be out of sync, rebuild it from the "toolbarItemsCopy"
-                        mainWindowLayout->qtoolbarsInUnifiedToolbarList.clear();
-                        for (int i = 0; i < mainWindowLayout->toolbarItemsCopy.size(); ++i) {
-                            // This will either append the correct toolbar or an
-                            // null toolbar. This is fine because this list
-                            // is really only kept to make sure that things are but in the right order.
-                            mainWindowLayout->qtoolbarsInUnifiedToolbarList.append(
-                                                                                   mainWindowLayout->unifiedToolbarHash.value(mainWindowLayout->
-                                                                                                                              toolbarItemsCopy.at(i)));
-                        }
-                    }
-                }
-            }
-            break;
-        }
-        case kEventToolbarItemRemoved: {
-            HIToolbarItemRef item;
-            if (GetEventParameter(event, kEventParamToolbarItem, typeHIToolbarItemRef,
-                                  0, sizeof(HIToolbarItemRef), 0, &item) == noErr) {
-                mainWindowLayout->unifiedToolbarHash.remove(item);
-                for (int i = 0; i < mainWindowLayout->toolbarItemsCopy.size(); ++i) {
-                    if (mainWindowLayout->toolbarItemsCopy.at(i) == item) {
-                        // I know about it, so release it.
-                        mainWindowLayout->toolbarItemsCopy.removeAt(i);
-                        mainWindowLayout->qtoolbarsInUnifiedToolbarList.removeAt(i);
-                        CFRelease(item);
-                        break;
-                    }
-                }
-            }
-            break;
-        }
-    }
-    return result;
-}
-#endif // ! QT_MAC_USE_COCOA
-
-#ifndef kWindowUnifiedTitleAndToolbarAttribute
-#define kWindowUnifiedTitleAndToolbarAttribute (1 << 7)
-#endif
-
-void QMainWindowLayout::updateHIToolBarStatus()
-{
-    bool useMacToolbar = layoutState.mainWindow->unifiedTitleAndToolBarOnMac();
-#ifndef QT_MAC_USE_COCOA
-    if (useMacToolbar) {
-        ChangeWindowAttributes(qt_mac_window_for(layoutState.mainWindow),
-                               kWindowUnifiedTitleAndToolbarAttribute, 0);
-    } else {
-        ChangeWindowAttributes(qt_mac_window_for(layoutState.mainWindow),
-                               0, kWindowUnifiedTitleAndToolbarAttribute);
-    }
-#endif
-
-    layoutState.mainWindow->setUpdatesEnabled(false);  // reduces a little bit of flicker, not all though
-#if defined(QT_MAC_USE_COCOA)
-    QMacCocoaAutoReleasePool pool;
-    NSView *cView = [qt_mac_window_for(layoutState.mainWindow) contentView];
-    if (useMacToolbar) {
-        [cView setPostsFrameChangedNotifications:YES];
-        [[NSNotificationCenter defaultCenter] addObserver: [QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate]
-                                                 selector: @selector(syncContentViewFrame:)
-                                                     name: NSViewFrameDidChangeNotification
-                                                   object: cView];
-    }
-#endif
-    if (!useMacToolbar) {
-        macWindowToolbarShow(layoutState.mainWindow, false);
-        // Move everything out of the HIToolbar into the main toolbar.
-        while (!qtoolbarsInUnifiedToolbarList.isEmpty()) {
-            // Should shrink the list by one every time.
-            QToolBar *toolbar = qtoolbarsInUnifiedToolbarList.first();
-#if defined(QT_MAC_USE_COCOA)
-            unifiedSurface->removeToolbar(toolbar);
-#endif
-            layoutState.mainWindow->addToolBar(Qt::TopToolBarArea, toolbar);
-        }
-        macWindowToolbarSet(qt_mac_window_for(layoutState.mainWindow), 0);
-    } else {
-        QList<QToolBar *> toolbars = layoutState.mainWindow->findChildren<QToolBar *>();
-        for (int i = 0; i < toolbars.size(); ++i) {
-            QToolBar *toolbar = toolbars.at(i);
-            if (toolBarArea(toolbar) == Qt::TopToolBarArea) {
-                // Do this here, because we are in an in-between state.
-                removeWidget(toolbar);
-                layoutState.mainWindow->addToolBar(Qt::TopToolBarArea, toolbar);
-            }
-        }
-        syncUnifiedToolbarVisibility();
-    }
-#if defined(QT_MAC_USE_COCOA)
-    if (!useMacToolbar) {
-        [cView setPostsFrameChangedNotifications:NO];
-        [[NSNotificationCenter defaultCenter] removeObserver: [QT_MANGLE_NAMESPACE(QCocoaWindowDelegate) sharedDelegate]
-                                                        name: NSViewFrameDidChangeNotification
-                                                      object: cView];
-    }
-#endif
-    layoutState.mainWindow->setUpdatesEnabled(true);
-}
-
-void QMainWindowLayout::insertIntoMacToolbar(QToolBar *before, QToolBar *toolbar)
-{
-    // This layering could go on to one more level, but I decided to stop here.
-    // The HIToolbar and NSToolbar APIs are fairly similar as you will see.
-    if (toolbar == 0)
-        return;
-
-#if defined(QT_MAC_USE_COCOA)
-    // toolbar will now become native (if not already) since we need
-    // an nsview for it inside the corresponding NSToolbarItem.
-    // Setting isInUnifiedToolbar will (among other things) stop alien
-    // siblings from becoming native when this happends since the toolbar
-    // will not overlap with other children of the QMainWindow. NB: Switching
-    // unified toolbar off after this stage is not supported, as this means
-    // that either the menubar must be alien again, or the sibling must
-    // be backed by an nsview to protect from overlapping issues:
-    toolbar->d_func()->isInUnifiedToolbar = true;
-#endif
-
-    QToolBarLayout *toolbarLayout = static_cast<QToolBarLayout *>(toolbar->layout());
-    toolbarSaveState.insert(toolbar, ToolBarSaveState(toolbar->isMovable(), toolbar->maximumSize()));
-
-    if (toolbarLayout->hasExpandFlag() == false)
-        toolbar->setMaximumSize(toolbar->sizeHint());
-
-    toolbar->setMovable(false);
-    toolbarLayout->setUsePopupMenu(true);
-    // Make the toolbar a child of the mainwindow to avoid creating a window.
-    toolbar->setParent(layoutState.mainWindow);
-
-    toolbar->winId();  // Now create the OSViewRef.
-    layoutState.mainWindow->createWinId();
-
-    OSWindowRef window = qt_mac_window_for(layoutState.mainWindow);
-    int beforeIndex = qtoolbarsInUnifiedToolbarList.indexOf(before);
-    if (beforeIndex == -1)
-        beforeIndex = qtoolbarsInUnifiedToolbarList.size();
-
-    int toolbarIndex = qtoolbarsInUnifiedToolbarList.indexOf(toolbar);
-
-#ifndef QT_MAC_USE_COCOA
-    HIToolbarRef macToolbar = NULL;
-    if ((GetWindowToolbar(window, &macToolbar) == noErr) && !macToolbar) {
-        HIToolbarCreate(kQMainWindowMacToolbarID,
-                        kHIToolbarItemAllowDuplicates, &macToolbar);
-        InstallEventHandler(HIObjectGetEventTarget(static_cast<HIToolbarRef>(macToolbar)),
-                            QMainWindowLayout::qtmacToolbarDelegate, GetEventTypeCount(kToolbarEvents),
-                            kToolbarEvents, this, 0);
-        HIToolbarSetDisplaySize(macToolbar, kHIToolbarDisplaySizeNormal);
-        HIToolbarSetDisplayMode(macToolbar, kHIToolbarDisplayModeIconOnly);
-        macWindowToolbarSet(window, macToolbar);
-        if (layoutState.mainWindow->isVisible())
-            macWindowToolbarShow(layoutState.mainWindow, true);
-        CFRelease(macToolbar);
-    }
-#else
-    QMacCocoaAutoReleasePool pool;
-    NSToolbar *macToolbar = [window toolbar];
-    if (macToolbar == nil) {
-        macToolbar = [[NSToolbar alloc] initWithIdentifier:qt_mac_QStringToNSString(QUuid::createUuid().toString())];
-        [macToolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
-        [macToolbar setSizeMode:NSToolbarSizeModeRegular];
-        [macToolbar setDelegate:[[QT_MANGLE_NAMESPACE(QCocoaToolBarDelegate) alloc] initWithMainWindowLayout:this]];
-        [window setToolbar:macToolbar];
-        [macToolbar release];
-    }
-#endif
-    if (toolbarIndex != -1) {
-        qtoolbarsInUnifiedToolbarList.removeAt(toolbarIndex);
-#ifndef QT_MAC_USE_COCOA
-        HIToolbarRemoveItemAtIndex(macToolbar, toolbarIndex);
-#else
-        [macToolbar removeItemAtIndex:toolbarIndex];
-#endif
-    }
-    qtoolbarsInUnifiedToolbarList.insert(beforeIndex, toolbar);
-
-    // Adding to the unified toolbar surface for the raster engine.
-    if (layoutState.mainWindow->windowSurface()) {
-        QPoint offset(0, 0);
-        for (int i = 0; i < beforeIndex; ++i) {
-            offset.setX(offset.x() + qtoolbarsInUnifiedToolbarList.at(i)->size().width());
-        }
-#ifdef QT_MAC_USE_COCOA
-        unifiedSurface->insertToolbar(toolbar, offset);
-#endif // QT_MAC_USE_COCOA
-    }
-
-#ifndef QT_MAC_USE_COCOA
-    QCFType<HIToolbarItemRef> outItem;
-    const QObject *stupidArray[] = { toolbar, this };
-    QCFType<CFArrayRef> array = CFArrayCreate(0, reinterpret_cast<const void **>(&stupidArray),
-                                              2, 0);
-    HIToolbarCreateItemWithIdentifier(macToolbar, kQToolBarHIToolbarIdentifier,
-                                      array, &outItem);
-    HIToolbarInsertItemAtIndex(macToolbar, outItem, beforeIndex);
-#else
-    NSString *toolbarID = kQToolBarNSToolbarIdentifier;
-    toolbarID = [toolbarID stringByAppendingFormat:@"%p", toolbar];
-    cocoaItemIDToToolbarHash.insert(qt_mac_NSStringToQString(toolbarID), toolbar);
-    [macToolbar insertItemWithItemIdentifier:toolbarID atIndex:beforeIndex];
-#endif
-}
-
-#ifdef QT_MAC_USE_COCOA
-void QMainWindowLayout::updateUnifiedToolbarOffset()
-{
-    QPoint offset(0, 0);
-
-    for (int i = 1; i < qtoolbarsInUnifiedToolbarList.length(); ++i) {
-        offset.setX(offset.x() + qtoolbarsInUnifiedToolbarList.at(i - 1)->size().width());
-        qtoolbarsInUnifiedToolbarList.at(i)->d_func()->toolbar_offset = offset;
-    }
-}
-#endif // QT_MAC_USE_COCOA
-
-
-void QMainWindowLayout::removeFromMacToolbar(QToolBar *toolbar)
-{
-    QHash<void *, QToolBar *>::iterator it = unifiedToolbarHash.begin();
-    while (it != unifiedToolbarHash.end()) {
-        if (it.value() == toolbar) {
-            // Rescue our HIView and set it on the mainWindow again.
-            bool saveVisible = !toolbar->isHidden();
-            toolbar->setParent(0);
-            toolbar->setParent(parentWidget());
-            toolbar->setVisible(saveVisible);
-            ToolBarSaveState saveState = toolbarSaveState.value(toolbar);
-            static_cast<QToolBarLayout *>(toolbar->layout())->setUsePopupMenu(false);
-            toolbar->setMovable(saveState.movable);
-            toolbar->setMaximumSize(saveState.maximumSize);
-            toolbarSaveState.remove(toolbar);
-#ifndef QT_MAC_USE_COCOA
-            HIToolbarItemRef item = static_cast<HIToolbarItemRef>(it.key());
-            HIToolbarRemoveItemAtIndex(HIToolbarItemGetToolbar(item),
-                                       toolbarItemsCopy.indexOf(item));
-#else
-            NSToolbarItem *item = static_cast<NSToolbarItem *>(it.key());
-            [[qt_mac_window_for(layoutState.mainWindow->window()) toolbar]
-                removeItemAtIndex:toolbarItemsCopy.indexOf(item)];
-             unifiedToolbarHash.remove(item);
-             qtoolbarsInUnifiedToolbarList.removeAll(toolbar);
-#endif
-            break;
-        }
-        ++it;
-    }
-}
-
-void QMainWindowLayout::cleanUpMacToolbarItems()
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-#endif
-    for (int i = 0; i < toolbarItemsCopy.size(); ++i) {
-#ifdef QT_MAC_USE_COCOA
-        NSToolbarItem *item = static_cast<NSToolbarItem *>(toolbarItemsCopy.at(i));
-        [item setView:0];
-#endif
-        CFRelease(toolbarItemsCopy.at(i));
-    }
-    toolbarItemsCopy.clear();
-    unifiedToolbarHash.clear();
-
-#ifdef QT_MAC_USE_COCOA
-    OSWindowRef window = qt_mac_window_for(layoutState.mainWindow);
-    NSToolbar *macToolbar = [window toolbar];
-    if (macToolbar) {
-      [[macToolbar delegate] release];
-      [macToolbar setDelegate:nil];
-    }
-#endif
-}
-
-void QMainWindowLayout::fixSizeInUnifiedToolbar(QToolBar *tb) const
-{
-#ifdef QT_MAC_USE_COCOA
-    QHash<void *, QToolBar *>::const_iterator it = unifiedToolbarHash.constBegin();
-    NSToolbarItem *item = nil;
-    while (it != unifiedToolbarHash.constEnd()) {
-        if (tb == it.value()) {
-            item = static_cast<NSToolbarItem *>(it.key());
-            break;
-        }
-        ++it;
-    }
-    if (item) {
-        QMacCocoaAutoReleasePool pool;
-        QWidgetItem layoutItem(tb);
-        QSize size = layoutItem.maximumSize();
-        NSSize nssize = NSMakeSize(size.width(), size.height());
-        [item setMaxSize:nssize];
-        size = layoutItem.minimumSize();
-        nssize.width = size.width();
-        nssize.height = size.height();
-        [item setMinSize:nssize];
-    }
-#else
-    Q_UNUSED(tb);
-#endif
-}
-
-void QMainWindowLayout::syncUnifiedToolbarVisibility()
-{
-    if (blockVisiblityCheck)
-        return;
-
-    Q_ASSERT(layoutState.mainWindow->unifiedTitleAndToolBarOnMac());
-    bool show = false;
-    const int ToolBarCount = qtoolbarsInUnifiedToolbarList.count();
-    for (int i = 0; i < ToolBarCount; ++i) {
-        if (qtoolbarsInUnifiedToolbarList.at(i)->isVisible()) {
-            show = true;
-            break;
-        }
-    }
-    macWindowToolbarShow(layoutState.mainWindow, show);
-}
-
-QT_END_NAMESPACE
diff --git a/src/gui/widgets/qmenu_mac.mm b/src/gui/widgets/qmenu_mac.mm
deleted file mode 100644 (file)
index 2f5bba1..0000000
+++ /dev/null
@@ -1,2226 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmenu.h"
-#include "qhash.h"
-#include <qdebug.h>
-#include "qapplication.h"
-#include <qt_mac_p.h>
-#include "qregexp.h"
-#include "qmainwindow.h"
-#include "qdockwidget.h"
-#include "qtoolbar.h"
-#include "qevent.h"
-#include "qstyle.h"
-#include "qwidgetaction.h"
-#include "qmacnativewidget_mac.h"
-#include "qthread_p.h"
-
-#include <qapplication_p.h>
-#include <qcocoaapplication_mac_p.h>
-#include <qmenu_p.h>
-#include <qmenubar_p.h>
-#include <qcocoamenuloader_mac_p.h>
-#include <qcocoamenu_mac_p.h>
-#include <qt_cocoa_helpers_mac_p.h>
-#include <Cocoa/Cocoa.h>
-
-QT_BEGIN_NAMESPACE
-
-/*****************************************************************************
-  QMenu debug facilities
- *****************************************************************************/
-
-/*****************************************************************************
-  QMenu globals
- *****************************************************************************/
-bool qt_mac_no_menubar_merge = false;
-bool qt_mac_quit_menu_item_enabled = true;
-int qt_mac_menus_open_count = 0;
-
-static OSMenuRef qt_mac_create_menu(QWidget *w);
-
-#ifndef QT_MAC_USE_COCOA
-static uint qt_mac_menu_static_cmd_id = 'QT00';
-const UInt32 kMenuCreatorQt = 'cute';
-enum {
-    kMenuPropertyQAction = 'QAcT',
-    kMenuPropertyQWidget = 'QWId',
-    kMenuPropertyCausedQWidget = 'QCAU',
-    kMenuPropertyMergeMenu = 'QApP',
-    kMenuPropertyMergeList = 'QAmL',
-    kMenuPropertyWidgetActionWidget = 'QWid',
-    kMenuPropertyWidgetMenu = 'QWMe',
-
-    kHICommandAboutQt = 'AOQT',
-    kHICommandCustomMerge = 'AQt0'
-};
-#endif
-
-static struct {
-    QPointer<QMenuBar> qmenubar;
-    bool modal;
-} qt_mac_current_menubar = { 0, false };
-
-
-
-
-/*****************************************************************************
-  Externals
- *****************************************************************************/
-extern OSViewRef qt_mac_hiview_for(const QWidget *w); //qwidget_mac.cpp
-extern HIViewRef qt_mac_hiview_for(OSWindowRef w); //qwidget_mac.cpp
-extern IconRef qt_mac_create_iconref(const QPixmap &px); //qpixmap_mac.cpp
-extern QWidget * mac_keyboard_grabber; //qwidget_mac.cpp
-extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); //qapplication_xxx.cpp
-RgnHandle qt_mac_get_rgn(); //qregion_mac.cpp
-void qt_mac_dispose_rgn(RgnHandle r); //qregion_mac.cpp
-
-/*****************************************************************************
-  QMenu utility functions
- *****************************************************************************/
-bool qt_mac_watchingAboutToShow(QMenu *menu)
-{
-    return menu && menu->receivers(SIGNAL(aboutToShow()));
-}
-
-static int qt_mac_CountMenuItems(OSMenuRef menu)
-{
-    if (menu) {
-#ifndef QT_MAC_USE_COCOA
-        int ret = 0;
-        const int items = CountMenuItems(menu);
-        for(int i = 0; i < items; i++) {
-            MenuItemAttributes attr;
-            if (GetMenuItemAttributes(menu, i+1, &attr) == noErr &&
-               attr & kMenuItemAttrHidden)
-                continue;
-            ++ret;
-        }
-        return ret;
-#else
-        return [menu numberOfItems];
-#endif
-    }
-    return 0;
-}
-
-static quint32 constructModifierMask(quint32 accel_key)
-{
-    quint32 ret = 0;
-    const bool dontSwap = qApp->testAttribute(Qt::AA_MacDontSwapCtrlAndMeta);
-#ifndef QT_MAC_USE_COCOA
-    if ((accel_key & Qt::ALT) == Qt::ALT)
-        ret |= kMenuOptionModifier;
-    if ((accel_key & Qt::SHIFT) == Qt::SHIFT)
-        ret |= kMenuShiftModifier;
-    if (dontSwap) {
-        if ((accel_key & Qt::META) != Qt::META)
-            ret |= kMenuNoCommandModifier;
-        if ((accel_key & Qt::CTRL) == Qt::CTRL)
-            ret |= kMenuControlModifier;
-    } else {
-        if ((accel_key & Qt::CTRL) != Qt::CTRL)
-            ret |= kMenuNoCommandModifier;
-        if ((accel_key & Qt::META) == Qt::META)
-            ret |= kMenuControlModifier;
-    }
-#else
-    if ((accel_key & Qt::CTRL) == Qt::CTRL)
-        ret |= (dontSwap ? NSControlKeyMask : NSCommandKeyMask);
-    if ((accel_key & Qt::META) == Qt::META)
-        ret |= (dontSwap ? NSCommandKeyMask : NSControlKeyMask);
-    if ((accel_key & Qt::ALT) == Qt::ALT)
-        ret |= NSAlternateKeyMask;
-    if ((accel_key & Qt::SHIFT) == Qt::SHIFT)
-        ret |= NSShiftKeyMask;
-#endif
-    return ret;
-}
-
-static void cancelAllMenuTracking()
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
-    [mainMenu cancelTracking];
-    for (NSMenuItem *item in [mainMenu itemArray]) {
-        if ([item submenu]) {
-            [[item submenu] cancelTracking];
-        }
-    }
-#else
-    CancelMenuTracking(AcquireRootMenu(), true, 0);
-#endif
-}
-
-static bool actualMenuItemVisibility(const QMenuBarPrivate::QMacMenuBarPrivate *mbp,
-                                     const QMacMenuAction *action)
-{
-    bool visible = action->action->isVisible();
-    if (visible && action->action->text() == QString(QChar(0x14)))
-        return false;
-    if (visible && action->action->menu() && !action->action->menu()->actions().isEmpty() &&
-        !qt_mac_CountMenuItems(action->action->menu()->macMenu(mbp->apple_menu)) &&
-        !qt_mac_watchingAboutToShow(action->action->menu())) {
-        return false;
-    }
-    return visible;
-}
-
-#ifndef QT_MAC_USE_COCOA
-bool qt_mac_activate_action(MenuRef menu, uint command, QAction::ActionEvent action_e, bool by_accel)
-{
-    //fire event
-    QMacMenuAction *action = 0;
-    if (GetMenuCommandProperty(menu, command, kMenuCreatorQt, kMenuPropertyQAction, sizeof(action), 0, &action) != noErr) {
-        QMenuMergeList *list = 0;
-        GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                            sizeof(list), 0, &list);
-        if (!list && qt_mac_current_menubar.qmenubar && qt_mac_current_menubar.qmenubar->isNativeMenuBar()) {
-            MenuRef apple_menu = qt_mac_current_menubar.qmenubar->d_func()->mac_menubar->apple_menu;
-            GetMenuItemProperty(apple_menu, 0, kMenuCreatorQt, kMenuPropertyMergeList, sizeof(list), 0, &list);
-            if (list)
-                menu = apple_menu;
-        }
-        if (list) {
-            for(int i = 0; i < list->size(); ++i) {
-                QMenuMergeItem item = list->at(i);
-                if (item.command == command && item.action) {
-                    action = item.action;
-                    break;
-                }
-            }
-        }
-        if (!action)
-            return false;
-    }
-
-    if (action_e == QAction::Trigger && by_accel && action->ignore_accel) //no, not a real accel (ie tab)
-        return false;
-
-    // Unhighlight the highlighted menu item before triggering the action to
-    // prevent items from staying highlighted while a modal dialog is shown.
-    // This also fixed the problem that parentless modal dialogs leave
-    // the menu item highlighted (since the menu bar is cleared for these types of dialogs).
-    if (action_e == QAction::Trigger)
-        HiliteMenu(0);
-
-    action->action->activate(action_e);
-
-    //now walk up firing for each "caused" widget (like in the platform independent menu)
-    QWidget *caused = 0;
-    if (action_e == QAction::Hover && GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget, sizeof(caused), 0, &caused) == noErr) {
-        MenuRef caused_menu = 0;
-        if (QMenu *qmenu2 = qobject_cast<QMenu*>(caused))
-            caused_menu = qmenu2->macMenu();
-        else if (QMenuBar *qmenubar2 = qobject_cast<QMenuBar*>(caused))
-            caused_menu = qmenubar2->macMenu();
-        else
-            caused_menu = 0;
-        while(caused_menu) {
-            //fire
-            QWidget *widget = 0;
-            GetMenuItemProperty(caused_menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(widget), 0, &widget);
-            if (QMenu *qmenu = qobject_cast<QMenu*>(widget)) {
-                action->action->showStatusText(widget);
-                emit qmenu->hovered(action->action);
-            } else if (QMenuBar *qmenubar = qobject_cast<QMenuBar*>(widget)) {
-                action->action->showStatusText(widget);
-                emit qmenubar->hovered(action->action);
-                break; //nothing more..
-            }
-
-            //walk up
-            if (GetMenuItemProperty(caused_menu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget,
-                                    sizeof(caused), 0, &caused) != noErr)
-                break;
-            if (QMenu *qmenu2 = qobject_cast<QMenu*>(caused))
-                caused_menu = qmenu2->macMenu();
-            else if (QMenuBar *qmenubar2 = qobject_cast<QMenuBar*>(caused))
-                caused_menu = qmenubar2->macMenu();
-            else
-                caused_menu = 0;
-        }
-    }
-    return true;
-}
-
-//lookup a QMacMenuAction in a menu
-static int qt_mac_menu_find_action(MenuRef menu, MenuCommand cmd)
-{
-    MenuItemIndex ret_idx;
-    MenuRef ret_menu;
-    if (GetIndMenuItemWithCommandID(menu, cmd, 1, &ret_menu, &ret_idx) == noErr) {
-        if (ret_menu == menu)
-            return (int)ret_idx;
-    }
-    return -1;
-}
-static int qt_mac_menu_find_action(MenuRef menu, QMacMenuAction *action)
-{
-    return qt_mac_menu_find_action(menu, action->command);
-}
-
-typedef QMultiHash<OSMenuRef, EventHandlerRef> EventHandlerHash;
-Q_GLOBAL_STATIC(EventHandlerHash, menu_eventHandlers_hash)
-
-static EventTypeSpec widget_in_menu_events[] = {
-    { kEventClassMenu, kEventMenuMeasureItemWidth },
-    { kEventClassMenu, kEventMenuMeasureItemHeight },
-    { kEventClassMenu, kEventMenuDrawItem },
-    { kEventClassMenu, kEventMenuCalculateSize }
-};
-
-static OSStatus qt_mac_widget_in_menu_eventHandler(EventHandlerCallRef er, EventRef event, void *)
-{
-    UInt32 ekind = GetEventKind(event);
-    UInt32 eclass = GetEventClass(event);
-    OSStatus result = eventNotHandledErr;
-    switch (eclass) {
-    case kEventClassMenu:
-        switch (ekind) {
-        default:
-            break;
-        case kEventMenuMeasureItemWidth: {
-            MenuItemIndex item;
-            GetEventParameter(event, kEventParamMenuItemIndex, typeMenuItemIndex,
-                              0, sizeof(item), 0, &item);
-            OSMenuRef menu;
-            GetEventParameter(event, kEventParamDirectObject, typeMenuRef, 0, sizeof(menu), 0, &menu);
-            QWidget *widget;
-            if (GetMenuItemProperty(menu, item, kMenuCreatorQt, kMenuPropertyWidgetActionWidget,
-                                 sizeof(widget), 0, &widget) == noErr) {
-                short width = short(widget->sizeHint().width());
-                SetEventParameter(event, kEventParamMenuItemWidth, typeSInt16,
-                                  sizeof(short), &width);
-                result = noErr;
-            }
-            break; }
-        case kEventMenuMeasureItemHeight: {
-            MenuItemIndex item;
-            GetEventParameter(event, kEventParamMenuItemIndex, typeMenuItemIndex,
-                              0, sizeof(item), 0, &item);
-            OSMenuRef menu;
-            GetEventParameter(event, kEventParamDirectObject, typeMenuRef, 0, sizeof(menu), 0, &menu);
-            QWidget *widget;
-            if (GetMenuItemProperty(menu, item, kMenuCreatorQt, kMenuPropertyWidgetActionWidget,
-                                     sizeof(widget), 0, &widget) == noErr && widget) {
-                short height = short(widget->sizeHint().height());
-                SetEventParameter(event, kEventParamMenuItemHeight, typeSInt16,
-                                  sizeof(short), &height);
-                result = noErr;
-            }
-            break; }
-        case kEventMenuDrawItem:
-            result = noErr;
-            break;
-        case kEventMenuCalculateSize: {
-            result = CallNextEventHandler(er, event);
-            if (result == noErr) {
-                OSMenuRef menu;
-                GetEventParameter(event, kEventParamDirectObject, typeMenuRef, 0, sizeof(menu), 0, &menu);
-                HIViewRef content;
-                HIMenuGetContentView(menu, kThemeMenuTypePullDown, &content);
-                UInt16 count = CountMenuItems(menu);
-                for (MenuItemIndex i = 1; i <= count; ++i) {
-                    QWidget *widget;
-                    if (GetMenuItemProperty(menu, i, kMenuCreatorQt, kMenuPropertyWidgetActionWidget,
-                            sizeof(widget), 0, &widget) == noErr && widget) {
-                        RgnHandle itemRgn = qt_mac_get_rgn();
-                        GetControlRegion(content, i, itemRgn);
-
-                        Rect bounds;
-                        GetRegionBounds( itemRgn, &bounds );
-                        qt_mac_dispose_rgn(itemRgn);
-                        widget->setGeometry(bounds.left, bounds.top,
-                                            bounds.right - bounds.left, bounds.bottom - bounds.top);
-                    }
-                }
-            }
-            break; }
-        }
-    }
-    return result;
-}
-
-//handling of events for menurefs created by Qt..
-static EventTypeSpec menu_events[] = {
-    { kEventClassCommand, kEventCommandProcess },
-    { kEventClassMenu, kEventMenuTargetItem },
-    { kEventClassMenu, kEventMenuOpening },
-    { kEventClassMenu, kEventMenuClosed }
-};
-
-// Special case for kEventMenuMatchKey, see qt_mac_create_menu below.
-static EventTypeSpec menu_menu_events[] = {
-    { kEventClassMenu, kEventMenuMatchKey }
-};
-
-OSStatus qt_mac_menu_event(EventHandlerCallRef er, EventRef event, void *)
-{
-    QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData);
-
-    bool handled_event = true;
-    UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event);
-    switch(eclass) {
-    case kEventClassCommand:
-        if (ekind == kEventCommandProcess) {
-            UInt32 context;
-            GetEventParameter(event, kEventParamMenuContext, typeUInt32,
-                              0, sizeof(context), 0, &context);
-            HICommand cmd;
-            GetEventParameter(event, kEventParamDirectObject, typeHICommand,
-                              0, sizeof(cmd), 0, &cmd);
-            if (!mac_keyboard_grabber && (context & kMenuContextKeyMatching)) {
-                QMacMenuAction *action = 0;
-                if (GetMenuCommandProperty(cmd.menu.menuRef, cmd.commandID, kMenuCreatorQt,
-                                          kMenuPropertyQAction, sizeof(action), 0, &action) == noErr) {
-                    QWidget *widget = 0;
-                    if (qApp->activePopupWidget())
-                        widget = (qApp->activePopupWidget()->focusWidget() ?
-                                  qApp->activePopupWidget()->focusWidget() : qApp->activePopupWidget());
-                    else if (QApplicationPrivate::focus_widget)
-                        widget = QApplicationPrivate::focus_widget;
-                    if (widget) {
-                        int key = action->action->shortcut();
-                        QKeyEvent accel_ev(QEvent::ShortcutOverride, (key & (~Qt::KeyboardModifierMask)),
-                                           Qt::KeyboardModifiers(key & Qt::KeyboardModifierMask));
-                        accel_ev.ignore();
-                        qt_sendSpontaneousEvent(widget, &accel_ev);
-                        if (accel_ev.isAccepted()) {
-                            handled_event = false;
-                            break;
-                        }
-                    }
-                }
-            }
-            handled_event = qt_mac_activate_action(cmd.menu.menuRef, cmd.commandID,
-                                                   QAction::Trigger, context & kMenuContextKeyMatching);
-        }
-        break;
-    case kEventClassMenu: {
-        MenuRef menu;
-        GetEventParameter(event, kEventParamDirectObject, typeMenuRef, NULL, sizeof(menu), NULL, &menu);
-        if (ekind == kEventMenuMatchKey) {
-            // Don't activate any actions if we are showing a native modal dialog,
-            // the key events should go to the dialog in this case.
-            if (QApplicationPrivate::native_modal_dialog_active)
-                return menuItemNotFoundErr;
-
-             handled_event = false;
-        } else if (ekind == kEventMenuTargetItem) {
-            MenuCommand command;
-            GetEventParameter(event, kEventParamMenuCommand, typeMenuCommand,
-                              0, sizeof(command), 0, &command);
-            handled_event = qt_mac_activate_action(menu, command, QAction::Hover, false);
-        } else if (ekind == kEventMenuOpening || ekind == kEventMenuClosed) {
-            qt_mac_menus_open_count += (ekind == kEventMenuOpening) ? 1 : -1;
-            MenuRef mr;
-            GetEventParameter(event, kEventParamDirectObject, typeMenuRef,
-                              0, sizeof(mr), 0, &mr);
-
-            QWidget *widget = 0;
-            if (GetMenuItemProperty(mr, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(widget), 0, &widget) == noErr) {
-                if (QMenu *qmenu = qobject_cast<QMenu*>(widget)) {
-                    handled_event = true;
-                    if (ekind == kEventMenuOpening) {
-                        emit qmenu->aboutToShow();
-
-                        int merged = 0;
-                        const QMenuPrivate::QMacMenuPrivate *mac_menu = qmenu->d_func()->mac_menu;
-                        const int ActionItemsCount = mac_menu->actionItems.size();
-                        for(int i = 0; i < ActionItemsCount; ++i) {
-                            QMacMenuAction *action = mac_menu->actionItems.at(i);
-                            if (action->action->isSeparator()) {
-                                bool hide = false;
-                                if(!action->action->isVisible()) {
-                                    hide = true;
-                                } else if (merged && merged == i) {
-                                    hide = true;
-                                } else {
-                                    for(int l = i+1; l < mac_menu->actionItems.size(); ++l) {
-                                        QMacMenuAction *action = mac_menu->actionItems.at(l);
-                                        if (action->merged) {
-                                            hide = true;
-                                        } else if (action->action->isSeparator()) {
-                                            if (hide)
-                                                break;
-                                        } else if (!action->merged) {
-                                            hide = false;
-                                            break;
-                                        }
-                                    }
-                                }
-
-                                const int index = qt_mac_menu_find_action(mr, action);
-                                if (hide) {
-                                    ++merged;
-                                    ChangeMenuItemAttributes(mr, index, kMenuItemAttrHidden, 0);
-                                } else {
-                                    ChangeMenuItemAttributes(mr, index, 0, kMenuItemAttrHidden);
-                                }
-                            } else if (action->merged) {
-                                ++merged;
-                            }
-                        }
-                    } else {
-                        emit qmenu->aboutToHide();
-                    }
-                }
-            }
-        } else {
-            handled_event = false;
-        }
-        break; }
-    default:
-        handled_event = false;
-        break;
-    }
-    if (!handled_event) //let the event go through
-        return CallNextEventHandler(er, event);
-    return noErr; //we eat the event
-}
-static EventHandlerRef mac_menu_event_handler = 0;
-static EventHandlerUPP mac_menu_eventUPP = 0;
-static void qt_mac_cleanup_menu_event()
-{
-    if (mac_menu_event_handler) {
-        RemoveEventHandler(mac_menu_event_handler);
-        mac_menu_event_handler = 0;
-    }
-    if (mac_menu_eventUPP) {
-        DisposeEventHandlerUPP(mac_menu_eventUPP);
-        mac_menu_eventUPP = 0;
-    }
-}
-static inline void qt_mac_create_menu_event_handler()
-{
-    if (!mac_menu_event_handler) {
-        mac_menu_eventUPP = NewEventHandlerUPP(qt_mac_menu_event);
-        InstallEventHandler(GetApplicationEventTarget(), mac_menu_eventUPP,
-                            GetEventTypeCount(menu_events), menu_events, 0,
-                            &mac_menu_event_handler);
-        qAddPostRoutine(qt_mac_cleanup_menu_event);
-    }
-}
-
-
-//enabling of commands
-static void qt_mac_command_set_enabled(MenuRef menu, UInt32 cmd, bool b)
-{
-    if (cmd == kHICommandQuit)
-        qt_mac_quit_menu_item_enabled = b;
-
-    if (b) {
-        EnableMenuCommand(menu, cmd);
-        if (MenuRef dock_menu = GetApplicationDockTileMenu())
-            EnableMenuCommand(dock_menu, cmd);
-    } else {
-        DisableMenuCommand(menu, cmd);
-        if (MenuRef dock_menu = GetApplicationDockTileMenu())
-            DisableMenuCommand(dock_menu, cmd);
-    }
-}
-
-static bool qt_mac_auto_apple_menu(MenuCommand cmd)
-{
-    return (cmd == kHICommandPreferences || cmd == kHICommandQuit);
-}
-
-static void qt_mac_get_accel(quint32 accel_key, quint32 *modif, quint32 *key) {
-    if (modif) {
-        *modif = constructModifierMask(accel_key);
-    }
-
-    accel_key &= ~(Qt::MODIFIER_MASK | Qt::UNICODE_ACCEL);
-    if (key) {
-        *key = 0;
-        if (accel_key == Qt::Key_Return)
-            *key = kMenuReturnGlyph;
-        else if (accel_key == Qt::Key_Enter)
-            *key = kMenuEnterGlyph;
-        else if (accel_key == Qt::Key_Tab)
-            *key = kMenuTabRightGlyph;
-        else if (accel_key == Qt::Key_Backspace)
-            *key = kMenuDeleteLeftGlyph;
-        else if (accel_key == Qt::Key_Delete)
-            *key = kMenuDeleteRightGlyph;
-        else if (accel_key == Qt::Key_Escape)
-            *key = kMenuEscapeGlyph;
-        else if (accel_key == Qt::Key_PageUp)
-            *key = kMenuPageUpGlyph;
-        else if (accel_key == Qt::Key_PageDown)
-            *key = kMenuPageDownGlyph;
-        else if (accel_key == Qt::Key_Up)
-            *key = kMenuUpArrowGlyph;
-        else if (accel_key == Qt::Key_Down)
-            *key = kMenuDownArrowGlyph;
-        else if (accel_key == Qt::Key_Left)
-            *key = kMenuLeftArrowGlyph;
-        else if (accel_key == Qt::Key_Right)
-            *key = kMenuRightArrowGlyph;
-        else if (accel_key == Qt::Key_CapsLock)
-            *key = kMenuCapsLockGlyph;
-        else if (accel_key >= Qt::Key_F1 && accel_key <= Qt::Key_F15)
-            *key = (accel_key - Qt::Key_F1) + kMenuF1Glyph;
-        else if (accel_key == Qt::Key_Home)
-            *key = kMenuNorthwestArrowGlyph;
-        else if (accel_key == Qt::Key_End)
-            *key = kMenuSoutheastArrowGlyph;
-    }
-}
-#else // Cocoa
-static inline void syncNSMenuItemVisiblity(NSMenuItem *menuItem, bool actionVisibility)
-{
-    [menuItem setHidden:NO];
-    [menuItem setHidden:YES];
-    [menuItem setHidden:!actionVisibility];
-}
-
-static inline void syncNSMenuItemEnabled(NSMenuItem *menuItem, bool enabled)
-{
-    [menuItem setEnabled:NO];
-    [menuItem setEnabled:YES];
-    [menuItem setEnabled:enabled];
-}
-
-static inline void syncMenuBarItemsVisiblity(const QMenuBarPrivate::QMacMenuBarPrivate *mac_menubar)
-{
-    const QList<QMacMenuAction *> &menubarActions = mac_menubar->actionItems;
-    for (int i = 0; i < menubarActions.size(); ++i) {
-        const QMacMenuAction *action = menubarActions.at(i);
-        syncNSMenuItemVisiblity(action->menuItem, actualMenuItemVisibility(mac_menubar, action));
-    }
-}
-
-static inline QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *getMenuLoader()
-{
-    return [[NSApplication sharedApplication] QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)];
-}
-
-static NSMenuItem *createNSMenuItem(const QString &title)
-{
-    NSMenuItem *item = [[NSMenuItem alloc] 
-                         initWithTitle:qt_mac_QStringToNSString(title)
-                         action:@selector(qtDispatcherToQAction:) keyEquivalent:@""];
-    [item setTarget:nil];
-    return item;
-}
-#endif
-
-
-
-// helper that recurses into a menu structure and en/dis-ables them
-void qt_mac_set_modal_state_helper_recursive(OSMenuRef menu, OSMenuRef merge, bool on)
-{
-#ifndef QT_MAC_USE_COCOA
-    for (int i = 0; i < CountMenuItems(menu); i++) {
-        OSMenuRef submenu;
-        GetMenuItemHierarchicalMenu(menu, i+1, &submenu);
-        if (submenu != merge) {
-            if (submenu)
-                qt_mac_set_modal_state_helper_recursive(submenu, merge, on);
-            if (on)
-                DisableMenuItem(submenu, 0);
-            else
-                EnableMenuItem(submenu, 0);
-        }
-    }
-#else
-    bool modalWindowOnScreen = qApp->activeModalWidget() != 0;
-    for (NSMenuItem *item in [menu itemArray]) {
-        OSMenuRef submenu = [item submenu];
-        if (submenu != merge) {
-            if (submenu)
-                qt_mac_set_modal_state_helper_recursive(submenu, merge, on);
-            if (!on) {
-                // The item should follow what the QAction has.
-                if ([item tag]) {
-                    QAction *action = reinterpret_cast<QAction *>([item tag]);
-                    syncNSMenuItemEnabled(item, action->isEnabled());
-                } else {
-                    syncNSMenuItemEnabled(item, YES);
-                }
-                // We sneak in some extra code here to handle a menu problem:
-                // If there is no window on screen, we cannot set 'nil' as
-                // menu item target, because then cocoa will disable the item
-                // (guess it assumes that there will be no first responder to
-                // catch the trigger anyway?) OTOH, If we have a modal window,
-                // then setting the menu loader as target will make cocoa not
-                // deliver the trigger because the loader is then seen as modally
-                // shaddowed). So either way there are shortcomings. Instead, we
-                // decide the target as late as possible:
-                [item setTarget:modalWindowOnScreen ? nil : getMenuLoader()];
-            } else {
-                syncNSMenuItemEnabled(item, NO);
-            }
-        }
-    }
-#endif
-}
-
-//toggling of modal state
-static void qt_mac_set_modal_state(OSMenuRef menu, bool on)
-{
-#ifndef QT_MAC_USE_COCOA
-    OSMenuRef merge = 0;
-    GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu,
-            sizeof(merge), 0, &merge);
-
-    qt_mac_set_modal_state_helper_recursive(menu, merge, on);
-
-    UInt32 commands[] = { kHICommandQuit, kHICommandPreferences, kHICommandAbout, kHICommandAboutQt, 0 };
-    for(int c = 0; commands[c]; c++) {
-        bool enabled = !on;
-        if (enabled) {
-            QMacMenuAction *action = 0;
-            GetMenuCommandProperty(menu, commands[c], kMenuCreatorQt, kMenuPropertyQAction,
-                    sizeof(action), 0, &action);
-            if (!action && merge) {
-                GetMenuCommandProperty(merge, commands[c], kMenuCreatorQt, kMenuPropertyQAction,
-                        sizeof(action), 0, &action);
-                if (!action) {
-                    QMenuMergeList *list = 0;
-                    GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                            sizeof(list), 0, &list);
-                    for(int i = 0; list && i < list->size(); ++i) {
-                        QMenuMergeItem item = list->at(i);
-                        if (item.command == commands[c] && item.action) {
-                            action = item.action;
-                            break;
-                        }
-                    }
-                }
-            }
-
-            if (!action) {
-                if (commands[c] != kHICommandQuit)
-                    enabled = false;
-            } else {
-                enabled = action->action ? action->action->isEnabled() : 0;
-            }
-        }
-        qt_mac_command_set_enabled(menu, commands[c], enabled);
-    }
-#else
-    OSMenuRef merge = QMenuPrivate::mergeMenuHash.value(menu);
-    qt_mac_set_modal_state_helper_recursive(menu, merge, on);
-    // I'm ignoring the special items now, since they should get handled via a syncAction()
-#endif
-}
-
-bool qt_mac_menubar_is_open()
-{
-    return qt_mac_menus_open_count > 0;
-}
-
-QMacMenuAction::~QMacMenuAction()
-{
-#ifdef QT_MAC_USE_COCOA
-    [menu release];
-    // Update the menu item if this action still owns it. For some items
-    // (like 'Quit') ownership will be transferred between all menu bars...
-    if (action && action.data() == reinterpret_cast<QAction *>([menuItem tag])) {
-        QAction::MenuRole role = action->menuRole();
-        // Check if the item is owned by Qt, and should be hidden to keep it from causing
-        // problems. Do it for everything but the quit menu item since that should always
-        // be visible.
-        if (role > QAction::ApplicationSpecificRole && role < QAction::QuitRole) {
-            [menuItem setHidden:YES];
-        } else if (role == QAction::TextHeuristicRole
-                   && menuItem != [getMenuLoader() quitMenuItem]) {
-            [menuItem setHidden:YES];
-        }
-        [menuItem setTag:nil];
-    }
-    [menuItem release];
-#endif
-}
-
-#ifndef QT_MAC_USE_COCOA
-static MenuCommand qt_mac_menu_merge_action(MenuRef merge, QMacMenuAction *action)
-#else
-static NSMenuItem *qt_mac_menu_merge_action(OSMenuRef merge, QMacMenuAction *action)
-#endif
-{
-    if (qt_mac_no_menubar_merge || action->action->menu() || action->action->isSeparator()
-            || action->action->menuRole() == QAction::NoRole)
-        return 0;
-
-    QString t = qt_mac_removeMnemonics(action->action->text().toLower());
-    int st = t.lastIndexOf(QLatin1Char('\t'));
-    if (st != -1)
-        t.remove(st, t.length()-st);
-    t.replace(QRegExp(QString::fromLatin1("\\.*$")), QLatin1String("")); //no ellipses
-    //now the fun part
-#ifndef QT_MAC_USE_COCOA
-    MenuCommand ret = 0;
-#else
-    NSMenuItem *ret = 0;
-    QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-#endif
-    switch (action->action->menuRole()) {
-    case QAction::NoRole:
-        ret = 0;
-        break;
-    case QAction::ApplicationSpecificRole:
-#ifndef QT_MAC_USE_COCOA
-        {
-            QMenuMergeList *list = 0;
-            if (GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                        sizeof(list), 0, &list) == noErr && list) {
-                MenuCommand lastCustom = kHICommandCustomMerge;
-                for(int i = 0; i < list->size(); ++i) {
-                    QMenuMergeItem item = list->at(i);
-                    if (item.command == lastCustom)
-                        ++lastCustom;
-                }
-                ret = lastCustom;
-            } else {
-                // The list hasn't been created, so, must be the first one.
-                ret = kHICommandCustomMerge;
-            }
-        }
-#else
-        ret = [loader appSpecificMenuItem];
-#endif
-        break;
-    case QAction::AboutRole:
-#ifndef QT_MAC_USE_COCOA
-        ret = kHICommandAbout;
-#else
-        ret = [loader aboutMenuItem];
-#endif
-        break;
-    case QAction::AboutQtRole:
-#ifndef QT_MAC_USE_COCOA
-        ret = kHICommandAboutQt;
-#else
-        ret = [loader aboutQtMenuItem];
-#endif
-        break;
-    case QAction::QuitRole:
-#ifndef QT_MAC_USE_COCOA
-        ret = kHICommandQuit;
-#else
-        ret = [loader quitMenuItem];
-#endif
-        break;
-    case QAction::PreferencesRole:
-#ifndef QT_MAC_USE_COCOA
-        ret = kHICommandPreferences;
-#else
-        ret = [loader preferencesMenuItem];
-#endif
-        break;
-    case QAction::TextHeuristicRole: {
-        QString aboutString = QMenuBar::tr("About").toLower();
-        if (t.startsWith(aboutString) || t.endsWith(aboutString)) {
-            if (t.indexOf(QRegExp(QString::fromLatin1("qt$"), Qt::CaseInsensitive)) == -1) {
-#ifndef QT_MAC_USE_COCOA
-                ret = kHICommandAbout;
-#else
-                ret = [loader aboutMenuItem];
-#endif
-            } else {
-#ifndef QT_MAC_USE_COCOA
-                ret = kHICommandAboutQt;
-#else
-                ret = [loader aboutQtMenuItem];
-#endif
-            }
-        } else if (t.startsWith(QMenuBar::tr("Config").toLower())
-                   || t.startsWith(QMenuBar::tr("Preference").toLower())
-                   || t.startsWith(QMenuBar::tr("Options").toLower())
-                   || t.startsWith(QMenuBar::tr("Setting").toLower())
-                   || t.startsWith(QMenuBar::tr("Setup").toLower())) {
-#ifndef QT_MAC_USE_COCOA
-            ret = kHICommandPreferences;
-#else
-            ret = [loader preferencesMenuItem];
-#endif
-        } else if (t.startsWith(QMenuBar::tr("Quit").toLower())
-                   || t.startsWith(QMenuBar::tr("Exit").toLower())) {
-#ifndef QT_MAC_USE_COCOA
-            ret = kHICommandQuit;
-#else
-            ret = [loader quitMenuItem];
-#endif
-        }
-    }
-        break;
-    }
-
-#ifndef QT_MAC_USE_COCOA
-    QMenuMergeList *list = 0;
-    if (GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                           sizeof(list), 0, &list) == noErr && list) {
-        for(int i = 0; i < list->size(); ++i) {
-            QMenuMergeItem item = list->at(i);
-            if (item.command == ret && item.action)
-                return 0;
-        }
-    }
-
-    QAction *cmd_action = 0;
-    if (GetMenuCommandProperty(merge, ret, kMenuCreatorQt, kMenuPropertyQAction,
-                              sizeof(cmd_action), 0, &cmd_action) == noErr && cmd_action)
-        return 0; //already taken
-#else
-    if (QMenuMergeList *list = QMenuPrivate::mergeMenuItemsHash.value(merge)) {
-        for(int i = 0; i < list->size(); ++i) {
-            const QMenuMergeItem &item = list->at(i);
-            if (item.menuItem == ret && item.action)
-                return 0;
-        }
-    }
-
-#endif
-    return ret;
-}
-
-static QString qt_mac_menu_merge_text(QMacMenuAction *action)
-{
-    QString ret;
-    extern QString qt_mac_applicationmenu_string(int type);
-#ifdef QT_MAC_USE_COCOA
-    QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-#endif
-    if (action->action->menuRole() == QAction::ApplicationSpecificRole)
-        ret = action->action->text();
-#ifndef QT_MAC_USE_COCOA
-    else if (action->command == kHICommandAbout)
-        ret = qt_mac_applicationmenu_string(6).arg(qAppName());
-    else if (action->command == kHICommandAboutQt)
-        ret = QMenuBar::tr("About Qt");
-    else if (action->command == kHICommandPreferences)
-        ret = qt_mac_applicationmenu_string(4);
-    else if (action->command == kHICommandQuit)
-        ret = qt_mac_applicationmenu_string(5).arg(qAppName());
-#else
-    else if (action->menuItem == [loader aboutMenuItem]) {
-        ret = qt_mac_applicationmenu_string(6).arg(qAppName());
-    } else if (action->menuItem == [loader aboutQtMenuItem]) {
-        if (action->action->text() == QString("About Qt"))
-            ret = QMenuBar::tr("About Qt");
-        else
-            ret = action->action->text();
-    } else if (action->menuItem == [loader preferencesMenuItem]) {
-        ret = qt_mac_applicationmenu_string(4);
-    } else if (action->menuItem == [loader quitMenuItem]) {
-        ret = qt_mac_applicationmenu_string(5).arg(qAppName());
-    }
-#endif
-    return ret;
-}
-
-static QKeySequence qt_mac_menu_merge_accel(QMacMenuAction *action)
-{
-    QKeySequence ret;
-#ifdef QT_MAC_USE_COCOA
-    QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-#endif
-    if (action->action->menuRole() == QAction::ApplicationSpecificRole)
-        ret = action->action->shortcut();
-#ifndef QT_MAC_USE_COCOA
-    else if (action->command == kHICommandPreferences)
-        ret = QKeySequence(QKeySequence::Preferences);
-    else if (action->command == kHICommandQuit)
-        ret = QKeySequence(QKeySequence::Quit);
-#else
-    else if (action->menuItem == [loader preferencesMenuItem])
-        ret = QKeySequence(QKeySequence::Preferences);
-    else if (action->menuItem == [loader quitMenuItem])
-        ret = QKeySequence(QKeySequence::Quit);
-#endif
-    return ret;
-}
-
-void Q_GUI_EXPORT qt_mac_set_menubar_icons(bool b)
-{ QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus, !b); }
-void Q_GUI_EXPORT qt_mac_set_native_menubar(bool b)
-{  QApplication::instance()->setAttribute(Qt::AA_DontUseNativeMenuBar, !b); }
-void Q_GUI_EXPORT qt_mac_set_menubar_merge(bool b) { qt_mac_no_menubar_merge = !b; }
-
-/*****************************************************************************
-  QMenu bindings
- *****************************************************************************/
-QMenuPrivate::QMacMenuPrivate::QMacMenuPrivate() : menu(0)
-{
-}
-
-QMenuPrivate::QMacMenuPrivate::~QMacMenuPrivate()
-{
-#ifndef QT_MAC_USE_COCOA
-    for(QList<QMacMenuAction*>::Iterator it = actionItems.begin(); it != actionItems.end(); ++it) {
-        QMacMenuAction *action = (*it);
-        RemoveMenuCommandProperty(action->menu, action->command, kMenuCreatorQt, kMenuPropertyQAction);
-        if (action->merged) {
-            QMenuMergeList *list = 0;
-            GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                                sizeof(list), 0, &list);
-            for(int i = 0; list && i < list->size(); ) {
-                QMenuMergeItem item = list->at(i);
-                if (item.action == action)
-                    list->removeAt(i);
-                else
-                    ++i;
-            }
-        }
-        delete action;
-    }
-    if (menu) {
-        EventHandlerHash::iterator it = menu_eventHandlers_hash()->find(menu);
-        while (it != menu_eventHandlers_hash()->end() && it.key() == menu) {
-            RemoveEventHandler(it.value());
-            ++it;
-        }
-        menu_eventHandlers_hash()->remove(menu);
-        ReleaseMenu(menu);
-    }
-#else
-    QMacCocoaAutoReleasePool pool;
-    while (actionItems.size()) {
-        QMacMenuAction *action = actionItems.takeFirst();
-        if (QMenuMergeList *list = mergeMenuItemsHash.value(action->menu)) {
-            int i = 0;
-            while (i < list->size()) {
-                const QMenuMergeItem &item = list->at(i);
-                if (item.action == action)
-                    list->removeAt(i);
-                else
-                    ++i;
-            }
-        }
-        delete action;
-    }
-    mergeMenuHash.remove(menu);
-    mergeMenuItemsHash.remove(menu);
-    [menu release];
-#endif
-}
-
-void
-QMenuPrivate::QMacMenuPrivate::addAction(QAction *a, QMacMenuAction *before, QMenuPrivate *qmenu)
-{
-    QMacMenuAction *action = new QMacMenuAction;
-    action->action = a;
-    action->ignore_accel = 0;
-    action->merged = 0;
-    action->menu = 0;
-#ifndef QT_MAC_USE_COCOA
-    action->command = qt_mac_menu_static_cmd_id++;
-#endif
-    addAction(action, before, qmenu);
-}
-
-void
-QMenuPrivate::QMacMenuPrivate::addAction(QMacMenuAction *action, QMacMenuAction *before, QMenuPrivate *qmenu)
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    Q_UNUSED(qmenu);
-#endif
-    if (!action)
-        return;
-    int before_index = actionItems.indexOf(before);
-    if (before_index < 0) {
-        before = 0;
-        before_index = actionItems.size();
-    }
-    actionItems.insert(before_index, action);
-
-#ifndef QT_MAC_USE_COCOA
-    int index = qt_mac_menu_find_action(menu, action);
-#else
-    [menu retain];
-    [action->menu release];
-#endif
-    action->menu = menu;
-
-    /* When the action is considered a mergable action it
-       will stay that way, until removed.. */
-    if (!qt_mac_no_menubar_merge) {
-#ifndef QT_MAC_USE_COCOA
-        MenuRef merge = 0;
-        GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu,
-                            sizeof(merge), 0, &merge);
-#else
-        OSMenuRef merge = QMenuPrivate::mergeMenuHash.value(menu);
-#endif
-        if (merge) {
-#ifndef QT_MAC_USE_COCOA
-            if (MenuCommand cmd = qt_mac_menu_merge_action(merge, action)) {
-                action->merged = 1;
-                action->menu = merge;
-                action->command = cmd;
-                if (qt_mac_auto_apple_menu(cmd))
-                    index = 0; //no need
-
-                QMenuMergeList *list = 0;
-                if (GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                                       sizeof(list), 0, &list) != noErr || !list) {
-                    list = new QMenuMergeList;
-                    SetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                                        sizeof(list), &list);
-                }
-                list->append(QMenuMergeItem(cmd, action));
-            }
-#else
-            if (NSMenuItem *cmd = qt_mac_menu_merge_action(merge, action)) {
-                action->merged = 1;
-                [merge retain];
-                [action->menu release];
-                action->menu = merge;
-                [cmd retain];
-                [cmd setAction:@selector(qtDispatcherToQAction:)];
-                [cmd setTarget:nil];
-                [action->menuItem release];
-                action->menuItem = cmd;
-                QMenuMergeList *list = QMenuPrivate::mergeMenuItemsHash.value(merge);
-                if (!list) {
-                    list = new QMenuMergeList;
-                    QMenuPrivate::mergeMenuItemsHash.insert(merge, list);
-                }
-                list->append(QMenuMergeItem(cmd, action));
-            }
-#endif
-        }
-    }
-
-#ifdef QT_MAC_USE_COCOA
-    NSMenuItem *newItem = action->menuItem;
-#endif
-    if (
-#ifndef QT_MAC_USE_COCOA
-        index == -1
-#else
-        newItem == 0
-#endif
-       ) {
-#ifndef QT_MAC_USE_COCOA
-        index = before_index;
-        MenuItemAttributes attr = kMenuItemAttrAutoRepeat;
-#else
-        newItem = createNSMenuItem(action->action->text());
-        action->menuItem = newItem;
-#endif
-        if (before) {
-#ifndef QT_MAC_USE_COCOA
-            InsertMenuItemTextWithCFString(action->menu, 0, qMax(before_index, 0), attr, action->command);
-#else
-            [menu insertItem:newItem atIndex:qMax(before_index, 0)];
-#endif
-        } else {
-#ifndef QT_MAC_USE_COCOA
-            // Append the menu item to the menu. If it is a kHICommandAbout or a kHICommandAboutQt append
-            // a separator also (to get a separator above "Preferences"), but make sure that we don't
-            // add separators between two "about" items.
-
-            // Build a set of all commands that could possibly be before the separator.
-            QSet<MenuCommand> mergedItems;
-            mergedItems.insert(kHICommandAbout);
-            mergedItems.insert(kHICommandAboutQt);
-            mergedItems.insert(kHICommandCustomMerge);
-
-            QMenuMergeList *list = 0;
-            if (GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                        sizeof(list), 0, &list) == noErr && list) {
-                for (int i = 0; i < list->size(); ++i) {
-                    MenuCommand command = list->at(i).command;
-                    if (command > kHICommandCustomMerge) {
-                        mergedItems.insert(command);
-                    }
-                }
-            }
-
-            const int itemCount = CountMenuItems(action->menu);
-            MenuItemAttributes testattr;
-            GetMenuItemAttributes(action->menu, itemCount , &testattr);
-            if (mergedItems.contains(action->command)
-                 && (testattr & kMenuItemAttrSeparator)) {
-                InsertMenuItemTextWithCFString(action->menu, 0, qMax(itemCount - 1, 0), attr, action->command);
-                index = itemCount;
-            } else {
-                MenuItemIndex tmpIndex;
-                AppendMenuItemTextWithCFString(action->menu, 0, attr, action->command, &tmpIndex);
-                index = tmpIndex;
-                if (mergedItems.contains(action->command))
-                    AppendMenuItemTextWithCFString(action->menu, 0, kMenuItemAttrSeparator, 0, &tmpIndex);
-            }
-#else
-            [menu addItem:newItem];
-#endif
-        }
-
-        QWidget *widget = qmenu ? qmenu->widgetItems.value(action->action) : 0;
-        if (widget) {
-#ifndef QT_MAC_USE_COCOA
-            ChangeMenuAttributes(action->menu, kMenuAttrDoNotCacheImage, 0);
-            attr = kMenuItemAttrCustomDraw;
-            SetMenuItemProperty(action->menu, index, kMenuCreatorQt, kMenuPropertyWidgetActionWidget,
-                                sizeof(QWidget *), &widget);
-            HIViewRef content;
-            HIMenuGetContentView(action->menu, kThemeMenuTypePullDown, &content);
-
-            EventHandlerRef eventHandlerRef;
-            InstallMenuEventHandler(action->menu, qt_mac_widget_in_menu_eventHandler,
-                                    GetEventTypeCount(widget_in_menu_events),
-                                    widget_in_menu_events, 0, &eventHandlerRef);
-            menu_eventHandlers_hash()->insert(action->menu, eventHandlerRef);
-
-            QWidget *menuWidget = 0;
-            GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyWidgetMenu,
-                                sizeof(menuWidget), 0, &menuWidget);
-            if(!menuWidget) {
-                menuWidget = new QMacNativeWidget(content);
-                SetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyWidgetMenu,
-                                    sizeof(menuWidget), &menuWidget);
-                menuWidget->show();
-            }
-            widget->setParent(menuWidget);
-#else
-            QMacNativeWidget *container = new QMacNativeWidget(0);
-            container->resize(widget->sizeHint());
-            widget->setAttribute(Qt::WA_LayoutUsesWidgetRect);
-            widget->setParent(container);
-
-            NSView *containerView = qt_mac_nativeview_for(container);
-            [containerView setAutoresizesSubviews:YES];
-            [containerView setAutoresizingMask:NSViewWidthSizable];
-            [qt_mac_nativeview_for(widget) setAutoresizingMask:NSViewWidthSizable];
-
-            [newItem setView:containerView];
-            container->show();
-#endif
-            widget->show();
-        }
-
-    } else {
-#ifndef QT_MAC_USE_COCOA
-        qt_mac_command_set_enabled(action->menu, action->command, !QApplicationPrivate::modalState());
-#else
-        [newItem setEnabled:!QApplicationPrivate::modalState()];
-#endif
-    }
-#ifndef QT_MAC_USE_COCOA
-    SetMenuCommandProperty(action->menu, action->command, kMenuCreatorQt, kMenuPropertyQAction,
-                           sizeof(action), &action);
-#else
-    [newItem setTag:long(static_cast<QAction *>(action->action))];
-#endif
-    syncAction(action);
-}
-
-// return an autoreleased string given a QKeySequence (currently only looks at the first one).
-NSString *keySequenceToKeyEqivalent(const QKeySequence &accel)
-{
-    quint32 accel_key = (accel[0] & ~(Qt::MODIFIER_MASK | Qt::UNICODE_ACCEL));
-    extern QChar qtKey2CocoaKey(Qt::Key key);
-    QChar cocoa_key = qtKey2CocoaKey(Qt::Key(accel_key));
-    if (cocoa_key.isNull())
-        cocoa_key = QChar(accel_key).toLower().unicode();
-    return [NSString stringWithCharacters:&cocoa_key.unicode() length:1];
-}
-
-// return the cocoa modifier mask for the QKeySequence (currently only looks at the first one).
-NSUInteger keySequenceModifierMask(const QKeySequence &accel)
-{
-    return constructModifierMask(accel[0]);
-}
-
-void
-QMenuPrivate::QMacMenuPrivate::syncAction(QMacMenuAction *action)
-{
-    if (!action)
-        return;
-
-#ifndef QT_MAC_USE_COCOA
-    const int index = qt_mac_menu_find_action(action->menu, action);
-    if (index == -1)
-        return;
-#else
-    NSMenuItem *item = action->menuItem;
-    if (!item)
-        return;
-#endif
-
-#ifndef QT_MAC_USE_COCOA
-    if (!action->action->isVisible()) {
-        ChangeMenuItemAttributes(action->menu, index, kMenuItemAttrHidden, 0);
-        return;
-    }
-    ChangeMenuItemAttributes(action->menu, index, 0, kMenuItemAttrHidden);
-#else
-    QMacCocoaAutoReleasePool pool;
-    NSMenu *menu = [item menu];
-    bool actionVisible = action->action->isVisible();
-    [item setHidden:!actionVisible];
-    if (!actionVisible)
-        return;
-#endif
-
-#ifndef QT_MAC_USE_COCOA
-    if (action->action->isSeparator()) {
-        ChangeMenuItemAttributes(action->menu, index, kMenuItemAttrSeparator, 0);
-        return;
-    }
-    ChangeMenuItemAttributes(action->menu, index, 0, kMenuItemAttrSeparator);
-#else
-    int itemIndex = [menu indexOfItem:item];
-    Q_ASSERT(itemIndex != -1);
-    if (action->action->isSeparator()) {
-        action->menuItem = [NSMenuItem separatorItem];
-        [action->menuItem retain];
-        [menu insertItem: action->menuItem atIndex:itemIndex];
-        [menu removeItem:item];
-        [item release];
-        item = action->menuItem;
-        return;
-    } else if ([item isSeparatorItem]) {
-        // I'm no longer a separator...
-        action->menuItem = createNSMenuItem(action->action->text());
-        [menu insertItem:action->menuItem atIndex:itemIndex];
-        [menu removeItem:item];
-        [item release];
-        item = action->menuItem;
-    }
-#endif
-
-    //find text (and accel)
-    action->ignore_accel = 0;
-    QString text = action->action->text();
-    QKeySequence accel = action->action->shortcut();
-    {
-        int st = text.lastIndexOf(QLatin1Char('\t'));
-        if (st != -1) {
-            action->ignore_accel = 1;
-            accel = QKeySequence(text.right(text.length()-(st+1)));
-            text.remove(st, text.length()-st);
-        }
-    }
-    {
-        QString cmd_text = qt_mac_menu_merge_text(action);
-        if (!cmd_text.isEmpty()) {
-            text = cmd_text;
-            accel = qt_mac_menu_merge_accel(action);
-        }
-    }
-    // Show multiple key sequences as part of the menu text.
-    if (accel.count() > 1)
-        text += QLatin1String(" (") + accel.toString(QKeySequence::NativeText) + QLatin1String(")");
-
-    QString finalString = qt_mac_removeMnemonics(text);
-
-#ifndef QT_MAC_USE_COCOA
-    MenuItemDataRec data;
-    memset(&data, '\0', sizeof(data));
-
-    //Carbon text
-    data.whichData |= kMenuItemDataCFString;
-    QCFString cfstring(finalString);  // Hold the reference to the end of the function.
-    data.cfText = cfstring;
-
-    // Carbon enabled
-    data.whichData |= kMenuItemDataEnabled;
-    data.enabled = action->action->isEnabled();
-    // Carbon icon
-    data.whichData |= kMenuItemDataIconHandle;
-    if (!action->action->icon().isNull()
-            && action->action->isIconVisibleInMenu()) {
-        data.iconType = kMenuIconRefType;
-        data.iconHandle = (Handle)qt_mac_create_iconref(action->action->icon().pixmap(16, QIcon::Normal));
-    } else {
-        data.iconType = kMenuNoIcon;
-    }
-    if (action->action->font().resolve()) { // Carbon font
-        if (action->action->font().bold())
-            data.style |= bold;
-        if (action->action->font().underline())
-            data.style |= underline;
-        if (action->action->font().italic())
-            data.style |= italic;
-        if (data.style)
-            data.whichData |= kMenuItemDataStyle;
-        data.whichData |= kMenuItemDataFontID;
-        data.fontID = action->action->font().macFontID();
-    }
-#else
-    // Cocoa Font and title
-    if (action->action->font().resolve()) {
-        const QFont &actionFont = action->action->font();
-        NSFont *customMenuFont = [NSFont fontWithName:qt_mac_QStringToNSString(actionFont.family())
-                                  size:actionFont.pointSize()];
-        NSArray *keys = [NSArray arrayWithObjects:NSFontAttributeName, nil];
-        NSArray *objects = [NSArray arrayWithObjects:customMenuFont, nil];
-        NSDictionary *attributes = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
-        NSAttributedString *str = [[[NSAttributedString alloc] initWithString:qt_mac_QStringToNSString(finalString)
-                                 attributes:attributes] autorelease];
-       [item setAttributedTitle: str];
-    } else {
-        [item setTitle: qt_mac_QStringToNSString(finalString)];
-    }
-
-    if (action->action->menuRole() == QAction::AboutRole || action->action->menuRole() == QAction::QuitRole)
-        [item setTitle:qt_mac_QStringToNSString(text)];
-    else
-        [item setTitle:qt_mac_QStringToNSString(qt_mac_removeMnemonics(text))];
-
-    // Cocoa Enabled
-    [item setEnabled: action->action->isEnabled()];
-
-    // Cocoa icon
-    NSImage *nsimage = 0;
-    if (!action->action->icon().isNull() && action->action->isIconVisibleInMenu()) {
-        nsimage = static_cast<NSImage *>(qt_mac_create_nsimage(action->action->icon().pixmap(16, QIcon::Normal)));
-    }
-    [item setImage:nsimage];
-    [nsimage release];
-#endif
-
-    if (action->action->menu()) { //submenu
-#ifndef QT_MAC_USE_COCOA
-        data.whichData |= kMenuItemDataSubmenuHandle;
-        data.submenuHandle = action->action->menu()->macMenu();
-        QWidget *caused = 0;
-        GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(caused), 0, &caused);
-        SetMenuItemProperty(data.submenuHandle, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget, sizeof(caused), &caused);
-#else
-        NSMenu *subMenu  = static_cast<NSMenu *>(action->action->menu()->macMenu());
-        if ([subMenu supermenu] && [subMenu supermenu] != [item menu]) {
-            // The menu is already a sub-menu of another one. Cocoa will throw an exception,
-            // in such cases. For the time being, a new QMenu with same set of actions is the
-            // only workaround.
-            action->action->setEnabled(false);
-        } else {
-            [item setSubmenu:subMenu];
-        }
-        [item setAction:nil];
-#endif
-    } else { //respect some other items
-#ifndef QT_MAC_USE_COCOA
-        //shortcuts (say we are setting them all so that we can also clear them).
-        data.whichData |= kMenuItemDataCmdKey;
-        data.whichData |= kMenuItemDataCmdKeyModifiers;
-        data.whichData |= kMenuItemDataCmdKeyGlyph;
-        if (accel.count() == 1) {
-            qt_mac_get_accel(accel[0], (quint32*)&data.cmdKeyModifiers, (quint32*)&data.cmdKeyGlyph);
-            if (data.cmdKeyGlyph == 0)
-                data.cmdKey = (UniChar)accel[0];
-        }
-#else
-        [item setSubmenu:0];
-        if ([item action] == nil)
-            [item setAction:@selector(qtDispatcherToQAction:)];
-        // No key equivalent set for multiple key QKeySequence.
-        if (accel.count() == 1) {
-            [item setKeyEquivalent:keySequenceToKeyEqivalent(accel)];
-            [item setKeyEquivalentModifierMask:keySequenceModifierMask(accel)];
-        } else {
-            [item setKeyEquivalent:@""];
-            [item setKeyEquivalentModifierMask:NSCommandKeyMask];
-        }
-#endif
-    }
-#ifndef QT_MAC_USE_COCOA
-    //mark glyph
-    data.whichData |= kMenuItemDataMark;
-    if (action->action->isChecked()) {
-#if 0
-        if (action->action->actionGroup() &&
-           action->action->actionGroup()->isExclusive())
-            data.mark = diamondMark;
-        else
-#endif
-            data.mark = checkMark;
-    } else {
-        data.mark = noMark;
-    }
-
-    //actually set it
-    SetMenuItemData(action->menu, action->command, true, &data);
-
-    // Free up memory
-    if (data.iconHandle)
-        ReleaseIconRef(IconRef(data.iconHandle));
-#else
-    //mark glyph
-    [item setState:action->action->isChecked() ?  NSOnState : NSOffState];
-#endif
-}
-
-void
-QMenuPrivate::QMacMenuPrivate::removeAction(QMacMenuAction *action)
-{
-    if (!action)
-        return;
-#ifndef QT_MAC_USE_COCOA
-    if (action->command == kHICommandQuit || action->command == kHICommandPreferences)
-        qt_mac_command_set_enabled(action->menu, action->command, false);
-    else
-        DeleteMenuItem(action->menu, qt_mac_menu_find_action(action->menu, action));
-#else
-    QMacCocoaAutoReleasePool pool;
-    if (action->merged) {
-        if (reinterpret_cast<QAction *>([action->menuItem tag]) == action->action) {
-            QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-            [action->menuItem setEnabled:false];
-            if (action->menuItem != [loader quitMenuItem]
-                && action->menuItem != [loader preferencesMenuItem]) {
-                [[action->menuItem menu] removeItem:action->menuItem];
-            }
-            if (QMenuMergeList *list = mergeMenuItemsHash.value(action->menu)) {
-                int i = 0;
-                while (i < list->size()) {
-                    const QMenuMergeItem &item = list->at(i);
-                    if (item.action == action)
-                        list->removeAt(i);
-                    else
-                        ++i;
-                }
-            }
-        }
-    } else {
-        [[action->menuItem menu] removeItem:action->menuItem];
-    }
-#endif
-    actionItems.removeAll(action);
-}
-
-OSMenuRef
-QMenuPrivate::macMenu(OSMenuRef merge)
-{
-    Q_UNUSED(merge);
-    Q_Q(QMenu);
-    if (mac_menu && mac_menu->menu)
-        return mac_menu->menu;
-    if (!mac_menu)
-        mac_menu = new QMacMenuPrivate;
-    mac_menu->menu = qt_mac_create_menu(q);
-    if (merge) {
-#ifndef QT_MAC_USE_COCOA
-        SetMenuItemProperty(mac_menu->menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu, sizeof(merge), &merge);
-#else
-        mergeMenuHash.insert(mac_menu->menu, merge);
-#endif
-    }
-    QList<QAction*> items = q->actions();
-    for(int i = 0; i < items.count(); i++)
-        mac_menu->addAction(items[i], 0, this);
-    syncSeparatorsCollapsible(collapsibleSeparators);
-    return mac_menu->menu;
-}
-
-/*!
-  \internal
-*/
-void
-QMenuPrivate::syncSeparatorsCollapsible(bool collapse)
-{
-#ifndef QT_MAC_USE_COCOA
-    if (collapse)
-        ChangeMenuAttributes(mac_menu->menu, kMenuAttrCondenseSeparators, 0);
-    else
-        ChangeMenuAttributes(mac_menu->menu, 0, kMenuAttrCondenseSeparators);
-#else
-    qt_mac_menu_collapseSeparators(mac_menu->menu, collapse);
-#endif
-}
-
-
-
-#ifndef QT_MAC_USE_COCOA
-/*!
-  \internal
-*/
-void QMenuPrivate::setMacMenuEnabled(bool enable)
-{
-    if (!macMenu(0))
-        return;
-
-    QMacCocoaAutoReleasePool pool;
-    if (enable) {
-        for (int i = 0; i < mac_menu->actionItems.count(); ++i) {
-            QMacMenuAction *menuItem = mac_menu->actionItems.at(i);
-            if (menuItem && menuItem->action && menuItem->action->isEnabled()) {
-                // Only enable those items which contains an enabled QAction.
-                // i == 0 -> the menu itself, hence i + 1 for items.
-                EnableMenuItem(mac_menu->menu, i + 1);
-            }
-        }
-    } else {
-        DisableAllMenuItems(mac_menu->menu);
-    }
-}
-#endif
-
-/*!
-    \internal
-
-    This function will return the OSMenuRef used to create the native menu bar
-    bindings.
-
-    If Qt is built against Carbon, the OSMenuRef is a MenuRef that can be used
-    with Carbon's Menu Manager API.
-
-    If Qt is built against Cocoa, the OSMenuRef is a NSMenu pointer.
-
-    \warning This function is not portable.
-
-    \sa QMenuBar::macMenu()
-*/
-OSMenuRef QMenu::macMenu(OSMenuRef merge) { return d_func()->macMenu(merge); }
-
-/*****************************************************************************
-  QMenuBar bindings
- *****************************************************************************/
-typedef QHash<QWidget *, QMenuBar *> MenuBarHash;
-Q_GLOBAL_STATIC(MenuBarHash, menubars)
-static QMenuBar *fallback = 0;
-QMenuBarPrivate::QMacMenuBarPrivate::QMacMenuBarPrivate() : menu(0), apple_menu(0)
-{
-}
-
-QMenuBarPrivate::QMacMenuBarPrivate::~QMacMenuBarPrivate()
-{
-    for(QList<QMacMenuAction*>::Iterator it = actionItems.begin(); it != actionItems.end(); ++it)
-        delete (*it);
-#ifndef QT_MAC_USE_COCOA
-    if (apple_menu) {
-        QMenuMergeList *list = 0;
-        GetMenuItemProperty(apple_menu, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                            sizeof(list), 0, &list);
-        if (list) {
-            RemoveMenuItemProperty(apple_menu, 0, kMenuCreatorQt, kMenuPropertyMergeList);
-            delete list;
-        }
-        ReleaseMenu(apple_menu);
-    }
-    if (menu)
-        ReleaseMenu(menu);
-#else
-    [apple_menu release];
-    [menu release];
-#endif
-}
-
-void
-QMenuBarPrivate::QMacMenuBarPrivate::addAction(QAction *a, QAction *before)
-{
-    if (a->isSeparator() || !menu)
-        return;
-    QMacMenuAction *action = new QMacMenuAction;
-    action->action = a;
-    action->ignore_accel = 1;
-#ifndef QT_MAC_USE_COCOA
-    action->command = qt_mac_menu_static_cmd_id++;
-#endif
-    addAction(action, findAction(before));
-}
-
-void
-QMenuBarPrivate::QMacMenuBarPrivate::addAction(QMacMenuAction *action, QMacMenuAction *before)
-{
-    if (!action || !menu)
-        return;
-
-    int before_index = actionItems.indexOf(before);
-    if (before_index < 0) {
-        before = 0;
-        before_index = actionItems.size();
-    }
-    actionItems.insert(before_index, action);
-
-    MenuItemIndex index = actionItems.size()-1;
-
-    action->menu = menu;
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    [action->menu retain];
-    NSMenuItem *newItem = createNSMenuItem(action->action->text());
-    action->menuItem = newItem;
-#endif
-    if (before) {
-#ifndef QT_MAC_USE_COCOA
-        InsertMenuItemTextWithCFString(action->menu, 0, qMax(1, before_index+1), 0, action->command);
-#else
-        [menu insertItem:newItem atIndex:qMax(1, before_index + 1)];
-#endif
-        index = before_index;
-    } else {
-#ifndef QT_MAC_USE_COCOA
-        AppendMenuItemTextWithCFString(action->menu, 0, 0, action->command, &index);
-#else
-        [menu addItem:newItem];
-#endif
-    }
-#ifndef QT_MAC_USE_COCOA
-    SetMenuItemProperty(action->menu, index, kMenuCreatorQt, kMenuPropertyQAction, sizeof(action),
-                        &action);
-#else
-    [newItem setTag:long(static_cast<QAction *>(action->action))];
-#endif
-    syncAction(action);
-}
-
-void
-QMenuBarPrivate::QMacMenuBarPrivate::syncAction(QMacMenuAction *action)
-{
-    if (!action || !menu)
-        return;
-#ifndef QT_MAC_USE_COCOA
-    const int index = qt_mac_menu_find_action(action->menu, action);
-#else
-    QMacCocoaAutoReleasePool pool;
-    NSMenuItem *item = action->menuItem;
-#endif
-
-    OSMenuRef submenu = 0;
-    bool release_submenu = false;
-    if (action->action->menu()) {
-        if ((submenu = action->action->menu()->macMenu(apple_menu))) {
-#ifndef QT_MAC_USE_COCOA
-            QWidget *caused = 0;
-            GetMenuItemProperty(action->menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(caused), 0, &caused);
-            SetMenuItemProperty(submenu, 0, kMenuCreatorQt, kMenuPropertyCausedQWidget, sizeof(caused), &caused);
-#else
-            if ([submenu supermenu] && [submenu supermenu] != [item menu])
-                return;
-            else
-                [item setSubmenu:submenu];
-#endif
-        }
-#ifndef QT_MAC_USE_COCOA
-    } else { // create a submenu to act as menu
-        release_submenu = true;
-        CreateNewMenu(0, 0, &submenu);
-#endif
-    }
-
-    if (submenu) {
-        bool visible = actualMenuItemVisibility(this, action);
-#ifndef QT_MAC_USE_COCOA
-        SetMenuItemHierarchicalMenu(action->menu, index, submenu);
-        SetMenuTitleWithCFString(submenu, QCFString(qt_mac_removeMnemonics(action->action->text())));
-        if (visible)
-            ChangeMenuAttributes(submenu, 0, kMenuAttrHidden);
-        else
-            ChangeMenuAttributes(submenu, kMenuAttrHidden, 0);
-#else
-        [item setSubmenu: submenu];
-        [submenu setTitle:qt_mac_QStringToNSString(qt_mac_removeMnemonics(action->action->text()))];
-        syncNSMenuItemVisiblity(item, visible);
-        syncNSMenuItemEnabled(item, action->action->isEnabled());
-#endif
-        if (release_submenu) { //no pointers to it
-#ifndef QT_MAC_USE_COCOA
-            ReleaseMenu(submenu);
-#else
-            [submenu release];
-#endif
-        }
-    } else {
-        qWarning("QMenu: No OSMenuRef created for popup menu");
-    }
-}
-
-void
-QMenuBarPrivate::QMacMenuBarPrivate::removeAction(QMacMenuAction *action)
-{
-    if (!action || !menu)
-        return;
-#ifndef QT_MAC_USE_COCOA
-    DeleteMenuItem(action->menu, qt_mac_menu_find_action(action->menu, action));
-#else
-    QMacCocoaAutoReleasePool pool;
-    [action->menu removeItem:action->menuItem];
-#endif
-    actionItems.removeAll(action);
-}
-
-bool QMenuBarPrivate::macWidgetHasNativeMenubar(QWidget *widget)
-{
-    // This function is different from q->isNativeMenuBar(), as
-    // it returns true only if a native menu bar is actually
-    // _created_.
-    if (!widget)
-        return false;
-    return menubars()->contains(widget->window());
-}
-
-void
-QMenuBarPrivate::macCreateMenuBar(QWidget *parent)
-{
-    Q_Q(QMenuBar);
-    static int dontUseNativeMenuBar = -1;
-    // We call the isNativeMenuBar function here
-    // because that will make sure that local overrides
-    // are dealt with correctly. q->isNativeMenuBar() will, if not
-    // overridden, depend on the attribute Qt::AA_DontUseNativeMenuBar:
-    bool qt_mac_no_native_menubar = !q->isNativeMenuBar();
-    if (qt_mac_no_native_menubar == false && dontUseNativeMenuBar < 0) {
-        // The menubar is set to be native. Let's check (one time only
-        // for all menubars) if this is OK with the rest of the environment.
-        // As a result, Qt::AA_DontUseNativeMenuBar is set. NB: the application
-        // might still choose to not respect, or change, this flag.
-        bool isPlugin = QApplication::testAttribute(Qt::AA_MacPluginApplication);
-        bool environmentSaysNo = !qgetenv("QT_MAC_NO_NATIVE_MENUBAR").isEmpty();
-        dontUseNativeMenuBar = isPlugin || environmentSaysNo;
-        QApplication::instance()->setAttribute(Qt::AA_DontUseNativeMenuBar, dontUseNativeMenuBar);
-        qt_mac_no_native_menubar = !q->isNativeMenuBar();
-    }
-    if (qt_mac_no_native_menubar == false) {
-        // INVARIANT: Use native menubar.
-        extern void qt_event_request_menubarupdate(); //qapplication_mac.cpp
-        qt_event_request_menubarupdate();
-        if (!parent && !fallback) {
-            fallback = q;
-            mac_menubar = new QMacMenuBarPrivate;
-        } else if (parent && parent->isWindow()) {
-            menubars()->insert(q->window(), q);
-            mac_menubar = new QMacMenuBarPrivate;
-        }
-    }
-}
-
-void QMenuBarPrivate::macDestroyMenuBar()
-{
-    Q_Q(QMenuBar);
-    QMacCocoaAutoReleasePool pool;
-    if (fallback == q)
-        fallback = 0;
-    delete mac_menubar;
-    QWidget *tlw = q->window();
-    menubars()->remove(tlw);
-    mac_menubar = 0;
-
-    if (!qt_mac_current_menubar.qmenubar || qt_mac_current_menubar.qmenubar == q) {
-#ifdef QT_MAC_USE_COCOA
-        QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-        [loader removeActionsFromAppMenu];
-#else
-        cancelAllMenuTracking();
-#endif
-        extern void qt_event_request_menubarupdate(); //qapplication_mac.cpp
-        qt_event_request_menubarupdate();
-    }
-}
-
-OSMenuRef QMenuBarPrivate::macMenu()
-{
-    Q_Q(QMenuBar);
-    if (!q->isNativeMenuBar() || !mac_menubar) {
-        return 0;
-    } else if (!mac_menubar->menu) {
-        mac_menubar->menu = qt_mac_create_menu(q);
-#ifdef QT_MAC_USE_COCOA
-        [mac_menubar->menu setAutoenablesItems:NO];
-#endif
-        ProcessSerialNumber mine, front;
-        if (GetCurrentProcess(&mine) == noErr && GetFrontProcess(&front) == noErr) {
-            if (!qt_mac_no_menubar_merge && !mac_menubar->apple_menu) {
-                mac_menubar->apple_menu = qt_mac_create_menu(q);
-#ifndef QT_MAC_USE_COCOA
-                MenuItemIndex index;
-                AppendMenuItemTextWithCFString(mac_menubar->menu, 0, 0, 0, &index);
-
-                SetMenuTitleWithCFString(mac_menubar->apple_menu, QCFString(QString(QChar(0x14))));
-                SetMenuItemHierarchicalMenu(mac_menubar->menu, index, mac_menubar->apple_menu);
-                SetMenuItemProperty(mac_menubar->apple_menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(q), &q);
-#else
-                [mac_menubar->apple_menu setTitle:qt_mac_QStringToNSString(QString(QChar(0x14)))];
-                NSMenuItem *apple_menuItem = [[NSMenuItem alloc] init];
-                [apple_menuItem setSubmenu:mac_menubar->menu];
-                [mac_menubar->apple_menu addItem:apple_menuItem];
-                [apple_menuItem release];
-#endif
-            }
-            if (mac_menubar->apple_menu) {
-#ifndef QT_MAC_USE_COCOA
-                SetMenuItemProperty(mac_menubar->menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu,
-                                    sizeof(mac_menubar->apple_menu), &mac_menubar->apple_menu);
-#else
-                QMenuPrivate::mergeMenuHash.insert(mac_menubar->menu, mac_menubar->apple_menu);
-#endif
-            }
-            QList<QAction*> items = q->actions();
-            for(int i = 0; i < items.count(); i++)
-                mac_menubar->addAction(items[i]);
-        }
-    }
-    return mac_menubar->menu;
-}
-
-/*!
-    \internal
-
-    This function will return the OSMenuRef used to create the native menu bar
-    bindings. This OSMenuRef is then set as the root menu for the Menu
-    Manager.
-
-    \warning This function is not portable.
-
-    \sa QMenu::macMenu()
-*/
-OSMenuRef QMenuBar::macMenu() { return d_func()->macMenu(); }
-
-/* !
-    \internal
-    Ancestor function that crosses windows (QWidget::isAncestorOf
-    only considers widgets within the same window).
-*/
-static bool qt_mac_is_ancestor(QWidget* possibleAncestor, QWidget *child)
-{
-    if (!possibleAncestor)
-        return false;
-
-    QWidget * current = child->parentWidget();
-    while (current != 0) {
-        if (current == possibleAncestor)
-            return true;
-        current = current->parentWidget();
-    }
-    return false;
-}
-
-/* !
-    \internal
-    Returns true if the entries of menuBar should be disabled,
-    based on the modality type of modalWidget.
-*/
-static bool qt_mac_should_disable_menu(QMenuBar *menuBar)
-{
-    QWidget *modalWidget = qApp->activeModalWidget();
-    if (!modalWidget)
-        return false;
-
-    if (menuBar && menuBar == menubars()->value(modalWidget))
-        // The menu bar is owned by the modal widget.
-        // In that case we should enable it:
-        return false;
-
-    // When there is an application modal window on screen, the entries of
-    // the menubar should be disabled. The exception in Qt is that if the
-    // modal window is the only window on screen, then we enable the menu bar.
-    QWidget *w = modalWidget;
-    QWidgetList topLevelWidgets = QApplication::topLevelWidgets();
-    while (w) {
-        if (w->isVisible() && w->windowModality() == Qt::ApplicationModal) {
-            for (int i=0; i<topLevelWidgets.size(); ++i) {
-                QWidget *top = topLevelWidgets.at(i);
-                if (w != top && top->isVisible()) {
-                    // INVARIANT: we found another visible window
-                    // on screen other than our modalWidget. We therefore
-                    // disable the menu bar to follow normal modality logic:
-                    return true;
-                }
-            }
-            // INVARIANT: We have only one window on screen that happends
-            // to be application modal. We choose to enable the menu bar
-            // in that case to e.g. enable the quit menu item.
-            return false;
-        }
-        w = w->parentWidget();
-    }
-
-    // INVARIANT: modalWidget is window modal. Disable menu entries
-    // if the menu bar belongs to an ancestor of modalWidget. If menuBar
-    // is nil, we understand it as the default menu bar set by the nib:
-    return menuBar ? qt_mac_is_ancestor(menuBar->parentWidget(), modalWidget) : false;
-}
-
-static QWidget *findWindowThatShouldDisplayMenubar()
-{
-    QWidget *w = qApp->activeWindow();
-    if (!w) {
-        // We have no active window on screen. Try to
-        // find a window from the list of top levels:
-        QWidgetList tlws = QApplication::topLevelWidgets();
-        for(int i = 0; i < tlws.size(); ++i) {
-            QWidget *tlw = tlws.at(i);
-            if ((tlw->isVisible() && tlw->windowType() != Qt::Tool &&
-                tlw->windowType() != Qt::Popup)) {
-                w = tlw;
-                break;
-            }
-        }
-    }
-    return w;
-}
-
-static QMenuBar *findMenubarForWindow(QWidget *w)
-{
-    QMenuBar *mb = 0;
-    if (w) {
-        mb = menubars()->value(w);
-#ifndef QT_NO_MAINWINDOW
-        QDockWidget *dw = qobject_cast<QDockWidget *>(w);
-        if (!mb && dw) {
-            QMainWindow *mw = qobject_cast<QMainWindow *>(dw->parentWidget());
-            if (mw && (mb = menubars()->value(mw)))
-                w = mw;
-        }
-#endif
-        while(w && !mb)
-            mb = menubars()->value((w = w->parentWidget()));
-    }
-
-    if (!mb) {
-        // We could not find a menu bar for the window. Lets
-        // check if we have a global (parentless) menu bar instead:
-        mb = fallback;
-    }
-
-    return mb;
-}
-
-void qt_mac_clear_menubar()
-{
-    if (QApplication::testAttribute(Qt::AA_MacPluginApplication))
-        return;
-
-#ifndef QT_MAC_USE_COCOA
-    MenuRef clear_menu = 0;
-    if (CreateNewMenu(0, 0, &clear_menu) == noErr) {
-        SetRootMenu(clear_menu);
-        ReleaseMenu(clear_menu);
-    } else {
-        qWarning("QMenu: Internal error at %s:%d", __FILE__, __LINE__);
-    }
-    ClearMenuBar();
-    qt_mac_command_set_enabled(0, kHICommandPreferences, false);
-    InvalMenuBar();
-#else
-    QMacCocoaAutoReleasePool pool;
-    QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-    NSMenu *menu = [loader menu];
-    [loader ensureAppMenuInMenu:menu];
-    [[NSApplication sharedApplication] setMainMenu:menu];
-    const bool modal = qt_mac_should_disable_menu(0);
-    if (qt_mac_current_menubar.qmenubar || modal != qt_mac_current_menubar.modal)
-        qt_mac_set_modal_state(menu, modal);
-    qt_mac_current_menubar.qmenubar = 0;
-    qt_mac_current_menubar.modal = modal;
-#endif
-}
-
-/*!
-  \internal
-
-  This function will update the current menu bar and set it as the
-  active menu bar in the Menu Manager.
-
-  \warning This function is not portable.
-
-  \sa QMenu::macMenu(), QMenuBar::macMenu()
-*/
-bool QMenuBar::macUpdateMenuBar()
-{
-#ifdef QT_MAC_USE_COCOA
-    QMacCocoaAutoReleasePool pool;
-    qt_cocoaPostMessage(getMenuLoader(), @selector(qtUpdateMenubar));
-    return true;
-#else
-    return QMenuBarPrivate::macUpdateMenuBarImmediatly();
-#endif
-}
-
-bool QMenuBarPrivate::macUpdateMenuBarImmediatly()
-{
-    bool ret = false;
-    cancelAllMenuTracking();
-    QWidget *w = findWindowThatShouldDisplayMenubar();
-    QMenuBar *mb = findMenubarForWindow(w);
-    extern bool qt_mac_app_fullscreen; //qapplication_mac.mm
-
-    // We need to see if we are in full screen mode, if so we need to
-    // switch the full screen mode to be able to show or hide the menubar.
-    if(w && mb) {
-        // This case means we are creating a menubar, check if full screen
-        if(w->isFullScreen()) {
-            // Ok, switch to showing the menubar when hovering over it.
-            SetSystemUIMode(kUIModeAllHidden, kUIOptionAutoShowMenuBar);
-            qt_mac_app_fullscreen = true;
-        }
-    } else if(w) {
-        // Removing a menubar
-        if(w->isFullScreen()) {
-            // Ok, switch to not showing the menubar when hovering on it
-            SetSystemUIMode(kUIModeAllHidden, 0);
-            qt_mac_app_fullscreen = true;
-        }
-    }
-
-    if (mb && mb->isNativeMenuBar()) {
-        bool modal = QApplicationPrivate::modalState();
-#ifdef QT_MAC_USE_COCOA
-        QMacCocoaAutoReleasePool pool;
-#endif
-        if (OSMenuRef menu = mb->macMenu()) {
-#ifndef QT_MAC_USE_COCOA
-            SetRootMenu(menu);
-#else
-            QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-            [loader ensureAppMenuInMenu:menu];
-            [[NSApplication sharedApplication] setMainMenu:menu];
-            syncMenuBarItemsVisiblity(mb->d_func()->mac_menubar);
-
-            if (OSMenuRef tmpMerge = QMenuPrivate::mergeMenuHash.value(menu)) {
-                if (QMenuMergeList *mergeList
-                        = QMenuPrivate::mergeMenuItemsHash.value(tmpMerge)) {
-                    const int mergeListSize = mergeList->size();
-
-                    for (int i = 0; i < mergeListSize; ++i) {
-                        const QMenuMergeItem &mergeItem = mergeList->at(i);
-                        // Ideally we would call QMenuPrivate::syncAction, but that requires finding
-                        // the original QMen and likely doing more work than we need.
-                        // For example, enabled is handled below.
-                        [mergeItem.menuItem setTag:reinterpret_cast<long>(
-                                                    static_cast<QAction *>(mergeItem.action->action))];
-                        [mergeItem.menuItem setHidden:!(mergeItem.action->action->isVisible())];
-                    }
-                }
-            }
-#endif
-            // Check if menu is modally shaddowed and should  be disabled:
-            modal = qt_mac_should_disable_menu(mb);
-            if (mb != qt_mac_current_menubar.qmenubar || modal != qt_mac_current_menubar.modal)
-                qt_mac_set_modal_state(menu, modal);
-        }
-        qt_mac_current_menubar.qmenubar = mb;
-        qt_mac_current_menubar.modal = modal;
-        ret = true;
-    } else if (qt_mac_current_menubar.qmenubar && qt_mac_current_menubar.qmenubar->isNativeMenuBar()) {
-        // INVARIANT: The currently active menu bar (if any) is not native. But we do have a
-        // native menu bar from before. So we need to decide whether or not is should be enabled:
-        const bool modal = qt_mac_should_disable_menu(qt_mac_current_menubar.qmenubar);
-        if (modal != qt_mac_current_menubar.modal) {
-            ret = true;
-            if (OSMenuRef menu = qt_mac_current_menubar.qmenubar->macMenu()) {
-#ifndef QT_MAC_USE_COCOA
-                SetRootMenu(menu);
-#else
-                QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader();
-                [loader ensureAppMenuInMenu:menu];
-                [[NSApplication sharedApplication] setMainMenu:menu];
-                syncMenuBarItemsVisiblity(qt_mac_current_menubar.qmenubar->d_func()->mac_menubar);
-#endif
-                qt_mac_set_modal_state(menu, modal);
-            }
-            qt_mac_current_menubar.modal = modal;
-        }
-    }
-
-    if (!ret) {
-        qt_mac_clear_menubar();
-    }
-    return ret;
-}
-
-QHash<OSMenuRef, OSMenuRef> QMenuPrivate::mergeMenuHash;
-QHash<OSMenuRef, QMenuMergeList*> QMenuPrivate::mergeMenuItemsHash;
-
-bool QMenuPrivate::QMacMenuPrivate::merged(const QAction *action) const
-{
-#ifndef QT_MAC_USE_COCOA
-    MenuRef merge = 0;
-    GetMenuItemProperty(menu, 0, kMenuCreatorQt, kMenuPropertyMergeMenu,
-            sizeof(merge), 0, &merge);
-    if (merge) {
-        QMenuMergeList *list = 0;
-        if (GetMenuItemProperty(merge, 0, kMenuCreatorQt, kMenuPropertyMergeList,
-                    sizeof(list), 0, &list) == noErr && list) {
-            for(int i = 0; i < list->size(); ++i) {
-                QMenuMergeItem item = list->at(i);
-                if (item.action->action == action)
-                    return true;
-            }
-        }
-    }
-#else
-    if (OSMenuRef merge = mergeMenuHash.value(menu)) {
-        if (QMenuMergeList *list = mergeMenuItemsHash.value(merge)) {
-            for(int i = 0; i < list->size(); ++i) {
-                const QMenuMergeItem &item = list->at(i);
-                if (item.action->action == action)
-                    return true;
-            }
-        }
-    }
-#endif
-    return false;
-}
-
-//creation of the OSMenuRef
-static OSMenuRef qt_mac_create_menu(QWidget *w)
-{
-    OSMenuRef ret;
-#ifndef QT_MAC_USE_COCOA
-    ret = 0;
-    if (CreateNewMenu(0, 0, &ret) == noErr) {
-        qt_mac_create_menu_event_handler();
-        SetMenuItemProperty(ret, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(w), &w);
-
-        // kEventMenuMatchKey is only sent to the menu itself and not to
-        // the application, install a separate handler for that event.
-        EventHandlerRef eventHandlerRef;
-        InstallMenuEventHandler(ret, qt_mac_menu_event,
-                                GetEventTypeCount(menu_menu_events),
-                                menu_menu_events, 0, &eventHandlerRef);
-        menu_eventHandlers_hash()->insert(ret, eventHandlerRef);
-    } else {
-        qWarning("QMenu: Internal error");
-    }
-#else
-    if (QMenu *qmenu = qobject_cast<QMenu *>(w)){
-        ret = [[QT_MANGLE_NAMESPACE(QCocoaMenu) alloc] initWithQMenu:qmenu];
-    } else {
-        ret = [[NSMenu alloc] init];
-    }
-#endif
-    return ret;
-}
-
-
-
-QT_END_NAMESPACE
-
diff --git a/src/gui/widgets/qmenu_wince.cpp b/src/gui/widgets/qmenu_wince.cpp
deleted file mode 100644 (file)
index c1780fd..0000000
+++ /dev/null
@@ -1,668 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-//Native menubars are only supported for Windows Mobile not the standard SDK/generic WinCE
-#ifdef Q_WS_WINCE
-#include "qmenu.h"
-#include "qt_windows.h"
-#include "qapplication.h"
-#include "qmainwindow.h"
-#include "qtoolbar.h"
-#include "qevent.h"
-#include "qstyle.h"
-#include "qdebug.h"
-#include "qwidgetaction.h"
-#include <qapplication_p.h>
-#include <qmenu_p.h>
-#include <qmenubar_p.h>
-
-#include "qmenu_wince_resource_p.h"
-
-#include <QtCore/qlibrary.h>
-#include <commctrl.h>
-#if Q_OS_WINCE_WM
-#   include <windowsm.h>
-#endif
-
-#include "qguifunctions_wince.h"
-
-#ifndef QT_NO_MENUBAR
-
-#ifndef SHCMBF_EMPTYBAR
-#define SHCMBF_EMPTYBAR 0x0001
-#endif
-
-#ifndef SHCMBM_GETSUBMENU
-#define SHCMBM_GETSUBMENU (WM_USER + 401)
-#endif
-
-#ifdef Q_OS_WINCE_WM
-#   define SHMBOF_NODEFAULT 0x00000001
-#   define SHMBOF_NOTIFY    0x00000002
-#   define SHCMBM_OVERRIDEKEY (WM_USER + 0x193)
-#endif
-
-extern bool qt_wince_is_smartphone();//defined in qguifunctions_wce.cpp
-extern bool qt_wince_is_pocket_pc(); //defined in qguifunctions_wce.cpp
-
-QT_BEGIN_NAMESPACE
-
-static uint qt_wce_menu_static_cmd_id = 200;
-static QList<QMenuBar*> nativeMenuBars;
-
-struct qt_SHMENUBARINFO
-{
-    DWORD     cbSize;
-    HWND      hwndParent;
-    DWORD     dwFlags;
-    UINT      nToolBarId;
-    HINSTANCE hInstRes;
-    int       nBmpId;
-    int       cBmpImages;
-    HWND      hwndMB;
-    COLORREF  clrBk;
-};
-
-typedef BOOL (WINAPI *AygCreateMenuBar)(qt_SHMENUBARINFO*);
-typedef HRESULT (WINAPI *AygEnableSoftKey)(HWND,UINT,BOOL,BOOL);
-
-static bool aygResolved = false;
-static AygCreateMenuBar ptrCreateMenuBar = 0;
-static AygEnableSoftKey ptrEnableSoftKey = 0;
-
-static void resolveAygLibs()
-{
-    if (!aygResolved) {
-        QLibrary aygLib(QLatin1String("aygshell"));
-        ptrCreateMenuBar = (AygCreateMenuBar) aygLib.resolve("SHCreateMenuBar");
-        ptrEnableSoftKey = (AygEnableSoftKey) aygLib.resolve("SHEnableSoftkey");
-        aygResolved = true;
-    }
-}
-
-static void qt_wce_enable_soft_key(HWND handle, uint command) 
-{
-    resolveAygLibs();
-    if (ptrEnableSoftKey)
-        ptrEnableSoftKey(handle, command, false, true);
-}
-
-static void qt_wce_disable_soft_key(HWND handle, uint command) 
-{
-    resolveAygLibs();
-    if (ptrEnableSoftKey)
-        ptrEnableSoftKey(handle, command, false, false);
-}
-
-static void qt_wce_delete_action_list(QList<QWceMenuAction*> *list)
-{
-    for(QList<QWceMenuAction*>::Iterator it = list->begin(); it != list->end(); ++it) {
-        QWceMenuAction *action = (*it);
-        delete action;
-        action = 0;
-    }
-    list->clear();
-}
-
-//search for first QuitRole in QMenuBar
-static QAction* qt_wce_get_quit_action(QList<QAction *> actionItems)
-{
-    QAction *returnAction = 0;
-    for (int i = 0; i < actionItems.size(); ++i) {
-        QAction *action = actionItems.at(i);
-        if (action->menuRole() == QAction::QuitRole)
-            returnAction = action;
-        else 
-            if (action->menu())
-                returnAction = qt_wce_get_quit_action(action->menu()->actions());
-        if (returnAction)
-            return returnAction; //return first action found
-    }
-    return 0; //nothing found;
-}
-
-static QAction* qt_wce_get_quit_action(QList<QWceMenuAction*> actionItems)
-{
-    for (int i = 0; i < actionItems.size(); ++i) {
-        if (actionItems.at(i)->action->menuRole() == QAction::QuitRole)
-            return actionItems.at(i)->action;
-        else if (actionItems.at(i)->action->menu()) {
-            QAction *returnAction = qt_wce_get_quit_action(actionItems.at(i)->action->menu()->actions());
-            if (returnAction)
-                return returnAction;
-        }
-    }
-    return 0;
-}
-
-static HMODULE qt_wce_get_module_handle()
-{
-    HMODULE module =  0; //handle to resources
-    if (!(module = GetModuleHandle(L"QtGui4"))) //release dynamic
-        if (!(module = GetModuleHandle(L"QtGuid4"))) //debug dynamic
-            module = (HINSTANCE)qWinAppInst(); //static
-    Q_ASSERT_X(module, "qt_wce_get_module_handle()", "cannot get handle to module?");
-    return module;
-}
-
-static void qt_wce_change_command(HWND menuHandle, int item, int command)
-{
-TBBUTTONINFOA tbbi;
-    memset(&tbbi,0,sizeof(tbbi));
-    tbbi.cbSize = sizeof(tbbi);
-    tbbi.dwMask = TBIF_COMMAND;
-    tbbi.idCommand = command;
-    SendMessage(menuHandle, TB_SETBUTTONINFO, item, (LPARAM)&tbbi);
-}
-
-static void qt_wce_rename_menu_item(HWND menuHandle, int item, const QString &newText)
-{
-    TBBUTTONINFOA tbbi;
-    memset(&tbbi,0,sizeof(tbbi));
-    tbbi.cbSize = sizeof(tbbi);
-    tbbi.dwMask = TBIF_TEXT;
-    QString text = newText;
-    text.remove(QChar::fromLatin1('&'));
-    tbbi.pszText = (LPSTR) text.utf16();
-    SendMessage(menuHandle, TB_SETBUTTONINFO, item, (LPARAM)&tbbi);
-}
-
-static HWND qt_wce_create_menubar(HWND parentHandle, HINSTANCE resourceHandle, int toolbarID, int flags = 0)
-{
-    resolveAygLibs();
-
-    if (ptrCreateMenuBar) {
-        qt_SHMENUBARINFO mbi;
-        memset(&mbi, 0, sizeof(qt_SHMENUBARINFO));
-        mbi.cbSize     = sizeof(qt_SHMENUBARINFO);
-        mbi.hwndParent = parentHandle;
-        mbi.hInstRes   = resourceHandle;
-        mbi.dwFlags = flags;
-        mbi.nToolBarId = toolbarID;
-
-        if (ptrCreateMenuBar(&mbi)) {
-#ifdef Q_OS_WINCE_WM
-            // Tell the menu bar that we want to override hot key behaviour.
-            LPARAM lparam = MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY,
-                                       SHMBOF_NODEFAULT | SHMBOF_NOTIFY);
-            SendMessage(mbi.hwndMB, SHCMBM_OVERRIDEKEY, VK_TBACK, lparam);
-#endif
-            return mbi.hwndMB;
-        }
-    }
-    return 0;
-}
-
-static void qt_wce_insert_action(HMENU menu, QWceMenuAction *action)
-{
-    Q_ASSERT_X(menu, "AppendMenu", "menu is 0");
-    if (action->action->isVisible()) {
-        int flags;
-        action->action->isEnabled() ? flags = MF_ENABLED : flags = MF_GRAYED;
-
-        QString text = action->action->iconText();
-        text.remove(QChar::fromLatin1('&'));
-        if (action->action->isSeparator()) {
-            AppendMenu (menu, MF_SEPARATOR , 0, 0);
-        }
-        else if (action->action->menu()) {
-            text.remove(QChar::fromLatin1('&'));
-            AppendMenu (menu, MF_STRING | flags | MF_POPUP,
-            (UINT) action->action->menu()->wceMenu(), reinterpret_cast<const wchar_t *> (text.utf16()));
-        }
-        else {
-            AppendMenu (menu, MF_STRING | flags, action->command, reinterpret_cast<const wchar_t *> (text.utf16()));
-        }
-        if (action->action->isCheckable())
-            if (action->action->isChecked())
-                CheckMenuItem(menu, action->command, MF_BYCOMMAND | MF_CHECKED);
-            else 
-                CheckMenuItem(menu, action->command, MF_BYCOMMAND | MF_UNCHECKED);
-    }
-}
-
-// Removes all items from the menu without destroying the handles.
-static void qt_wce_clear_menu(HMENU hMenu)
-{
-    while (RemoveMenu(hMenu, 0, MF_BYPOSITION));
-}
-
-/*!
-    \internal 
-    
-    This function refreshes the native Windows CE menu.
-*/
-
-void QMenuBar::wceRefresh()
-{
-    for (int i = 0; i < nativeMenuBars.size(); ++i)
-        nativeMenuBars.at(i)->d_func()->wceRefresh();
-}
-
-void QMenuBarPrivate::wceRefresh()
-{
-    DrawMenuBar(wce_menubar->menubarHandle);
-}
-
-/*!
-    \internal 
-    
-    This function sends native Windows CE commands to Qt menus.
-*/
-
-QAction* QMenu::wceCommands(uint command)
-{
-    Q_D(QMenu);
-    return d->wceCommands(command);
-}
-
-/*!
-    \internal 
-    
-    This function sends native Windows CE commands to Qt menu bars
-    and all their child menus.
-*/
-
-void QMenuBar::wceCommands(uint command)
-{
-    const HWND hwndActiveWindow = GetActiveWindow();
-    for (int i = 0; i < nativeMenuBars.size(); ++i) {
-        QMenuBarPrivate* nativeMenuBar = nativeMenuBars.at(i)->d_func();
-        if (hwndActiveWindow == nativeMenuBar->wce_menubar->parentWindowHandle)
-            nativeMenuBar->wceCommands(command);
-    }
-}
-
-bool QMenuBarPrivate::wceEmitSignals(QList<QWceMenuAction*> actions, uint command)
-{
-    QAction *foundAction = 0;
-    for (int i = 0; i < actions.size(); ++i) {
-        QWceMenuAction *action = actions.at(i);
-        if (action->action->menu()) {
-            foundAction = action->action->menu()->wceCommands(command);
-            if (foundAction)
-                break;
-        }
-        else if (action->command == command) {
-            action->action->activate(QAction::Trigger);
-            return true;
-        }
-    }
-    if (foundAction) {
-        emit q_func()->triggered(foundAction);
-        return true;
-    }
-    return false;
-}
-
-void QMenuBarPrivate::wceCommands(uint command)
-{
-    if (wceClassicMenu) {
-        for (int i = 0; i < wce_menubar->actionItemsClassic.size(); ++i)
-            wceEmitSignals(wce_menubar->actionItemsClassic.at(i), command);
-    } else {
-        if (wceEmitSignals(wce_menubar->actionItems, command)) {
-            return;
-        }
-        else if (wce_menubar->leftButtonIsMenu) {//check if command is on the left quick button
-            wceEmitSignals(wce_menubar->actionItemsLeftButton, command);
-        }
-        else if ((wce_menubar->leftButtonAction) && (command == wce_menubar->leftButtonCommand)) {
-            emit q_func()->triggered(wce_menubar->leftButtonAction);
-            wce_menubar->leftButtonAction->activate(QAction::Trigger);
-        }
-    }
-}
-
-QAction *QMenuPrivate::wceCommands(uint command)
-{
-    QAction *foundAction = 0;
-    for (int i  = 0; i < wce_menu->actionItems.size(); ++i) {
-        if (foundAction)
-            break;
-        QWceMenuAction *action = wce_menu->actionItems.at(i);
-        if (action->action->menu()) {
-            foundAction = action->action->menu()->d_func()->wceCommands(command);
-        }
-        else if (action->command == command) {
-            activateAction(action->action, QAction::Trigger);
-            return action->action;
-        }
-    }
-    if (foundAction)
-        emit q_func()->triggered(foundAction);
-    return foundAction;
-}
-
-void QMenuBarPrivate::wceCreateMenuBar(QWidget *parent)
-{
-    Q_Q(QMenuBar);
-    wce_menubar = new QWceMenuBarPrivate(this);
-
-    wce_menubar->parentWindowHandle = parent ? parent->winId() : q->winId();
-    wce_menubar->leftButtonAction = defaultAction;
-
-    wce_menubar->menubarHandle = qt_wce_create_menubar(wce_menubar->parentWindowHandle, (HINSTANCE)qWinAppInst(), 0, SHCMBF_EMPTYBAR);
-    Q_ASSERT_X(wce_menubar->menubarHandle, "wceCreateMenuBar", "cannot create empty menu bar");
-    DrawMenuBar(wce_menubar->menubarHandle);
-    nativeMenuBars.append(q);
-    wceClassicMenu = (!qt_wince_is_smartphone() && !qt_wince_is_pocket_pc());
-}
-
-void QMenuBarPrivate::wceDestroyMenuBar()
-{
-    Q_Q(QMenuBar);
-    int index = nativeMenuBars.indexOf(q);
-    nativeMenuBars.removeAt(index);
-    if (wce_menubar) {
-        delete wce_menubar;
-        wce_menubar = 0;
-    }
-}
-
-QMenuBarPrivate::QWceMenuBarPrivate::QWceMenuBarPrivate(QMenuBarPrivate *menubar)
-:   menubarHandle(0), menuHandle(0), leftButtonMenuHandle(0),
-    leftButtonAction(0), leftButtonIsMenu(false), d(menubar)
-{
-}
-
-QMenuBarPrivate::QWceMenuBarPrivate::~QWceMenuBarPrivate()
-{
-    if (menubarHandle)
-        DestroyWindow(menubarHandle);
-    qt_wce_delete_action_list(&actionItems);
-    qt_wce_delete_action_list(&actionItemsLeftButton);
-
-    for (int i=0; i<actionItemsClassic.size(); ++i)
-        if (!actionItemsClassic.value(i).empty())
-            qt_wce_delete_action_list(&actionItemsClassic[i]);
-    actionItemsClassic.clear();
-
-    menubarHandle = 0;
-    menuHandle = 0;
-    leftButtonMenuHandle = 0;
-    leftButtonCommand = 0;
-    QMenuBar::wceRefresh();
-}
-
-QMenuPrivate::QWceMenuPrivate::QWceMenuPrivate()
-:   menuHandle(0)
-{
-}
-
-QMenuPrivate::QWceMenuPrivate::~QWceMenuPrivate()
-{
-    qt_wce_delete_action_list(&actionItems);
-    if (menuHandle)
-        DestroyMenu(menuHandle);
-}
-
-void QMenuPrivate::QWceMenuPrivate::addAction(QAction *a, QWceMenuAction *before)
-{
-    QWceMenuAction *action = new QWceMenuAction;
-    action->action = a;
-    action->command = qt_wce_menu_static_cmd_id++;
-    addAction(action, before);
-}
-
-void QMenuPrivate::QWceMenuPrivate::addAction(QWceMenuAction *action, QWceMenuAction *before)
-{
-    if (!action)
-        return;
-    int before_index = actionItems.indexOf(before);
-    if (before_index < 0) {
-        before = 0;
-        before_index = actionItems.size();
-    }
-    actionItems.insert(before_index, action);
-    rebuild();
-}
-
-/*!
-    \internal
-    
-    This function will return the HMENU used to create the native
-    Windows CE menu bar bindings.
-*/
-
-HMENU QMenu::wceMenu()
-{
-    return d_func()->wceMenu();
-}
-
-HMENU QMenuPrivate::wceMenu()
-{
-    if (!wce_menu)
-        wce_menu = new QWceMenuPrivate;
-    if (!wce_menu->menuHandle)
-        wce_menu->rebuild();
-    return wce_menu->menuHandle;
-}
-
-void QMenuPrivate::QWceMenuPrivate::rebuild()
-{
-    if (!menuHandle)
-        menuHandle = CreatePopupMenu();
-    else
-        qt_wce_clear_menu(menuHandle);
-
-    for (int i = 0; i < actionItems.size(); ++i) {
-        QWceMenuAction *action = actionItems.at(i);
-        action->menuHandle = menuHandle;
-        qt_wce_insert_action(menuHandle, action);
-    }
-    QMenuBar::wceRefresh();
-}
-
-void QMenuPrivate::QWceMenuPrivate::syncAction(QWceMenuAction *)
-{
-    rebuild();
-}
-
-void QMenuPrivate::QWceMenuPrivate::removeAction(QWceMenuAction *action)
-{
-    actionItems.removeAll(action);
-    delete action;
-    rebuild();
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::addAction(QAction *a, QAction *before)
-{
-    QWceMenuAction *action = new QWceMenuAction;
-    action->action = a;
-    action->command = qt_wce_menu_static_cmd_id++;
-    addAction(action, findAction(before));
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::addAction(QWceMenuAction *action, QWceMenuAction *before)
-{
-    if (!action)
-        return;
-    int before_index = actionItems.indexOf(before);
-    if (before_index < 0) {
-        before = 0;
-        before_index = actionItems.size();
-    }
-    actionItems.insert(before_index, action);
-    rebuild();
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::syncAction(QWceMenuAction*)
-{
-    QMenuBar::wceRefresh();
-    rebuild();
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::removeAction(QWceMenuAction *action)
-{
-    actionItems.removeAll(action);
-    delete action;
-    rebuild();
-}
-
-void QMenuBarPrivate::_q_updateDefaultAction()
-{
-    if (wce_menubar)
-        wce_menubar->rebuild();
-}
-
-void QMenuBarPrivate::QWceMenuBarPrivate::rebuild()
-{
-    d->q_func()->resize(0,0);
-    parentWindowHandle = d->q_func()->parentWidget() ? d->q_func()->parentWidget()->winId() : d->q_func()->winId();
-    if (d->wceClassicMenu) {
-        QList<QAction*> actions = d->actions;
-        int maxEntries;
-        int resourceHandle;
-        if (actions.size() < 5) {
-            maxEntries = 4;
-            resourceHandle = IDR_MAIN_MENU3;
-        } else if (actions.size() < 7) {
-            maxEntries = 6;
-            resourceHandle = IDR_MAIN_MENU4;
-        }
-        else {
-          maxEntries = 8;
-          resourceHandle = IDR_MAIN_MENU5;
-        }
-        Q_ASSERT_X(menubarHandle, "rebuild !created", "menubar already deleted");
-        qt_wce_clear_menu(menuHandle);
-        DestroyWindow(menubarHandle);
-        menubarHandle = qt_wce_create_menubar(parentWindowHandle, qt_wce_get_module_handle(), resourceHandle);
-        Q_ASSERT_X(menubarHandle, "rebuild classic menu", "cannot create menubar from resource");
-        DrawMenuBar(menubarHandle);
-        QList<int> menu_ids;
-        QList<int> item_ids;
-        menu_ids << IDM_MENU1 << IDM_MENU2 << IDM_MENU3 << IDM_MENU4 << IDM_MENU5 << IDM_MENU6 << IDM_MENU7 << IDM_MENU8;
-        item_ids << IDM_ITEM1 << IDM_ITEM2 << IDM_ITEM3 << IDM_ITEM4 << IDM_ITEM5 << IDM_ITEM6 << IDM_ITEM7 << IDM_ITEM8;
-
-        for (int i = 0; i < actionItemsClassic.size(); ++i)
-          if (!actionItemsClassic.value(i).empty())
-            qt_wce_delete_action_list(&actionItemsClassic[i]);
-        actionItemsClassic.clear();
-
-        for (int i = 0; i < actions.size(); ++i) {
-            qt_wce_rename_menu_item(menubarHandle, menu_ids.at(i), actions.at(i)->text());
-            QList<QAction *> subActions = actions.at(i)->menu()->actions();
-            HMENU subMenuHandle = (HMENU) SendMessage(menubarHandle, SHCMBM_GETSUBMENU,0 , menu_ids.at(i));
-            DeleteMenu(subMenuHandle, item_ids.at(i), MF_BYCOMMAND);
-            for (int c = 0; c < subActions.size(); ++c) {
-                QList<QWceMenuAction*> list;
-                actionItemsClassic.append(list);
-                QWceMenuAction *action = new QWceMenuAction;
-                action->action = subActions.at(c);
-                action->command = qt_wce_menu_static_cmd_id++;
-                action->menuHandle = subMenuHandle;
-                actionItemsClassic.last().append(action);
-                qt_wce_insert_action(subMenuHandle, action);
-            }
-        }
-        for (int i = actions.size();i<maxEntries;++i) {
-            qt_wce_rename_menu_item(menubarHandle, menu_ids.at(i), QString());
-            qt_wce_disable_soft_key(menubarHandle, menu_ids.at(i));
-        }
-    } else {
-        leftButtonAction = d->defaultAction;
-        if (!leftButtonAction)
-            leftButtonAction = qt_wce_get_quit_action(actionItems);
-
-        leftButtonIsMenu = (leftButtonAction && leftButtonAction->menu());
-        Q_ASSERT_X(menubarHandle, "rebuild !created", "menubar already deleted");
-        qt_wce_clear_menu(menuHandle);
-        DestroyWindow(menubarHandle);
-        if (leftButtonIsMenu) {
-            menubarHandle = qt_wce_create_menubar(parentWindowHandle, qt_wce_get_module_handle(), IDR_MAIN_MENU2);
-            Q_ASSERT_X(menubarHandle, "rebuild !created left menubar", "cannot create menubar from resource");
-            menuHandle = (HMENU) SendMessage(menubarHandle, SHCMBM_GETSUBMENU,0,IDM_MENU);
-            Q_ASSERT_X(menuHandle, "rebuild !created", "IDM_MENU not found - invalid resource?");
-            DeleteMenu(menuHandle, IDM_ABOUT, MF_BYCOMMAND);
-            leftButtonMenuHandle = (HMENU) SendMessage(menubarHandle, SHCMBM_GETSUBMENU,0,IDM_LEFTMENU);
-            Q_ASSERT_X(leftButtonMenuHandle, "rebuild !created", "IDM_LEFTMENU not found - invalid resource?");
-            DeleteMenu(leftButtonMenuHandle, IDM_VIEW, MF_BYCOMMAND);
-        } else {
-            menubarHandle = qt_wce_create_menubar(parentWindowHandle, qt_wce_get_module_handle(), IDR_MAIN_MENU);
-            Q_ASSERT_X(menubarHandle, "rebuild !created no left menubar", "cannot create menubar from resource");
-            menuHandle = (HMENU) SendMessage(menubarHandle, SHCMBM_GETSUBMENU,0,IDM_MENU);
-            Q_ASSERT_X(menuHandle, "rebuild !created", "IDM_MENU not found - invalid resource?");
-            DeleteMenu(menuHandle, IDM_ABOUT, MF_BYCOMMAND);
-            leftButtonMenuHandle = 0;
-            leftButtonCommand = qt_wce_menu_static_cmd_id++;
-            qt_wce_change_command(menubarHandle, IDM_EXIT, leftButtonCommand);
-        }
-
-        if (actionItems.size() == 0) {
-            qt_wce_rename_menu_item(menubarHandle, IDM_MENU, QLatin1String(""));
-            qt_wce_disable_soft_key(menubarHandle, IDM_MENU);
-        }
-        for (int i = 0; i < actionItems.size(); ++i) {
-            QWceMenuAction *action = actionItems.at(i);
-            action->menuHandle = menuHandle;
-            qt_wce_insert_action(menuHandle, action);
-        }
-        if (!leftButtonIsMenu) {
-            if (leftButtonAction) {
-                qt_wce_rename_menu_item(menubarHandle, leftButtonCommand, leftButtonAction->text());
-                qt_wce_enable_soft_key(menubarHandle, leftButtonCommand);
-            } else {
-                qt_wce_rename_menu_item(menubarHandle, leftButtonCommand, QLatin1String(""));           
-                qt_wce_disable_soft_key(menubarHandle, leftButtonCommand);
-            }
-        } else {
-            qt_wce_rename_menu_item(menubarHandle, IDM_LEFTMENU, leftButtonAction->text());
-            QList<QAction *> actions = leftButtonAction->menu()->actions();
-            qt_wce_delete_action_list(&actionItemsLeftButton);
-            for (int i=0; i<actions.size(); ++i) {
-                QWceMenuAction *action = new QWceMenuAction;
-                action->action = actions.at(i);
-                action->command = qt_wce_menu_static_cmd_id++;
-                action->menuHandle = leftButtonMenuHandle;
-                actionItemsLeftButton.append(action);
-                qt_wce_insert_action(leftButtonMenuHandle, action);
-            }
-        }
-    }
-    DrawMenuBar(menubarHandle);
-}
-
-QT_END_NAMESPACE
-
-#endif //QT_NO_MENUBAR
-#endif //Q_WS_WINCE
diff --git a/src/gui/widgets/qmenu_wince.rc b/src/gui/widgets/qmenu_wince.rc
deleted file mode 100644 (file)
index 2540d9f..0000000
+++ /dev/null
@@ -1,231 +0,0 @@
-#include "qmenu_wince_resource_p.h"
-
-#include <commctrl.h>
-#include "winuser.h"
-
-#if defined (_DEBUG) && defined(QT_DLL)
-#include "QtGuid_resource.rc"
-#elif defined(QT_DLL)
-#include "QtGui_resource.rc"
-#endif
-
-#define DIALOGEX        DIALOG DISCARDABLE
-#define SHMENUBAR       RCDATA
-#define I_IMAGENONE     (-2)
-#define NOMENU          0xFFFF
-
-IDR_MAIN_MENU MENU DISCARDABLE 
-BEGIN
-    POPUP "Menu"
-    BEGIN
-      MENUITEM "About",                       IDM_ABOUT  
-    END
-END
-
-IDR_MAIN_MENU2 MENU DISCARDABLE 
-BEGIN
-    POPUP "Menu"
-    BEGIN
-      MENUITEM "About",                       IDM_ABOUT  
-    END
-    POPUP "Display"
-    BEGIN
-      MENUITEM "View",                        IDM_VIEW
-    END
-END
-
-
-IDR_MAIN_MENU3 MENU DISCARDABLE 
-BEGIN
-    POPUP "Menu1"
-    BEGIN
-      MENUITEM "Item1",                       IDM_ITEM1
-    END
-    POPUP "Menu2"
-    BEGIN
-      MENUITEM "Item2",                       IDM_ITEM2
-    END
-    POPUP "Menu3"
-    BEGIN
-      MENUITEM "Item3",                       IDM_ITEM3
-    END
-    POPUP "Menu4"
-    BEGIN
-      MENUITEM "Item4",                       IDM_ITEM4
-    END
-END
-
-IDR_MAIN_MENU4 MENU DISCARDABLE 
-BEGIN
-    POPUP "Menu1"
-    BEGIN
-      MENUITEM "Item1",                       IDM_ITEM1
-    END
-    POPUP "Menu2"
-    BEGIN
-      MENUITEM "Item2",                       IDM_ITEM2
-    END
-    POPUP "Menu3"
-    BEGIN
-      MENUITEM "Item3",                       IDM_ITEM3
-    END
-    POPUP "Menu4"
-    BEGIN
-      MENUITEM "Item4",                       IDM_ITEM4
-    END
-    POPUP "Menu5"
-    BEGIN
-      MENUITEM "Item5",                       IDM_ITEM5
-    END
-    POPUP "Menu6"
-    BEGIN
-      MENUITEM "Item6",                       IDM_ITEM6
-    END
-END
-
-IDR_MAIN_MENU5 MENU DISCARDABLE 
-BEGIN
-    POPUP "Menu1"
-    BEGIN
-      MENUITEM "Item1",                       IDM_ITEM1
-    END
-    POPUP "Menu2"
-    BEGIN
-      MENUITEM "Item2",                       IDM_ITEM2
-    END
-    POPUP "Menu3"
-    BEGIN
-      MENUITEM "Item3",                       IDM_ITEM3
-    END
-    POPUP "Menu4"
-    BEGIN
-      MENUITEM "Item4",                       IDM_ITEM4
-    END
-    POPUP "Menu5"
-    BEGIN
-      MENUITEM "Item5",                       IDM_ITEM5
-    END
-    POPUP "Menu6"
-    BEGIN
-      MENUITEM "Item6",                       IDM_ITEM6
-    END
-    POPUP "Menu7"
-    BEGIN
-      MENUITEM "Item7",                       IDM_ITEM7
-    END
-    POPUP "Menu8"
-    BEGIN
-      MENUITEM "Item8",                       IDM_ITEM8
-    END
-END
-
-STRINGTABLE  
-BEGIN   
-   IDS_EXIT    "Exit"
-   IDS_MENU    "Menu"
-   IDS_LEFTMENU "Display"
-   IDS_MENU1   "Menu__1"
-   IDS_MENU2   "Menu__2"
-   IDS_MENU3   "Menu__3"
-   IDS_MENU4   "Menu__4"
-   IDS_MENU5   "Menu__5"
-   IDS_MENU6   "Menu__6"
-   IDS_MENU7   "Menu__7"
-   IDS_MENU8   "Menu__8"
-END
-
-IDR_MAIN_MENU SHMENUBAR DISCARDABLE
-BEGIN
-    IDR_MAIN_MENU, 
-    2,
-
-    I_IMAGENONE, IDM_EXIT, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE,
-    IDS_EXIT, 0, NOMENU,
-    
-    I_IMAGENONE, IDM_MENU, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU, 0, 0,
-END
-
-IDR_MAIN_MENU2 SHMENUBAR DISCARDABLE
-BEGIN
-    IDR_MAIN_MENU2, 
-    2,
-
-    I_IMAGENONE, IDM_LEFTMENU, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_LEFTMENU, 0, 1,
-    
-    I_IMAGENONE, IDM_MENU, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU, 0, 0,
-END
-
-IDR_MAIN_MENU3 SHMENUBAR DISCARDABLE
-BEGIN
-    IDR_MAIN_MENU3, 
-    4,
-
-    I_IMAGENONE, IDM_MENU1, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU1, 0, 0,
-
-    I_IMAGENONE, IDM_MENU2, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU2, 0, 1,
-
-    I_IMAGENONE, IDM_MENU3, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU3, 0, 2,
-
-    I_IMAGENONE, IDM_MENU4, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU4, 0, 3,
-END
-
-IDR_MAIN_MENU4 SHMENUBAR DISCARDABLE
-BEGIN
-    IDR_MAIN_MENU4, 
-    6,
-
-    I_IMAGENONE, IDM_MENU1, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU1, 0, 0,
-
-    I_IMAGENONE, IDM_MENU2, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU2, 0, 1,
-
-    I_IMAGENONE, IDM_MENU3, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU3, 0, 2,
-
-    I_IMAGENONE, IDM_MENU4, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU4, 0, 3,
-
-    I_IMAGENONE, IDM_MENU5, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU5, 0, 4,
-
-    I_IMAGENONE, IDM_MENU6, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU6, 0, 5,
-END
-
-IDR_MAIN_MENU5 SHMENUBAR DISCARDABLE
-BEGIN
-    IDR_MAIN_MENU5, 
-    8,
-
-    I_IMAGENONE, IDM_MENU1, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU1, 0, 0,
-
-    I_IMAGENONE, IDM_MENU2, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU2, 0, 1,
-
-    I_IMAGENONE, IDM_MENU3, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU3, 0, 2,
-
-    I_IMAGENONE, IDM_MENU4, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU4, 0, 3,
-
-    I_IMAGENONE, IDM_MENU5, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU5, 0, 4,
-
-    I_IMAGENONE, IDM_MENU6, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU6, 0, 5,
-
-    I_IMAGENONE, IDM_MENU7, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU7, 0, 6,
-
-    I_IMAGENONE, IDM_MENU8, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
-    IDS_MENU8, 0, 7,
-END
diff --git a/src/gui/widgets/qmenu_wince_resource_p.h b/src/gui/widgets/qmenu_wince_resource_p.h
deleted file mode 100644 (file)
index a260031..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-QT_BEGIN_HEADER        
-
-#define IDR_MAIN_MENU       102
-#define IDR_MAIN_MENU2      103
-#define IDR_MAIN_MENU3      104
-#define IDS_EXIT            105
-#define IDS_MENU            106
-#define IDS_LEFTMENU        107
-#define IDM_ABOUT           108
-#define IDM_VIEW            109
-#define IDM_ITEM1           108
-#define IDM_ITEM2           109
-#define IDM_ITEM3           110
-#define IDM_ITEM4           111
-#define IDM_ITEM5           112
-#define IDM_ITEM6           113
-#define IDM_ITEM7           114
-#define IDM_ITEM8           115
-#define IDS_MENU1           116
-#define IDS_MENU2           117
-#define IDS_MENU3           118
-#define IDS_MENU4           119
-#define IDS_MENU5           120
-#define IDS_MENU6           121
-#define IDS_MENU7           122
-#define IDS_MENU8           123
-#define IDR_MAIN_MENU4      124
-#define IDR_MAIN_MENU5      125
-#define IDM_EXIT            40000
-#define IDM_MENU            40001
-#define IDM_LEFTMENU        40002
-#define IDM_MENU1           40003
-#define IDM_MENU2           40004
-#define IDM_MENU3           40005
-#define IDM_MENU4           40006
-#define IDM_MENU5           40007
-#define IDM_MENU6           40008
-#define IDM_MENU7           40009
-#define IDM_MENU8           40010
-
-QT_END_HEADER
-
diff --git a/src/multimedia/audio/qaudio_mac.cpp b/src/multimedia/audio/qaudio_mac.cpp
deleted file mode 100644 (file)
index a1b231a..0000000
+++ /dev/null
@@ -1,145 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtMultimedia 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "qaudio_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-// Debugging
-QDebug operator<<(QDebug dbg, const QAudioFormat& audioFormat)
-{
-    dbg.nospace() << "QAudioFormat(" <<
-            audioFormat.frequency() << "," <<
-            audioFormat.channels() << "," <<
-            audioFormat.sampleSize()<< "," <<
-            audioFormat.codec() << "," <<
-            audioFormat.byteOrder() << "," <<
-            audioFormat.sampleType() << ")";
-
-    return dbg.space();
-}
-
-
-// Conversion
-QAudioFormat toQAudioFormat(AudioStreamBasicDescription const& sf)
-{
-    QAudioFormat    audioFormat;
-
-    audioFormat.setFrequency(sf.mSampleRate);
-    audioFormat.setChannels(sf.mChannelsPerFrame);
-    audioFormat.setSampleSize(sf.mBitsPerChannel);
-    audioFormat.setCodec(QString::fromLatin1("audio/pcm"));
-    audioFormat.setByteOrder((sf.mFormatFlags & kAudioFormatFlagIsBigEndian) != 0 ? QAudioFormat::BigEndian : QAudioFormat::LittleEndian);
-    QAudioFormat::SampleType type = QAudioFormat::UnSignedInt;
-    if ((sf.mFormatFlags & kAudioFormatFlagIsSignedInteger) != 0)
-        type = QAudioFormat::SignedInt;
-    else if ((sf.mFormatFlags & kAudioFormatFlagIsFloat) != 0)
-        type = QAudioFormat::Float;
-    audioFormat.setSampleType(type);
-
-    return audioFormat;
-}
-
-AudioStreamBasicDescription toAudioStreamBasicDescription(QAudioFormat const& audioFormat)
-{
-    AudioStreamBasicDescription sf;
-
-    sf.mFormatFlags         = kAudioFormatFlagIsPacked;
-    sf.mSampleRate          = audioFormat.frequency();
-    sf.mFramesPerPacket     = 1;
-    sf.mChannelsPerFrame    = audioFormat.channels();
-    sf.mBitsPerChannel      = audioFormat.sampleSize();
-    sf.mBytesPerFrame       = sf.mChannelsPerFrame * (sf.mBitsPerChannel / 8);
-    sf.mBytesPerPacket      = sf.mFramesPerPacket * sf.mBytesPerFrame;
-    sf.mFormatID            = kAudioFormatLinearPCM;
-
-    switch (audioFormat.sampleType()) {
-    case QAudioFormat::SignedInt: sf.mFormatFlags |= kAudioFormatFlagIsSignedInteger; break;
-    case QAudioFormat::UnSignedInt: /* default */ break;
-    case QAudioFormat::Float: sf.mFormatFlags |= kAudioFormatFlagIsFloat; break;
-    case QAudioFormat::Unknown:  default: break;
-    }
-
-    if (audioFormat.byteOrder() == QAudioFormat::BigEndian)
-        sf.mFormatFlags |= kAudioFormatFlagIsBigEndian;
-
-    return sf;
-}
-
-// QAudioRingBuffer
-QAudioRingBuffer::QAudioRingBuffer(int bufferSize):
-    m_bufferSize(bufferSize)
-{
-    m_buffer = new char[m_bufferSize];
-    reset();
-}
-
-QAudioRingBuffer::~QAudioRingBuffer()
-{
-    delete m_buffer;
-}
-
-int QAudioRingBuffer::used() const
-{
-    return m_bufferUsed;
-}
-
-int QAudioRingBuffer::free() const
-{
-    return m_bufferSize - m_bufferUsed;
-}
-
-int QAudioRingBuffer::size() const
-{
-    return m_bufferSize;
-}
-
-void QAudioRingBuffer::reset()
-{
-    m_readPos = 0;
-    m_writePos = 0;
-    m_bufferUsed = 0;
-}
-
-QT_END_NAMESPACE
-
-
diff --git a/src/multimedia/audio/qaudio_mac_p.h b/src/multimedia/audio/qaudio_mac_p.h
deleted file mode 100644 (file)
index 9fb21e0..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtMultimedia 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 QAUDIO_MAC_P_H
-#define QAUDIO_MAC_P_H
-
-#include <CoreAudio/CoreAudio.h>
-
-#include <QtCore/qdebug.h>
-#include <QtCore/qatomic.h>
-
-#include <QtMultimedia/qaudioformat.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-
-
-extern QDebug operator<<(QDebug dbg, const QAudioFormat& audioFormat);
-
-extern QAudioFormat toQAudioFormat(const AudioStreamBasicDescription& streamFormat);
-extern AudioStreamBasicDescription toAudioStreamBasicDescription(QAudioFormat const& audioFormat);
-
-class QAudioRingBuffer
-{
-public:
-    typedef QPair<char*, int> Region;
-
-    QAudioRingBuffer(int bufferSize);
-    ~QAudioRingBuffer();
-
-    Region acquireReadRegion(int size)
-    {
-        const int used = m_bufferUsed.fetchAndAddAcquire(0);
-
-        if (used > 0) {
-            const int readSize = qMin(size, qMin(m_bufferSize - m_readPos, used));
-
-            return readSize > 0 ? Region(m_buffer + m_readPos, readSize) : Region(0, 0);
-        }
-
-        return Region(0, 0);
-    }
-
-    void releaseReadRegion(Region const& region)
-    {
-        m_readPos = (m_readPos + region.second) % m_bufferSize;
-
-        m_bufferUsed.fetchAndAddRelease(-region.second);
-    }
-
-    Region acquireWriteRegion(int size)
-    {
-        const int free = m_bufferSize - m_bufferUsed.fetchAndAddAcquire(0);
-
-        if (free > 0) {
-            const int writeSize = qMin(size, qMin(m_bufferSize - m_writePos, free));
-
-            return writeSize > 0 ? Region(m_buffer + m_writePos, writeSize) : Region(0, 0);
-        }
-
-        return Region(0, 0);
-    }
-
-    void releaseWriteRegion(Region const& region)
-    {
-        m_writePos = (m_writePos + region.second) % m_bufferSize;
-
-        m_bufferUsed.fetchAndAddRelease(region.second);
-    }
-
-    int used() const;
-    int free() const;
-    int size() const;
-
-    void reset();
-
-private:
-    int     m_bufferSize;
-    int     m_readPos;
-    int     m_writePos;
-    char*   m_buffer;
-    QAtomicInt  m_bufferUsed;
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif  // QAUDIO_MAC_P_H
-
-
diff --git a/src/multimedia/audio/qaudiodeviceinfo_mac_p.cpp b/src/multimedia/audio/qaudiodeviceinfo_mac_p.cpp
deleted file mode 100644 (file)
index ac028dc..0000000
+++ /dev/null
@@ -1,363 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtMultimedia 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#include <QtCore/qstringlist.h>
-#include <QtCore/qlist.h>
-#include <QtCore/qbytearray.h>
-#include <QtCore/qdatastream.h>
-#include <QtCore/qdebug.h>
-#include <qcore_mac_p.h>
-
-#include <QtMultimedia/qaudiodeviceinfo.h>
-#include "qaudio_mac_p.h"
-#include "qaudiodeviceinfo_mac_p.h"
-
-
-
-QT_BEGIN_NAMESPACE
-
-
-QAudioDeviceInfoInternal::QAudioDeviceInfoInternal(QByteArray const& handle, QAudio::Mode)
-{
-    QDataStream ds(handle);
-    quint32 did, tm;
-
-    ds >> did >> tm >> name;
-    deviceId = AudioDeviceID(did);
-    mode = QAudio::Mode(tm);
-}
-
-bool QAudioDeviceInfoInternal::isFormatSupported(const QAudioFormat& format) const
-{
-    QAudioDeviceInfoInternal *self = const_cast<QAudioDeviceInfoInternal*>(this);
-
-    return format.isValid()
-            && format.codec() == QString::fromLatin1("audio/pcm")
-            && self->frequencyList().contains(format.frequency())
-            && self->channelsList().contains(format.channels())
-            && self->sampleSizeList().contains(format.sampleSize());
-}
-
-QAudioFormat QAudioDeviceInfoInternal::preferredFormat() const
-{
-    QAudioFormat    rc;
-
-    UInt32  propSize = 0;
-
-    if (AudioDeviceGetPropertyInfo(deviceId,
-                                    0,
-                                    mode == QAudio::AudioInput,
-                                    kAudioDevicePropertyStreams,
-                                    &propSize,
-                                    0) == noErr) {
-
-        const int sc = propSize / sizeof(AudioStreamID);
-
-        if (sc > 0) {
-            AudioStreamID*  streams = new AudioStreamID[sc];
-
-            if (AudioDeviceGetProperty(deviceId,
-                                        0,
-                                        mode == QAudio::AudioInput,
-                                        kAudioDevicePropertyStreams,
-                                        &propSize,
-                                        streams) == noErr) {
-
-                for (int i = 0; i < sc; ++i) {
-                    if (AudioStreamGetPropertyInfo(streams[i],
-                                                    0,
-                                                    kAudioStreamPropertyPhysicalFormat,
-                                                    &propSize,
-                                                    0) == noErr) {
-
-                        AudioStreamBasicDescription sf;
-
-                        if (AudioStreamGetProperty(streams[i],
-                                                    0,
-                                                    kAudioStreamPropertyPhysicalFormat,
-                                                    &propSize,
-                                                    &sf) == noErr) {
-                            rc = toQAudioFormat(sf);
-                            break;
-                        }
-                    }
-                }
-            }
-
-            delete[] streams;
-        }
-    }
-
-    return rc;
-}
-
-QAudioFormat QAudioDeviceInfoInternal::nearestFormat(const QAudioFormat& format) const
-{
-    QAudioFormat    rc(format);
-    QAudioFormat    target = preferredFormat();
-
-    if (!format.codec().isEmpty() && format.codec() != QString::fromLatin1("audio/pcm"))
-        return QAudioFormat();
-
-    rc.setCodec(QString::fromLatin1("audio/pcm"));
-
-    if (rc.frequency() != target.frequency())
-        rc.setFrequency(target.frequency());
-    if (rc.channels() != target.channels())
-        rc.setChannels(target.channels());
-    if (rc.sampleSize() != target.sampleSize())
-        rc.setSampleSize(target.sampleSize());
-    if (rc.byteOrder() != target.byteOrder())
-        rc.setByteOrder(target.byteOrder());
-    if (rc.sampleType() != target.sampleType())
-        rc.setSampleType(target.sampleType());
-
-    return rc;
-}
-
-QString QAudioDeviceInfoInternal::deviceName() const
-{
-    return name;
-}
-
-QStringList QAudioDeviceInfoInternal::codecList()
-{
-    return QStringList() << QString::fromLatin1("audio/pcm");
-}
-
-QList<int> QAudioDeviceInfoInternal::frequencyList()
-{
-    QSet<int>  rc;
-
-    // Add some common frequencies
-    rc << 8000 << 11025 << 22050 << 44100;
-
-    //
-    UInt32  propSize = 0;
-
-    if (AudioDeviceGetPropertyInfo(deviceId,
-                                    0,
-                                    mode == QAudio::AudioInput,
-                                    kAudioDevicePropertyAvailableNominalSampleRates,
-                                    &propSize,
-                                    0) == noErr) {
-
-        const int pc = propSize / sizeof(AudioValueRange);
-
-        if (pc > 0) {
-            AudioValueRange*    vr = new AudioValueRange[pc];
-
-            if (AudioDeviceGetProperty(deviceId,
-                                        0,
-                                        mode == QAudio::AudioInput,
-                                        kAudioDevicePropertyAvailableNominalSampleRates,
-                                        &propSize,
-                                        vr) == noErr) {
-
-                for (int i = 0; i < pc; ++i)
-                    rc << vr[i].mMaximum;
-            }
-
-            delete[] vr;
-        }
-    }
-
-    return rc.toList();
-}
-
-QList<int> QAudioDeviceInfoInternal::channelsList()
-{
-    QList<int>  rc;
-
-    // Can mix down to 1 channel
-    rc << 1;
-
-    UInt32  propSize = 0;
-    int     channels = 0;
-
-    if (AudioDeviceGetPropertyInfo(deviceId, 
-                                    0,
-                                    mode == QAudio::AudioInput,
-                                    kAudioDevicePropertyStreamConfiguration,
-                                    &propSize, 
-                                    0) == noErr) {
-
-        AudioBufferList* audioBufferList = static_cast<AudioBufferList*>(malloc(propSize));
-
-        if (audioBufferList != 0) {
-            if (AudioDeviceGetProperty(deviceId, 
-                                        0,
-                                        mode == QAudio::AudioInput,
-                                        kAudioDevicePropertyStreamConfiguration,
-                                        &propSize,
-                                        audioBufferList) == noErr) {
-
-                for (int i = 0; i < int(audioBufferList->mNumberBuffers); ++i) {
-                    channels += audioBufferList->mBuffers[i].mNumberChannels;
-                    rc << channels;
-                }
-            }
-
-            free(audioBufferList);
-        }
-    }
-
-    return rc;
-}
-
-QList<int> QAudioDeviceInfoInternal::sampleSizeList()
-{
-    return QList<int>() << 8 << 16 << 24 << 32 << 64;
-}
-
-QList<QAudioFormat::Endian> QAudioDeviceInfoInternal::byteOrderList()
-{
-    return QList<QAudioFormat::Endian>() << QAudioFormat::LittleEndian << QAudioFormat::BigEndian;
-}
-
-QList<QAudioFormat::SampleType> QAudioDeviceInfoInternal::sampleTypeList()
-{
-    return QList<QAudioFormat::SampleType>() << QAudioFormat::SignedInt << QAudioFormat::UnSignedInt << QAudioFormat::Float;
-}
-
-static QByteArray get_device_info(AudioDeviceID audioDevice, QAudio::Mode mode)
-{
-    UInt32      size;
-    QByteArray  device;
-    QDataStream ds(&device, QIODevice::WriteOnly);
-    AudioStreamBasicDescription     sf;
-    CFStringRef name;
-    Boolean     isInput = mode == QAudio::AudioInput;
-
-    // Id
-    ds << quint32(audioDevice);
-
-    // Mode
-    size = sizeof(AudioStreamBasicDescription);
-    if (AudioDeviceGetProperty(audioDevice, 0, isInput, kAudioDevicePropertyStreamFormat,
-                                &size, &sf) != noErr) {
-        return QByteArray();
-    }
-    ds << quint32(mode);
-
-    // Name
-    size = sizeof(CFStringRef);
-    if (AudioDeviceGetProperty(audioDevice, 0, isInput, kAudioObjectPropertyName,
-                                &size, &name) != noErr) {
-        qWarning() << "QAudioDeviceInfo: Unable to find device name";
-    }
-    ds << QCFString::toQString(name);
-
-    CFRelease(name);
-
-    return device;
-}
-
-QByteArray QAudioDeviceInfoInternal::defaultInputDevice()
-{
-    AudioDeviceID   audioDevice;
-    UInt32          size = sizeof(audioDevice);
-
-    if (AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &size,
-                                    &audioDevice) != noErr) {
-        qWarning() << "QAudioDeviceInfo: Unable to find default input device";
-        return QByteArray();
-    }
-
-    return get_device_info(audioDevice, QAudio::AudioInput);
-}
-
-QByteArray QAudioDeviceInfoInternal::defaultOutputDevice()
-{
-    AudioDeviceID audioDevice;
-    UInt32        size = sizeof(audioDevice);
-
-    if (AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &size,
-                                    &audioDevice) != noErr) {
-        qWarning() << "QAudioDeviceInfo: Unable to find default output device";
-        return QByteArray();
-    }
-
-    return get_device_info(audioDevice, QAudio::AudioOutput);
-}
-
-QList<QByteArray> QAudioDeviceInfoInternal::availableDevices(QAudio::Mode mode)
-{
-    QList<QByteArray>   devices;
-
-    UInt32  propSize = 0;
-
-    if (AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propSize, 0) == noErr) {
-
-        const int dc = propSize / sizeof(AudioDeviceID);
-
-        if (dc > 0) {
-            AudioDeviceID*  audioDevices = new AudioDeviceID[dc];
-
-            if (AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propSize, audioDevices) == noErr) {
-                for (int i = 0; i < dc; ++i) {
-                    QByteArray info = get_device_info(audioDevices[i], mode);
-                    if (!info.isNull())
-                        devices << info;
-                }
-            }
-
-            delete[] audioDevices;
-        }
-    }
-
-    return devices;
-}
-
-
-QT_END_NAMESPACE
-
diff --git a/src/multimedia/audio/qaudiodeviceinfo_mac_p.h b/src/multimedia/audio/qaudiodeviceinfo_mac_p.h
deleted file mode 100644 (file)
index 975724d..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtMultimedia 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 QDEVICEINFO_MAC_P_H
-#define QDEVICEINFO_MAC_P_H
-
-#include <CoreAudio/CoreAudio.h>
-
-#include <QtMultimedia/qaudioengine.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QAudioDeviceInfoInternal : public QAbstractAudioDeviceInfo
-{
-public:
-    AudioDeviceID   deviceId;
-    QString         name;
-    QAudio::Mode   mode;
-
-    QAudioDeviceInfoInternal(QByteArray const& handle, QAudio::Mode mode);
-
-    bool isFormatSupported(const QAudioFormat& format) const;
-    QAudioFormat preferredFormat() const;
-    QAudioFormat nearestFormat(const QAudioFormat& format) const;
-
-    QString deviceName() const;
-
-    QStringList codecList();
-    QList<int> frequencyList();
-    QList<int> channelsList();
-    QList<int> sampleSizeList();
-    QList<QAudioFormat::Endian> byteOrderList();
-    QList<QAudioFormat::SampleType> sampleTypeList();
-
-    static QByteArray defaultInputDevice();
-    static QByteArray defaultOutputDevice();
-
-    static QList<QByteArray> availableDevices(QAudio::Mode mode);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif  // QDEVICEINFO_MAC_P_H
diff --git a/src/multimedia/audio/qaudioinput_mac_p.cpp b/src/multimedia/audio/qaudioinput_mac_p.cpp
deleted file mode 100644 (file)
index 010d10c..0000000
+++ /dev/null
@@ -1,957 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtMultimedia 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#include <QtCore/qendian.h>
-#include <QtCore/qtimer.h>
-#include <QtCore/qdebug.h>
-
-#include <QtMultimedia/qaudioinput.h>
-
-#include "qaudio_mac_p.h"
-#include "qaudioinput_mac_p.h"
-#include "qaudiodeviceinfo_mac_p.h"
-
-QT_BEGIN_NAMESPACE
-
-
-namespace QtMultimediaInternal
-{
-
-static const int default_buffer_size = 4 * 1024;
-
-class QAudioBufferList
-{
-public:
-    QAudioBufferList(AudioStreamBasicDescription const& streamFormat):
-        owner(false),
-        sf(streamFormat)
-    {
-        const bool isInterleaved = (sf.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0;
-        const int numberOfBuffers = isInterleaved ? 1 : sf.mChannelsPerFrame;
-
-        dataSize = 0;
-
-        bfs = reinterpret_cast<AudioBufferList*>(malloc(sizeof(AudioBufferList) +
-                                                                (sizeof(AudioBuffer) * numberOfBuffers)));
-
-        bfs->mNumberBuffers = numberOfBuffers;
-        for (int i = 0; i < numberOfBuffers; ++i) {
-            bfs->mBuffers[i].mNumberChannels = isInterleaved ? numberOfBuffers : 1;
-            bfs->mBuffers[i].mDataByteSize = 0;
-            bfs->mBuffers[i].mData = 0;
-        }
-    }
-
-    QAudioBufferList(AudioStreamBasicDescription const& streamFormat, char* buffer, int bufferSize):
-        owner(false),
-        sf(streamFormat),
-        bfs(0)
-    {
-        dataSize = bufferSize;
-
-        bfs = reinterpret_cast<AudioBufferList*>(malloc(sizeof(AudioBufferList) + sizeof(AudioBuffer)));
-
-        bfs->mNumberBuffers = 1;
-        bfs->mBuffers[0].mNumberChannels = 1;
-        bfs->mBuffers[0].mDataByteSize = dataSize;
-        bfs->mBuffers[0].mData = buffer;
-    }
-
-    QAudioBufferList(AudioStreamBasicDescription const& streamFormat, int framesToBuffer):
-        owner(true),
-        sf(streamFormat),
-        bfs(0)
-    {
-        const bool isInterleaved = (sf.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0;
-        const int numberOfBuffers = isInterleaved ? 1 : sf.mChannelsPerFrame;
-
-        dataSize = framesToBuffer * sf.mBytesPerFrame;
-
-        bfs = reinterpret_cast<AudioBufferList*>(malloc(sizeof(AudioBufferList) +
-                                                                (sizeof(AudioBuffer) * numberOfBuffers)));
-        bfs->mNumberBuffers = numberOfBuffers;
-        for (int i = 0; i < numberOfBuffers; ++i) {
-            bfs->mBuffers[i].mNumberChannels = isInterleaved ? numberOfBuffers : 1;
-            bfs->mBuffers[i].mDataByteSize = dataSize;
-            bfs->mBuffers[i].mData = malloc(dataSize);
-        }
-    }
-
-    ~QAudioBufferList()
-    {
-        if (owner) {
-            for (UInt32 i = 0; i < bfs->mNumberBuffers; ++i)
-                free(bfs->mBuffers[i].mData);
-        }
-
-        free(bfs);
-    }
-
-    AudioBufferList* audioBufferList() const
-    {
-        return bfs;
-    }
-
-    char* data(int buffer = 0) const
-    {
-        return static_cast<char*>(bfs->mBuffers[buffer].mData);
-    }
-
-    qint64 bufferSize(int buffer = 0) const
-    {
-        return bfs->mBuffers[buffer].mDataByteSize;
-    }
-
-    int frameCount(int buffer = 0) const
-    {
-        return bfs->mBuffers[buffer].mDataByteSize / sf.mBytesPerFrame;
-    }
-
-    int packetCount(int buffer = 0) const
-    {
-        return bfs->mBuffers[buffer].mDataByteSize / sf.mBytesPerPacket;
-    }
-
-    int packetSize() const
-    {
-        return sf.mBytesPerPacket;
-    }
-
-    void reset()
-    {
-        for (UInt32 i = 0; i < bfs->mNumberBuffers; ++i) {
-            bfs->mBuffers[i].mDataByteSize = dataSize;
-            bfs->mBuffers[i].mData = 0;
-        }
-    }
-
-private:
-    bool    owner;
-    int     dataSize;
-    AudioStreamBasicDescription sf;
-    AudioBufferList* bfs;
-};
-
-class QAudioPacketFeeder
-{
-public:
-    QAudioPacketFeeder(QAudioBufferList* abl):
-        audioBufferList(abl)
-    {
-        totalPackets = audioBufferList->packetCount();
-        position = 0;
-    }
-
-    bool feed(AudioBufferList& dst, UInt32& packetCount)
-    {
-        if (position == totalPackets) {
-            dst.mBuffers[0].mDataByteSize = 0;
-            packetCount = 0;
-            return false;
-        }
-
-        if (totalPackets - position < packetCount)
-            packetCount = totalPackets - position;
-
-        dst.mBuffers[0].mDataByteSize = packetCount * audioBufferList->packetSize();
-        dst.mBuffers[0].mData = audioBufferList->data() + (position * audioBufferList->packetSize());
-
-        position += packetCount;
-
-        return true;
-    }
-
-    bool empty() const
-    {
-        return position == totalPackets;
-    }
-
-private:
-    UInt32 totalPackets;
-    UInt32 position;
-    QAudioBufferList*   audioBufferList;
-};
-
-class QAudioInputBuffer : public QObject
-{
-    Q_OBJECT
-
-public:
-    QAudioInputBuffer(int bufferSize,
-                        int maxPeriodSize,
-                        AudioStreamBasicDescription const& inputFormat,
-                        AudioStreamBasicDescription const& outputFormat,
-                        QObject* parent):
-        QObject(parent),
-        m_deviceError(false),
-        m_audioConverter(0),
-        m_inputFormat(inputFormat),
-        m_outputFormat(outputFormat)
-    {
-        m_maxPeriodSize = maxPeriodSize;
-        m_periodTime = m_maxPeriodSize / m_outputFormat.mBytesPerFrame * 1000 / m_outputFormat.mSampleRate;
-        m_buffer = new QAudioRingBuffer(bufferSize + (bufferSize % maxPeriodSize == 0 ? 0 : maxPeriodSize - (bufferSize % maxPeriodSize)));
-        m_inputBufferList = new QAudioBufferList(m_inputFormat);
-
-        m_flushTimer = new QTimer(this);
-        connect(m_flushTimer, SIGNAL(timeout()), SLOT(flushBuffer()));
-
-        if (toQAudioFormat(inputFormat) != toQAudioFormat(outputFormat)) {
-            if (AudioConverterNew(&m_inputFormat, &m_outputFormat, &m_audioConverter) != noErr) {
-                qWarning() << "QAudioInput: Unable to create an Audio Converter";
-                m_audioConverter = 0;
-            }
-        }
-    }
-
-    ~QAudioInputBuffer()
-    {
-        delete m_buffer;
-    }
-
-    qint64 renderFromDevice(AudioUnit audioUnit,
-                             AudioUnitRenderActionFlags* ioActionFlags,
-                             const AudioTimeStamp* inTimeStamp,
-                             UInt32 inBusNumber,
-                             UInt32 inNumberFrames)
-    {
-        const bool  pullMode = m_device == 0;
-
-        OSStatus    err;
-        qint64      framesRendered = 0;
-
-        m_inputBufferList->reset();
-        err = AudioUnitRender(audioUnit,
-                                ioActionFlags,
-                                inTimeStamp,
-                                inBusNumber,
-                                inNumberFrames,
-                                m_inputBufferList->audioBufferList());
-
-        if (m_audioConverter != 0) {
-            QAudioPacketFeeder  feeder(m_inputBufferList);
-
-            int     copied = 0;
-            const int available = m_buffer->free();
-
-            while (err == noErr && !feeder.empty()) {
-                QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(available);
-
-                if (region.second == 0)
-                    break;
-
-                AudioBufferList     output;
-                output.mNumberBuffers = 1;
-                output.mBuffers[0].mNumberChannels = 1;
-                output.mBuffers[0].mDataByteSize = region.second;
-                output.mBuffers[0].mData = region.first;
-
-                UInt32  packetSize = region.second / m_outputFormat.mBytesPerPacket;
-                err = AudioConverterFillComplexBuffer(m_audioConverter,
-                                                      converterCallback,
-                                                      &feeder,
-                                                      &packetSize,
-                                                      &output,
-                                                      0);
-                region.second = output.mBuffers[0].mDataByteSize;
-                copied += region.second;
-
-                m_buffer->releaseWriteRegion(region);
-            }
-
-            framesRendered += copied / m_outputFormat.mBytesPerFrame;
-        }
-        else {
-            const int available = m_inputBufferList->bufferSize();
-            bool    wecan = true;
-            int     copied = 0;
-
-            while (wecan && copied < available) {
-                QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(available - copied);
-
-                if (region.second > 0) {
-                    memcpy(region.first, m_inputBufferList->data() + copied, region.second);
-                    copied += region.second;
-                }
-                else
-                    wecan = false;
-
-                m_buffer->releaseWriteRegion(region);
-            }
-
-            framesRendered = copied / m_outputFormat.mBytesPerFrame;
-        }
-
-        if (pullMode && framesRendered > 0)
-            emit readyRead();
-
-        return framesRendered;
-    }
-
-    qint64 readBytes(char* data, qint64 len)
-    {
-        bool    wecan = true;
-        qint64  bytesCopied = 0;
-
-        len -= len % m_maxPeriodSize;
-        while (wecan && bytesCopied < len) {
-            QAudioRingBuffer::Region region = m_buffer->acquireReadRegion(len - bytesCopied);
-
-            if (region.second > 0) {
-                memcpy(data + bytesCopied, region.first, region.second);
-                bytesCopied += region.second;
-            }
-            else
-                wecan = false;
-
-            m_buffer->releaseReadRegion(region);
-        }
-
-        return bytesCopied;
-    }
-
-    void setFlushDevice(QIODevice* device)
-    {
-        if (m_device != device)
-            m_device = device;
-    }
-
-    void startFlushTimer()
-    {
-        if (m_device != 0) {
-            m_flushTimer->start((m_buffer->size() - (m_maxPeriodSize * 2)) / m_maxPeriodSize * m_periodTime);
-        }
-    }
-
-    void stopFlushTimer()
-    {
-        m_flushTimer->stop();
-    }
-
-    void flush(bool all = false)
-    {
-        if (m_device == 0)
-            return;
-
-        const int used = m_buffer->used();
-        const int readSize = all ? used : used - (used % m_maxPeriodSize);
-
-        if (readSize > 0) {
-            bool    wecan = true;
-            int     flushed = 0;
-
-            while (!m_deviceError && wecan && flushed < readSize) {
-                QAudioRingBuffer::Region region = m_buffer->acquireReadRegion(readSize - flushed);
-
-                if (region.second > 0) {
-                    int bytesWritten = m_device->write(region.first, region.second);
-                    if (bytesWritten < 0) {
-                        stopFlushTimer();
-                        m_deviceError = true;
-                    }
-                    else {
-                        region.second = bytesWritten;
-                        flushed += bytesWritten;
-                        wecan = bytesWritten != 0;
-                    }
-                }
-                else
-                    wecan = false;
-
-                m_buffer->releaseReadRegion(region);
-            }
-        }
-    }
-
-    void reset()
-    {
-        m_buffer->reset();
-        m_deviceError = false;
-    }
-
-    int available() const
-    {
-        return m_buffer->free();
-    }
-
-    int used() const
-    {
-        return m_buffer->used();
-    }
-
-signals:
-    void readyRead();
-
-private slots:
-    void flushBuffer()
-    {
-        flush();
-    }
-
-private:
-    bool        m_deviceError;
-    int         m_maxPeriodSize;
-    int         m_periodTime;
-    QIODevice*  m_device;
-    QTimer*     m_flushTimer;
-    QAudioRingBuffer*   m_buffer;
-    QAudioBufferList*   m_inputBufferList;
-    AudioConverterRef   m_audioConverter;
-    AudioStreamBasicDescription m_inputFormat;
-    AudioStreamBasicDescription m_outputFormat;
-
-    const static OSStatus as_empty = 'qtem';
-
-    // Converter callback
-    static OSStatus converterCallback(AudioConverterRef inAudioConverter,
-                                UInt32* ioNumberDataPackets,
-                                AudioBufferList* ioData,
-                                AudioStreamPacketDescription** outDataPacketDescription,
-                                void* inUserData)
-    {
-        Q_UNUSED(inAudioConverter);
-        Q_UNUSED(outDataPacketDescription);
-
-        QAudioPacketFeeder* feeder = static_cast<QAudioPacketFeeder*>(inUserData);
-
-        if (!feeder->feed(*ioData, *ioNumberDataPackets))
-            return as_empty;
-
-        return noErr;
-    }
-};
-
-
-class MacInputDevice : public QIODevice
-{
-    Q_OBJECT
-
-public:
-    MacInputDevice(QAudioInputBuffer* audioBuffer, QObject* parent):
-        QIODevice(parent),
-        m_audioBuffer(audioBuffer)
-    {
-        open(QIODevice::ReadOnly | QIODevice::Unbuffered);
-        connect(m_audioBuffer, SIGNAL(readyRead()), SIGNAL(readyRead()));
-    }
-
-    qint64 readData(char* data, qint64 len)
-    {
-        return m_audioBuffer->readBytes(data, len);
-    }
-
-    qint64 writeData(const char* data, qint64 len)
-    {
-        Q_UNUSED(data);
-        Q_UNUSED(len);
-
-        return 0;
-    }
-
-    bool isSequential() const
-    {
-        return true;
-    }
-
-private:
-    QAudioInputBuffer*   m_audioBuffer;
-};
-
-}
-
-
-QAudioInputPrivate::QAudioInputPrivate(const QByteArray& device, QAudioFormat const& format):
-    audioFormat(format)
-{
-    QDataStream ds(device);
-    quint32 did, mode;
-
-    ds >> did >> mode;
-
-    if (QAudio::Mode(mode) == QAudio::AudioOutput)
-        errorCode = QAudio::OpenError;
-    else {
-        audioDeviceInfo = new QAudioDeviceInfoInternal(device, QAudio::AudioInput);
-        isOpen = false;
-        audioDeviceId = AudioDeviceID(did);
-        audioUnit = 0;
-        startTime = 0;
-        totalFrames = 0;
-        audioBuffer = 0;
-        internalBufferSize = QtMultimediaInternal::default_buffer_size;
-        clockFrequency = AudioGetHostClockFrequency() / 1000;
-        errorCode = QAudio::NoError;
-        stateCode = QAudio::StoppedState;
-
-        intervalTimer = new QTimer(this);
-        intervalTimer->setInterval(1000);
-        connect(intervalTimer, SIGNAL(timeout()), SIGNAL(notify()));
-    }
-}
-
-QAudioInputPrivate::~QAudioInputPrivate()
-{
-    close();
-    delete audioDeviceInfo;
-}
-
-bool QAudioInputPrivate::open()
-{
-    UInt32  size = 0;
-
-    if (isOpen)
-        return true;
-
-    ComponentDescription    cd;
-    cd.componentType = kAudioUnitType_Output;
-    cd.componentSubType = kAudioUnitSubType_HALOutput;
-    cd.componentManufacturer = kAudioUnitManufacturer_Apple;
-    cd.componentFlags = 0;
-    cd.componentFlagsMask = 0;
-
-    // Open
-    Component cp = FindNextComponent(NULL, &cd);
-    if (cp == 0) {
-        qWarning() << "QAudioInput: Failed to find HAL Output component";
-        return false;
-    }
-
-    if (OpenAComponent(cp, &audioUnit) != noErr) {
-        qWarning() << "QAudioInput: Unable to Open Output Component";
-        return false;
-    }
-
-    // Set mode
-    // switch to input mode
-    UInt32 enable = 1;
-    if (AudioUnitSetProperty(audioUnit,
-                               kAudioOutputUnitProperty_EnableIO,
-                               kAudioUnitScope_Input,
-                               1,
-                               &enable,
-                               sizeof(enable)) != noErr) {
-        qWarning() << "QAudioInput: Unable to switch to input mode (Enable Input)";
-        return false;
-    }
-
-    enable = 0;
-    if (AudioUnitSetProperty(audioUnit,
-                            kAudioOutputUnitProperty_EnableIO,
-                            kAudioUnitScope_Output,
-                            0,
-                            &enable,
-                            sizeof(enable)) != noErr) {
-        qWarning() << "QAudioInput: Unable to switch to input mode (Disable output)";
-        return false;
-    }
-
-    // register callback
-    AURenderCallbackStruct cb;
-    cb.inputProc = inputCallback;
-    cb.inputProcRefCon = this;
-
-    if (AudioUnitSetProperty(audioUnit,
-                               kAudioOutputUnitProperty_SetInputCallback,
-                               kAudioUnitScope_Global,
-                               0,
-                               &cb,
-                               sizeof(cb)) != noErr) {
-        qWarning() << "QAudioInput: Failed to set AudioUnit callback";
-        return false;
-    }
-
-    // Set Audio Device
-    if (AudioUnitSetProperty(audioUnit,
-                                kAudioOutputUnitProperty_CurrentDevice,
-                                kAudioUnitScope_Global,
-                                0,
-                                &audioDeviceId,
-                                sizeof(audioDeviceId)) != noErr) {
-        qWarning() << "QAudioInput: Unable to use configured device";
-        return false;
-    }
-
-    // Set format
-    // Wanted
-    streamFormat = toAudioStreamBasicDescription(audioFormat);
-
-    // Required on unit
-    if (audioFormat == audioDeviceInfo->preferredFormat()) {
-        deviceFormat = streamFormat;
-        AudioUnitSetProperty(audioUnit,
-                               kAudioUnitProperty_StreamFormat,
-                               kAudioUnitScope_Output,
-                               1,
-                               &deviceFormat,
-                               sizeof(deviceFormat));
-    }
-    else {
-        size = sizeof(deviceFormat);
-        if (AudioUnitGetProperty(audioUnit,
-                                    kAudioUnitProperty_StreamFormat,
-                                    kAudioUnitScope_Input,
-                                    1,
-                                    &deviceFormat,
-                                    &size) != noErr) {
-            qWarning() << "QAudioInput: Unable to retrieve device format";
-            return false;
-        }
-
-        if (AudioUnitSetProperty(audioUnit,
-                                   kAudioUnitProperty_StreamFormat,
-                                   kAudioUnitScope_Output,
-                                   1,
-                                   &deviceFormat,
-                                   sizeof(deviceFormat)) != noErr) {
-            qWarning() << "QAudioInput: Unable to set device format";
-            return false;
-        }
-    }
-
-    // Setup buffers
-    UInt32 numberOfFrames;
-    size = sizeof(UInt32);
-    if (AudioUnitGetProperty(audioUnit,
-                                kAudioDevicePropertyBufferFrameSize,
-                                kAudioUnitScope_Global,
-                                0,
-                                &numberOfFrames,
-                                &size) != noErr) {
-        qWarning() << "QAudioInput: Failed to get audio period size";
-        return false;
-    }
-
-    // Allocate buffer
-    periodSizeBytes = numberOfFrames * streamFormat.mBytesPerFrame;
-
-    if (internalBufferSize < periodSizeBytes * 2)
-        internalBufferSize = periodSizeBytes * 2;
-    else
-        internalBufferSize -= internalBufferSize % streamFormat.mBytesPerFrame;
-
-    audioBuffer = new QtMultimediaInternal::QAudioInputBuffer(internalBufferSize,
-                                        periodSizeBytes,
-                                        deviceFormat,
-                                        streamFormat,
-                                        this);
-
-    audioIO = new QtMultimediaInternal::MacInputDevice(audioBuffer, this);
-
-    // Init
-    if (AudioUnitInitialize(audioUnit) != noErr) {
-        qWarning() << "QAudioInput: Failed to initialize AudioUnit";
-        return false;
-    }
-
-    isOpen = true;
-
-    return isOpen;
-}
-
-void QAudioInputPrivate::close()
-{
-    if (audioUnit != 0) {
-        AudioOutputUnitStop(audioUnit);
-        AudioUnitUninitialize(audioUnit);
-        CloseComponent(audioUnit);
-    }
-
-    delete audioBuffer;
-}
-
-QAudioFormat QAudioInputPrivate::format() const
-{
-    return audioFormat;
-}
-
-QIODevice* QAudioInputPrivate::start(QIODevice* device)
-{
-    QIODevice*  op = device;
-
-    if (!audioDeviceInfo->isFormatSupported(audioFormat) || !open()) {
-        stateCode = QAudio::StoppedState;
-        errorCode = QAudio::OpenError;
-        return audioIO;
-    }
-
-    reset();
-    audioBuffer->reset();
-    audioBuffer->setFlushDevice(op);
-
-    if (op == 0)
-        op = audioIO;
-
-    // Start
-    startTime = AudioGetCurrentHostTime();
-    totalFrames = 0;
-
-    audioThreadStart();
-
-    stateCode = QAudio::ActiveState;
-    errorCode = QAudio::NoError;
-    emit stateChanged(stateCode);
-
-    return op;
-}
-
-void QAudioInputPrivate::stop()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode != QAudio::StoppedState) {
-        audioThreadStop();
-        audioBuffer->flush(true);
-
-        errorCode = QAudio::NoError;
-        stateCode = QAudio::StoppedState;
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-void QAudioInputPrivate::reset()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode != QAudio::StoppedState) {
-        audioThreadStop();
-
-        errorCode = QAudio::NoError;
-        stateCode = QAudio::StoppedState;
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-void QAudioInputPrivate::suspend()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::ActiveState || stateCode == QAudio::IdleState) {
-        audioThreadStop();
-
-        errorCode = QAudio::NoError;
-        stateCode = QAudio::SuspendedState;
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-void QAudioInputPrivate::resume()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::SuspendedState) {
-        audioThreadStart();
-
-        errorCode = QAudio::NoError;
-        stateCode = QAudio::ActiveState;
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-int QAudioInputPrivate::bytesReady() const
-{
-    return audioBuffer->used();
-}
-
-int QAudioInputPrivate::periodSize() const
-{
-    return periodSizeBytes;
-}
-
-void QAudioInputPrivate::setBufferSize(int bs)
-{
-    internalBufferSize = bs;
-}
-
-int QAudioInputPrivate::bufferSize() const
-{
-    return internalBufferSize;
-}
-
-void QAudioInputPrivate::setNotifyInterval(int milliSeconds)
-{
-    if (intervalTimer->interval() == milliSeconds)
-        return;
-
-    if (milliSeconds <= 0)
-        milliSeconds = 0;
-
-    intervalTimer->setInterval(milliSeconds);
-}
-
-int QAudioInputPrivate::notifyInterval() const
-{
-    return intervalTimer->interval();
-}
-
-qint64 QAudioInputPrivate::processedUSecs() const
-{
-    return totalFrames * 1000000 / audioFormat.frequency();
-}
-
-qint64 QAudioInputPrivate::elapsedUSecs() const
-{
-    if (stateCode == QAudio::StoppedState)
-        return 0;
-
-    return (AudioGetCurrentHostTime() - startTime) / (clockFrequency / 1000);
-}
-
-QAudio::Error QAudioInputPrivate::error() const
-{
-    return errorCode;
-}
-
-QAudio::State QAudioInputPrivate::state() const
-{
-    return stateCode;
-}
-
-void QAudioInputPrivate::audioThreadStop()
-{
-    stopTimers();
-    if (audioThreadState.testAndSetAcquire(Running, Stopped))
-        threadFinished.wait(&mutex);
-}
-
-void QAudioInputPrivate::audioThreadStart()
-{
-    startTimers();
-    audioThreadState = Running;
-    AudioOutputUnitStart(audioUnit);
-}
-
-void QAudioInputPrivate::audioDeviceStop()
-{
-    AudioOutputUnitStop(audioUnit);
-    audioThreadState = Stopped;
-    threadFinished.wakeOne();
-}
-
-void QAudioInputPrivate::audioDeviceFull()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::ActiveState) {
-        audioDeviceStop();
-
-        errorCode = QAudio::UnderrunError;
-        stateCode = QAudio::IdleState;
-        QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection);
-    }
-}
-
-void QAudioInputPrivate::audioDeviceError()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::ActiveState) {
-        audioDeviceStop();
-
-        errorCode = QAudio::IOError;
-        stateCode = QAudio::StoppedState;
-        QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection);
-    }
-}
-
-void QAudioInputPrivate::startTimers()
-{
-    audioBuffer->startFlushTimer();
-    if (intervalTimer->interval() > 0)
-        intervalTimer->start();
-}
-
-void QAudioInputPrivate::stopTimers()
-{
-    audioBuffer->stopFlushTimer();
-    intervalTimer->stop();
-}
-
-void QAudioInputPrivate::deviceStopped()
-{
-    stopTimers();
-    emit stateChanged(stateCode);
-}
-
-// Input callback
-OSStatus QAudioInputPrivate::inputCallback(void* inRefCon,
-                                AudioUnitRenderActionFlags* ioActionFlags,
-                                const AudioTimeStamp* inTimeStamp,
-                                UInt32 inBusNumber,
-                                UInt32 inNumberFrames,
-                                AudioBufferList* ioData)
-{
-    Q_UNUSED(ioData);
-
-    QAudioInputPrivate* d = static_cast<QAudioInputPrivate*>(inRefCon);
-
-    const int threadState = d->audioThreadState.fetchAndAddAcquire(0);
-    if (threadState == Stopped)
-        d->audioDeviceStop();
-    else {
-        qint64      framesWritten;
-
-        framesWritten = d->audioBuffer->renderFromDevice(d->audioUnit,
-                                                         ioActionFlags,
-                                                         inTimeStamp,
-                                                         inBusNumber,
-                                                         inNumberFrames);
-
-        if (framesWritten > 0)
-            d->totalFrames += framesWritten;
-        else if (framesWritten == 0)
-            d->audioDeviceFull();
-        else if (framesWritten < 0)
-            d->audioDeviceError();
-    }
-
-    return noErr;
-}
-
-
-QT_END_NAMESPACE
-
-#include "qaudioinput_mac_p.moc"
-
diff --git a/src/multimedia/audio/qaudioinput_mac_p.h b/src/multimedia/audio/qaudioinput_mac_p.h
deleted file mode 100644 (file)
index 46a4b37..0000000
+++ /dev/null
@@ -1,169 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtMultimedia 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 QAUDIOINPUT_MAC_P_H
-#define QAUDIOINPUT_MAC_P_H
-
-#include <CoreServices/CoreServices.h>
-#include <CoreAudio/CoreAudio.h>
-#include <AudioUnit/AudioUnit.h>
-#include <AudioToolbox/AudioToolbox.h>
-
-#include <QtCore/qobject.h>
-#include <QtCore/qmutex.h>
-#include <QtCore/qwaitcondition.h>
-#include <QtCore/qatomic.h>
-
-#include <QtMultimedia/qaudio.h>
-#include <QtMultimedia/qaudioformat.h>
-#include <QtMultimedia/qaudioengine.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QTimer;
-class QIODevice;
-class QAbstractAudioDeviceInfo;
-
-namespace QtMultimediaInternal
-{
-class QAudioInputBuffer;
-}
-
-class QAudioInputPrivate : public QAbstractAudioInput
-{
-    Q_OBJECT
-
-public:
-    bool            isOpen;
-    int             periodSizeBytes;
-    int             internalBufferSize;
-    qint64          totalFrames;
-    QAudioFormat    audioFormat;
-    QIODevice*      audioIO;
-    AudioUnit       audioUnit;
-    AudioDeviceID   audioDeviceId;
-    Float64         clockFrequency;
-    UInt64          startTime;
-    QAudio::Error   errorCode;
-    QAudio::State   stateCode;
-    QtMultimediaInternal::QAudioInputBuffer*   audioBuffer;
-    QMutex          mutex;
-    QWaitCondition  threadFinished;
-    QAtomicInt      audioThreadState;
-    QTimer*         intervalTimer;
-    AudioStreamBasicDescription streamFormat;
-    AudioStreamBasicDescription deviceFormat;
-    QAbstractAudioDeviceInfo *audioDeviceInfo;
-
-    QAudioInputPrivate(const QByteArray& device, QAudioFormat const& format);
-    ~QAudioInputPrivate();
-
-    bool open();
-    void close();
-
-    QAudioFormat format() const;
-
-    QIODevice* start(QIODevice* device);
-    void stop();
-    void reset();
-    void suspend();
-    void resume();
-    void idle();
-
-    int bytesReady() const;
-    int periodSize() const;
-
-    void setBufferSize(int value);
-    int bufferSize() const;
-
-    void setNotifyInterval(int milliSeconds);
-    int notifyInterval() const;
-
-    qint64 processedUSecs() const;
-    qint64 elapsedUSecs() const;
-
-    QAudio::Error error() const;
-    QAudio::State state() const;
-
-    void audioThreadStart();
-    void audioThreadStop();
-
-    void audioDeviceStop();
-    void audioDeviceFull();
-    void audioDeviceError();
-
-    void startTimers();
-    void stopTimers();
-
-private slots:
-    void deviceStopped();
-
-private:
-    enum { Running, Stopped };
-
-    // Input callback
-    static OSStatus inputCallback(void* inRefCon,
-                                    AudioUnitRenderActionFlags* ioActionFlags,
-                                    const AudioTimeStamp* inTimeStamp,
-                                    UInt32 inBusNumber,
-                                    UInt32 inNumberFrames,
-                                    AudioBufferList* ioData);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // QAUDIOINPUT_MAC_P_H
diff --git a/src/multimedia/audio/qaudiooutput_mac_p.cpp b/src/multimedia/audio/qaudiooutput_mac_p.cpp
deleted file mode 100644 (file)
index 14dbdae..0000000
+++ /dev/null
@@ -1,703 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtMultimedia 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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.
-//
-
-#include <CoreServices/CoreServices.h>
-#include <CoreAudio/CoreAudio.h>
-#include <AudioUnit/AudioUnit.h>
-#include <AudioToolbox/AudioToolbox.h>
-
-#include <QtCore/qendian.h>
-#include <QtCore/qbuffer.h>
-#include <QtCore/qtimer.h>
-#include <QtCore/qdebug.h>
-
-#include <QtMultimedia/qaudiooutput.h>
-
-#include "qaudio_mac_p.h"
-#include "qaudiooutput_mac_p.h"
-#include "qaudiodeviceinfo_mac_p.h"
-
-
-QT_BEGIN_NAMESPACE
-
-
-namespace QtMultimediaInternal
-{
-
-static const int default_buffer_size = 8 * 1024;
-
-
-class QAudioOutputBuffer : public QObject
-{
-    Q_OBJECT
-
-public:
-    QAudioOutputBuffer(int bufferSize, int maxPeriodSize, QAudioFormat const& audioFormat):
-        m_deviceError(false),
-        m_maxPeriodSize(maxPeriodSize),
-        m_device(0)
-    {
-        m_buffer = new QAudioRingBuffer(bufferSize + (bufferSize % maxPeriodSize == 0 ? 0 : maxPeriodSize - (bufferSize % maxPeriodSize)));
-        m_bytesPerFrame = (audioFormat.sampleSize() / 8) * audioFormat.channels();
-        m_periodTime = m_maxPeriodSize / m_bytesPerFrame * 1000 / audioFormat.frequency();
-
-        m_fillTimer = new QTimer(this);
-        connect(m_fillTimer, SIGNAL(timeout()), SLOT(fillBuffer()));
-    }
-
-    ~QAudioOutputBuffer()
-    {
-        delete m_buffer;
-    }
-
-    qint64 readFrames(char* data, qint64 maxFrames)
-    {
-        bool    wecan = true;
-        qint64  framesRead = 0;
-
-        while (wecan && framesRead < maxFrames) {
-            QAudioRingBuffer::Region region = m_buffer->acquireReadRegion((maxFrames - framesRead) * m_bytesPerFrame);
-
-            if (region.second > 0) {
-                region.second -= region.second % m_bytesPerFrame;
-                memcpy(data + (framesRead * m_bytesPerFrame), region.first, region.second);
-                framesRead += region.second / m_bytesPerFrame;
-            }
-            else
-                wecan = false;
-
-            m_buffer->releaseReadRegion(region);
-        }
-
-        if (framesRead == 0 && m_deviceError)
-            framesRead = -1;
-
-        return framesRead;
-    }
-
-    qint64 writeBytes(const char* data, qint64 maxSize)
-    {
-        bool    wecan = true;
-        qint64  bytesWritten = 0;
-
-        maxSize -= maxSize % m_bytesPerFrame;
-        while (wecan && bytesWritten < maxSize) {
-            QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(maxSize - bytesWritten);
-
-            if (region.second > 0) {
-                memcpy(region.first, data + bytesWritten, region.second);
-                bytesWritten += region.second;
-            }
-            else
-                wecan = false;
-
-            m_buffer->releaseWriteRegion(region);
-        }
-
-        if (bytesWritten > 0)
-            emit readyRead();
-
-        return bytesWritten;
-    }
-
-    int available() const
-    {
-        return m_buffer->free();
-    }
-
-    void reset()
-    {
-        m_buffer->reset();
-        m_deviceError = false;
-    }
-
-    void setPrefetchDevice(QIODevice* device)
-    {
-        if (m_device != device) {
-            m_device = device;
-            if (m_device != 0)
-                fillBuffer();
-        }
-    }
-
-    void startFillTimer()
-    {
-        if (m_device != 0)
-            m_fillTimer->start(m_buffer->size() / 2 / m_maxPeriodSize * m_periodTime);
-    }
-
-    void stopFillTimer()
-    {
-        m_fillTimer->stop();
-    }
-
-signals:
-    void readyRead();
-
-private slots:
-    void fillBuffer()
-    {
-        const int free = m_buffer->free();
-        const int writeSize = free - (free % m_maxPeriodSize);
-
-        if (writeSize > 0) {
-            bool    wecan = true;
-            int     filled = 0;
-
-            while (!m_deviceError && wecan && filled < writeSize) {
-                QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(writeSize - filled);
-
-                if (region.second > 0) {
-                    region.second = m_device->read(region.first, region.second);
-                    if (region.second > 0)
-                        filled += region.second;
-                    else if (region.second == 0)
-                        wecan = false;
-                    else if (region.second < 0) {
-                        m_fillTimer->stop();
-                        region.second = 0;
-                        m_deviceError = true;
-                    }
-                }
-                else
-                    wecan = false;
-
-                m_buffer->releaseWriteRegion(region);
-            }
-
-            if (filled > 0)
-                emit readyRead();
-        }
-    }
-
-private:
-    bool        m_deviceError;
-    int         m_maxPeriodSize;
-    int         m_bytesPerFrame;
-    int         m_periodTime;
-    QIODevice*  m_device;
-    QTimer*     m_fillTimer;
-    QAudioRingBuffer*  m_buffer;
-};
-
-
-}
-
-class MacOutputDevice : public QIODevice
-{
-    Q_OBJECT
-
-public:
-    MacOutputDevice(QtMultimediaInternal::QAudioOutputBuffer* audioBuffer, QObject* parent):
-        QIODevice(parent),
-        m_audioBuffer(audioBuffer)
-    {
-        open(QIODevice::WriteOnly | QIODevice::Unbuffered);
-    }
-
-    qint64 readData(char* data, qint64 len)
-    {
-        Q_UNUSED(data);
-        Q_UNUSED(len);
-
-        return 0;
-    }
-
-    qint64 writeData(const char* data, qint64 len)
-    {
-        return m_audioBuffer->writeBytes(data, len);
-    }
-
-    bool isSequential() const
-    {
-        return true;
-    }
-
-private:
-    QtMultimediaInternal::QAudioOutputBuffer*    m_audioBuffer;
-};
-
-
-QAudioOutputPrivate::QAudioOutputPrivate(const QByteArray& device, const QAudioFormat& format):
-    audioFormat(format)
-{
-    QDataStream ds(device);
-    quint32 did, mode;
-
-    ds >> did >> mode;
-
-    if (QAudio::Mode(mode) == QAudio::AudioInput)
-        errorCode = QAudio::OpenError;
-    else {
-        audioDeviceInfo = new QAudioDeviceInfoInternal(device, QAudio::AudioOutput);
-        isOpen = false;
-        audioDeviceId = AudioDeviceID(did);
-        audioUnit = 0;
-        audioIO = 0;
-        startTime = 0;
-        totalFrames = 0;
-        audioBuffer = 0;
-        internalBufferSize = QtMultimediaInternal::default_buffer_size;
-        clockFrequency = AudioGetHostClockFrequency() / 1000;
-        errorCode = QAudio::NoError;
-        stateCode = QAudio::StoppedState;
-        audioThreadState = Stopped;
-
-        intervalTimer = new QTimer(this);
-        intervalTimer->setInterval(1000);
-        connect(intervalTimer, SIGNAL(timeout()), SIGNAL(notify()));
-    }
-}
-
-QAudioOutputPrivate::~QAudioOutputPrivate()
-{
-    delete audioDeviceInfo;
-    close();
-}
-
-bool QAudioOutputPrivate::open()
-{
-    if (errorCode != QAudio::NoError)
-        return false;
-
-    if (isOpen)
-        return true;
-
-    ComponentDescription    cd;
-    cd.componentType = kAudioUnitType_Output;
-    cd.componentSubType = kAudioUnitSubType_HALOutput;
-    cd.componentManufacturer = kAudioUnitManufacturer_Apple;
-    cd.componentFlags = 0;
-    cd.componentFlagsMask = 0;
-
-    // Open
-    Component cp = FindNextComponent(NULL, &cd);
-    if (cp == 0) {
-        qWarning() << "QAudioOutput: Failed to find HAL Output component";
-        return false;
-    }
-
-    if (OpenAComponent(cp, &audioUnit) != noErr) {
-        qWarning() << "QAudioOutput: Unable to Open Output Component";
-        return false;
-    }
-
-    // register callback
-    AURenderCallbackStruct  cb;
-    cb.inputProc = renderCallback;
-    cb.inputProcRefCon = this;
-
-    if (AudioUnitSetProperty(audioUnit,
-                               kAudioUnitProperty_SetRenderCallback,
-                               kAudioUnitScope_Global,
-                               0,
-                               &cb,
-                               sizeof(cb)) != noErr) {
-        qWarning() << "QAudioOutput: Failed to set AudioUnit callback";
-        return false;
-    }
-
-    // Set Audio Device
-    if (AudioUnitSetProperty(audioUnit,
-                                kAudioOutputUnitProperty_CurrentDevice,
-                                kAudioUnitScope_Global,
-                                0,
-                                &audioDeviceId,
-                                sizeof(audioDeviceId)) != noErr) {
-        qWarning() << "QAudioOutput: Unable to use configured device";
-        return false;
-    }
-
-    // Set stream format
-    streamFormat = toAudioStreamBasicDescription(audioFormat);
-
-    UInt32 size = sizeof(streamFormat);
-    if (AudioUnitSetProperty(audioUnit,
-                                kAudioUnitProperty_StreamFormat,
-                                kAudioUnitScope_Input,
-                                0,
-                                &streamFormat,
-                                sizeof(streamFormat)) != noErr) {
-        qWarning() << "QAudioOutput: Unable to Set Stream information";
-        return false;
-    }
-
-    // Allocate buffer
-    UInt32 numberOfFrames = 0;
-    size = sizeof(UInt32);
-    if (AudioUnitGetProperty(audioUnit,
-                                kAudioDevicePropertyBufferFrameSize,
-                                kAudioUnitScope_Global,
-                                0,
-                                &numberOfFrames,
-                                &size) != noErr) {
-        qWarning() << "QAudioInput: Failed to get audio period size";
-        return false;
-    }
-
-    periodSizeBytes = numberOfFrames * streamFormat.mBytesPerFrame;
-    if (internalBufferSize < periodSizeBytes * 2)
-        internalBufferSize = periodSizeBytes * 2;
-    else
-        internalBufferSize -= internalBufferSize % streamFormat.mBytesPerFrame;
-
-    audioBuffer = new QtMultimediaInternal::QAudioOutputBuffer(internalBufferSize, periodSizeBytes, audioFormat);
-    connect(audioBuffer, SIGNAL(readyRead()), SLOT(inputReady()));  // Pull
-
-    audioIO = new MacOutputDevice(audioBuffer, this);
-
-    // Init
-    if (AudioUnitInitialize(audioUnit)) {
-        qWarning() << "QAudioOutput: Failed to initialize AudioUnit";
-        return false;
-    }
-
-    isOpen = true;
-
-    return true;
-}
-
-void QAudioOutputPrivate::close()
-{
-    if (audioUnit != 0) {
-        AudioOutputUnitStop(audioUnit);
-        AudioUnitUninitialize(audioUnit);
-        CloseComponent(audioUnit);
-    }
-
-    delete audioBuffer;
-}
-
-QAudioFormat QAudioOutputPrivate::format() const
-{
-    return audioFormat;
-}
-
-QIODevice* QAudioOutputPrivate::start(QIODevice* device)
-{
-    QIODevice*  op = device;
-
-    if (!audioDeviceInfo->isFormatSupported(audioFormat) || !open()) {
-        stateCode = QAudio::StoppedState;
-        errorCode = QAudio::OpenError;
-        return audioIO;
-    }
-
-    reset();
-    audioBuffer->reset();
-    audioBuffer->setPrefetchDevice(op);
-
-    if (op == 0) {
-        op = audioIO;
-        stateCode = QAudio::IdleState;
-    }
-    else
-        stateCode = QAudio::ActiveState;
-
-    // Start
-    errorCode = QAudio::NoError;
-    totalFrames = 0;
-    startTime = AudioGetCurrentHostTime();
-
-    if (stateCode == QAudio::ActiveState)
-        audioThreadStart();
-
-    emit stateChanged(stateCode);
-
-    return op;
-}
-
-void QAudioOutputPrivate::stop()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode != QAudio::StoppedState) {
-        audioThreadDrain();
-
-        stateCode = QAudio::StoppedState;
-        errorCode = QAudio::NoError;
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-void QAudioOutputPrivate::reset()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode != QAudio::StoppedState) {
-        audioThreadStop();
-
-        stateCode = QAudio::StoppedState;
-        errorCode = QAudio::NoError;
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-void QAudioOutputPrivate::suspend()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::ActiveState || stateCode == QAudio::IdleState) {
-        audioThreadStop();
-
-        stateCode = QAudio::SuspendedState;
-        errorCode = QAudio::NoError;
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-void QAudioOutputPrivate::resume()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::SuspendedState) {
-        audioThreadStart();
-
-        stateCode = QAudio::ActiveState;
-        errorCode = QAudio::NoError;
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-int QAudioOutputPrivate::bytesFree() const
-{
-    return audioBuffer->available();
-}
-
-int QAudioOutputPrivate::periodSize() const
-{
-    return periodSizeBytes;
-}
-
-void QAudioOutputPrivate::setBufferSize(int bs)
-{
-    if (stateCode == QAudio::StoppedState)
-        internalBufferSize = bs;
-}
-
-int QAudioOutputPrivate::bufferSize() const
-{
-    return internalBufferSize;
-}
-
-void QAudioOutputPrivate::setNotifyInterval(int milliSeconds)
-{
-    if (intervalTimer->interval() == milliSeconds)
-        return;
-
-    if (milliSeconds <= 0)
-        milliSeconds = 0;
-
-    intervalTimer->setInterval(milliSeconds);
-}
-
-int QAudioOutputPrivate::notifyInterval() const
-{
-    return intervalTimer->interval();
-}
-
-qint64 QAudioOutputPrivate::processedUSecs() const
-{
-    return totalFrames * 1000000 / audioFormat.frequency();
-}
-
-qint64 QAudioOutputPrivate::elapsedUSecs() const
-{
-    if (stateCode == QAudio::StoppedState)
-        return 0;
-
-    return (AudioGetCurrentHostTime() - startTime) / (clockFrequency / 1000);
-}
-
-QAudio::Error QAudioOutputPrivate::error() const
-{
-    return errorCode;
-}
-
-QAudio::State QAudioOutputPrivate::state() const
-{
-    return stateCode;
-}
-
-void QAudioOutputPrivate::audioThreadStart()
-{
-    startTimers();
-    audioThreadState = Running;
-    AudioOutputUnitStart(audioUnit);
-}
-
-void QAudioOutputPrivate::audioThreadStop()
-{
-    stopTimers();
-    if (audioThreadState.testAndSetAcquire(Running, Stopped))
-        threadFinished.wait(&mutex);
-}
-
-void QAudioOutputPrivate::audioThreadDrain()
-{
-    stopTimers();
-    if (audioThreadState.testAndSetAcquire(Running, Draining))
-        threadFinished.wait(&mutex);
-}
-
-void QAudioOutputPrivate::audioDeviceStop()
-{
-    AudioOutputUnitStop(audioUnit);
-    audioThreadState = Stopped;
-    threadFinished.wakeOne();
-}
-
-void QAudioOutputPrivate::audioDeviceIdle()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::ActiveState) {
-        audioDeviceStop();
-
-        errorCode = QAudio::UnderrunError;
-        stateCode = QAudio::IdleState;
-        QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection);
-    }
-}
-
-void QAudioOutputPrivate::audioDeviceError()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::ActiveState) {
-        audioDeviceStop();
-
-        errorCode = QAudio::IOError;
-        stateCode = QAudio::StoppedState;
-        QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection);
-    }
-}
-
-void QAudioOutputPrivate::startTimers()
-{
-    audioBuffer->startFillTimer();
-    if (intervalTimer->interval() > 0)
-        intervalTimer->start();
-}
-
-void QAudioOutputPrivate::stopTimers()
-{
-    audioBuffer->stopFillTimer();
-    intervalTimer->stop();
-}
-
-
-void QAudioOutputPrivate::deviceStopped()
-{
-    intervalTimer->stop();
-    emit stateChanged(stateCode);
-}
-
-void QAudioOutputPrivate::inputReady()
-{
-    QMutexLocker    lock(&mutex);
-    if (stateCode == QAudio::IdleState) {
-        audioThreadStart();
-
-        stateCode = QAudio::ActiveState;
-        errorCode = QAudio::NoError;
-
-        QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
-    }
-}
-
-
-OSStatus QAudioOutputPrivate::renderCallback(void* inRefCon,
-                                    AudioUnitRenderActionFlags* ioActionFlags,
-                                    const AudioTimeStamp* inTimeStamp,
-                                    UInt32 inBusNumber,
-                                    UInt32 inNumberFrames,
-                                    AudioBufferList* ioData)
-{
-    Q_UNUSED(ioActionFlags)
-    Q_UNUSED(inTimeStamp)
-    Q_UNUSED(inBusNumber)
-    Q_UNUSED(inNumberFrames)
-
-    QAudioOutputPrivate* d = static_cast<QAudioOutputPrivate*>(inRefCon);
-
-    const int threadState = d->audioThreadState.fetchAndAddAcquire(0);
-    if (threadState == Stopped) {
-        ioData->mBuffers[0].mDataByteSize = 0;
-        d->audioDeviceStop();
-    }
-    else {
-        const UInt32    bytesPerFrame = d->streamFormat.mBytesPerFrame;
-        qint64          framesRead;
-
-        framesRead = d->audioBuffer->readFrames((char*)ioData->mBuffers[0].mData,
-                                                 ioData->mBuffers[0].mDataByteSize / bytesPerFrame);
-
-        if (framesRead > 0) {
-            ioData->mBuffers[0].mDataByteSize = framesRead * bytesPerFrame;
-            d->totalFrames += framesRead;
-        }
-        else {
-            ioData->mBuffers[0].mDataByteSize = 0;
-            if (framesRead == 0) {
-                if (threadState == Draining)
-                    d->audioDeviceStop();
-                else
-                    d->audioDeviceIdle();
-            }
-            else
-                d->audioDeviceError();
-        }
-    }
-
-    return noErr;
-}
-
-
-QT_END_NAMESPACE
-
-#include "qaudiooutput_mac_p.moc"
-
diff --git a/src/multimedia/audio/qaudiooutput_mac_p.h b/src/multimedia/audio/qaudiooutput_mac_p.h
deleted file mode 100644 (file)
index 1029587..0000000
+++ /dev/null
@@ -1,169 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtMultimedia 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.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 QAUDIOOUTPUT_MAC_P_H
-#define QAUDIOOUTPUT_MAC_P_H
-
-#include <CoreServices/CoreServices.h>
-#include <CoreAudio/CoreAudio.h>
-#include <AudioUnit/AudioUnit.h>
-#include <AudioToolbox/AudioToolbox.h>
-
-#include <QtCore/qobject.h>
-#include <QtCore/qmutex.h>
-#include <QtCore/qwaitcondition.h>
-#include <QtCore/qtimer.h>
-#include <QtCore/qatomic.h>
-
-#include <QtMultimedia/qaudio.h>
-#include <QtMultimedia/qaudioformat.h>
-#include <QtMultimedia/qaudioengine.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-class QIODevice;
-class QAbstractAudioDeviceInfo;
-
-namespace QtMultimediaInternal
-{
-class QAudioOutputBuffer;
-}
-
-class QAudioOutputPrivate : public QAbstractAudioOutput
-{
-    Q_OBJECT
-
-public:
-    bool            isOpen;
-    int             internalBufferSize;
-    int             periodSizeBytes;
-    qint64          totalFrames;
-    QAudioFormat    audioFormat;
-    QIODevice*      audioIO;
-    AudioDeviceID   audioDeviceId;
-    AudioUnit       audioUnit;
-    Float64         clockFrequency;
-    UInt64          startTime;
-    AudioStreamBasicDescription deviceFormat;
-    AudioStreamBasicDescription streamFormat;
-    QtMultimediaInternal::QAudioOutputBuffer*   audioBuffer;
-    QAtomicInt      audioThreadState;
-    QWaitCondition  threadFinished;
-    QMutex          mutex;
-    QTimer*         intervalTimer;
-    QAbstractAudioDeviceInfo *audioDeviceInfo;
-
-    QAudio::Error    errorCode;
-    QAudio::State    stateCode;
-
-    QAudioOutputPrivate(const QByteArray& device, const QAudioFormat& format);
-    ~QAudioOutputPrivate();
-
-    bool open();
-    void close();
-
-    QAudioFormat format() const;
-
-    QIODevice* start(QIODevice* device);
-    void stop();
-    void reset();
-    void suspend();
-    void resume();
-
-    int bytesFree() const;
-    int periodSize() const;
-
-    void setBufferSize(int value);
-    int bufferSize() const;
-
-    void setNotifyInterval(int milliSeconds);
-    int notifyInterval() const;
-
-    qint64 processedUSecs() const;
-    qint64 elapsedUSecs() const;
-
-    QAudio::Error error() const;
-    QAudio::State state() const;
-
-    void audioThreadStart();
-    void audioThreadStop();
-    void audioThreadDrain();
-
-    void audioDeviceStop();
-    void audioDeviceIdle();
-    void audioDeviceError();
-
-    void startTimers();
-    void stopTimers();
-
-private slots:
-    void deviceStopped();
-    void inputReady();
-
-private:
-    enum { Running, Draining, Stopped };
-
-    static OSStatus renderCallback(void* inRefCon,
-                                    AudioUnitRenderActionFlags* ioActionFlags,
-                                    const AudioTimeStamp* inTimeStamp,
-                                    UInt32 inBusNumber,
-                                    UInt32 inNumberFrames,
-                                    AudioBufferList* ioData);
-};
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif
diff --git a/src/network/kernel/qhostinfo_win.cpp b/src/network/kernel/qhostinfo_win.cpp
deleted file mode 100644 (file)
index fac66d6..0000000
+++ /dev/null
@@ -1,280 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <winsock2.h>
-
-#include "qhostinfo_p.h"
-#include "qnativesocketengine_p.h"
-#include <ws2tcpip.h>
-#include <qsystemlibrary_p.h>
-#include <qurl.h>
-
-QT_BEGIN_NAMESPACE
-
-//#define QHOSTINFO_DEBUG
-
-// Older SDKs do not include the addrinfo struct declaration, so we
-// include a copy of it here.
-struct qt_addrinfo
-{
-    int ai_flags;
-    int ai_family;
-    int ai_socktype;
-    int ai_protocol;
-    size_t ai_addrlen;
-    char *ai_canonname;
-    sockaddr *ai_addr;
-    qt_addrinfo *ai_next;
-};
-
-//###
-#define QT_SOCKLEN_T int
-#ifndef NI_MAXHOST // already defined to 1025 in ws2tcpip.h?
-#define NI_MAXHOST 1024
-#endif
-
-typedef int (__stdcall *getnameinfoProto)(const sockaddr *, QT_SOCKLEN_T, const char *, DWORD, const char *, DWORD, int);
-typedef int (__stdcall *getaddrinfoProto)(const char *, const char *, const qt_addrinfo *, qt_addrinfo **);
-typedef int (__stdcall *freeaddrinfoProto)(qt_addrinfo *);
-static getnameinfoProto local_getnameinfo = 0;
-static getaddrinfoProto local_getaddrinfo = 0;
-static freeaddrinfoProto local_freeaddrinfo = 0;
-
-static void resolveLibrary()
-{
-    // Attempt to resolve getaddrinfo(); without it we'll have to fall
-    // back to gethostbyname(), which has no IPv6 support.
-    static bool triedResolve = false;
-    if (triedResolve)
-        return;
-
-#if !defined(Q_OS_WINCE)
-    QSystemLibrary ws2lib(QLatin1String("ws2_32"));
-#else
-    QSystemLibrary ws2lib(QLatin1String("ws2"));
-#endif
-    if (ws2lib.load()) {
-        local_getaddrinfo = (getaddrinfoProto)ws2lib.resolve("getaddrinfo");
-        local_freeaddrinfo = (freeaddrinfoProto)ws2lib.resolve("freeaddrinfo");
-        local_getnameinfo = (getnameinfoProto)ws2lib.resolve("getnameinfo");
-    }
-
-    triedResolve = true;
-}
-
-#if defined(Q_OS_WINCE)
-#include <qmutex.h>
-Q_GLOBAL_STATIC(QMutex, qPrivCEMutex)
-#endif
-
-static void translateWSAError(int error, QHostInfo *results)
-{
-    switch (error) {
-    case WSAHOST_NOT_FOUND: //authoritative not found
-    case WSATRY_AGAIN: //non authoritative not found
-    case WSANO_DATA: //valid name, no associated address
-        results->setError(QHostInfo::HostNotFound);
-        results->setErrorString(QHostInfoAgent::tr("Host not found"));
-        return;
-    default:
-        results->setError(QHostInfo::UnknownError);
-        results->setErrorString(QHostInfoAgent::tr("Unknown error (%1)").arg(error));
-        return;
-    }
-}
-
-QHostInfo QHostInfoAgent::fromName(const QString &hostName)
-{
-    resolveLibrary();
-
-#if defined(Q_OS_WINCE)
-    QMutexLocker locker(qPrivCEMutex());
-#endif
-
-    QWindowsSockInit winSock;
-
-    QHostInfo results;
-
-#if defined(QHOSTINFO_DEBUG)
-    qDebug("QHostInfoAgent::fromName(%p): looking up \"%s\" (IPv6 support is %s)",
-           this, hostName.toLatin1().constData(),
-           (local_getaddrinfo && local_freeaddrinfo) ? "enabled" : "disabled");
-#endif
-
-    QHostAddress address;
-    if (address.setAddress(hostName)) {
-        // Reverse lookup
-        if (local_getnameinfo) {
-            sockaddr_in sa4;
-            qt_sockaddr_in6 sa6;
-            sockaddr *sa;
-            QT_SOCKLEN_T saSize;
-            if (address.protocol() == QAbstractSocket::IPv4Protocol) {
-                sa = (sockaddr *)&sa4;
-                saSize = sizeof(sa4);
-                memset(&sa4, 0, sizeof(sa4));
-                sa4.sin_family = AF_INET;
-                sa4.sin_addr.s_addr = htonl(address.toIPv4Address());
-            } else {
-                sa = (sockaddr *)&sa6;
-                saSize = sizeof(sa6);
-                memset(&sa6, 0, sizeof(sa6));
-                sa6.sin6_family = AF_INET6;
-                memcpy(sa6.sin6_addr.qt_s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.qt_s6_addr));
-            }
-
-            char hbuf[NI_MAXHOST];
-            if (local_getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0)
-                results.setHostName(QString::fromLatin1(hbuf));
-        } else {
-            unsigned long addr = inet_addr(hostName.toLatin1().constData());
-            struct hostent *ent = gethostbyaddr((const char*)&addr, sizeof(addr), AF_INET);
-            if (ent)
-                results.setHostName(QString::fromLatin1(ent->h_name));
-        }
-
-        if (results.hostName().isEmpty())
-            results.setHostName(address.toString());
-        results.setAddresses(QList<QHostAddress>() << address);
-        return results;
-    }
-
-    // IDN support
-    QByteArray aceHostname = QUrl::toAce(hostName);
-    results.setHostName(hostName);
-    if (aceHostname.isEmpty()) {
-        results.setError(QHostInfo::HostNotFound);
-        results.setErrorString(hostName.isEmpty() ? tr("No host name given") : tr("Invalid hostname"));
-        return results;
-    }
-
-    if (local_getaddrinfo && local_freeaddrinfo) {
-        // Call getaddrinfo, and place all IPv4 addresses at the start
-        // and the IPv6 addresses at the end of the address list in
-        // results.
-        qt_addrinfo *res;
-        int err = local_getaddrinfo(aceHostname.constData(), 0, 0, &res);
-        if (err == 0) {
-            QList<QHostAddress> addresses;
-            for (qt_addrinfo *p = res; p != 0; p = p->ai_next) {
-                switch (p->ai_family) {
-                case AF_INET: {
-                    QHostAddress addr;
-                    addr.setAddress(ntohl(((sockaddr_in *) p->ai_addr)->sin_addr.s_addr));
-                    if (!addresses.contains(addr))
-                        addresses.append(addr);
-                }
-                    break;
-                case AF_INET6: {
-                    QHostAddress addr;
-                    addr.setAddress(((qt_sockaddr_in6 *) p->ai_addr)->sin6_addr.qt_s6_addr);
-                    if (!addresses.contains(addr))
-                        addresses.append(addr);
-                }
-                    break;
-                default:
-                    results.setError(QHostInfo::UnknownError);
-                    results.setErrorString(tr("Unknown address type"));
-                }
-            }
-            results.setAddresses(addresses);
-            local_freeaddrinfo(res);
-        } else {
-            translateWSAError(WSAGetLastError(), &results);
-        }
-    } else {
-        // Fall back to gethostbyname, which only supports IPv4.
-        hostent *ent = gethostbyname(aceHostname.constData());
-        if (ent) {
-            char **p;
-            QList<QHostAddress> addresses;
-            switch (ent->h_addrtype) {
-            case AF_INET:
-                for (p = ent->h_addr_list; *p != 0; p++) {
-                    long *ip4Addr = (long *) *p;
-                    QHostAddress temp;
-                    temp.setAddress(ntohl(*ip4Addr));
-                    addresses << temp;
-                }
-                break;
-            default:
-                results.setError(QHostInfo::UnknownError);
-                results.setErrorString(tr("Unknown address type"));
-                break;
-            }
-            results.setAddresses(addresses);
-        } else {
-            translateWSAError(WSAGetLastError(), &results);
-        }
-    }
-
-#if defined(QHOSTINFO_DEBUG)
-    if (results.error() != QHostInfo::NoError) {
-        qDebug("QHostInfoAgent::run(%p): error (%s)",
-               this, results.errorString().toLatin1().constData());
-    } else {
-        QString tmp;
-        QList<QHostAddress> addresses = results.addresses();
-        for (int i = 0; i < addresses.count(); ++i) {
-            if (i != 0) tmp += ", ";
-            tmp += addresses.at(i).toString();
-        }
-        qDebug("QHostInfoAgent::run(%p): found %i entries: {%s}",
-               this, addresses.count(), tmp.toLatin1().constData());
-    }
-#endif
-    return results;
-}
-
-QString QHostInfo::localHostName()
-{
-    QWindowsSockInit winSock;
-
-    char hostName[512];
-    if (gethostname(hostName, sizeof(hostName)) == -1)
-        return QString();
-    hostName[sizeof(hostName) - 1] = '\0';
-    return QString::fromLocal8Bit(hostName);
-}
-
-// QString QHostInfo::localDomainName() defined in qnetworkinterface_win.cpp
-
-QT_END_NAMESPACE
diff --git a/src/network/kernel/qnetworkfunctions_wince.h b/src/network/kernel/qnetworkfunctions_wince.h
deleted file mode 100644 (file)
index eace325..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-#ifndef Q_NETWORK_FUNCTIONS_WCE_H
-#define Q_NETWORK_FUNCTIONS_WCE_H
-#ifdef Q_OS_WINCE
-
-#include <qt_windows.h>
-
-QT_BEGIN_HEADER
-
-QT_BEGIN_NAMESPACE
-
-
-DECLARE_HANDLE(SC_HANDLE);
-typedef enum _SC_ENUM_TYPE {
-        SC_ENUM_PROCESS_INFO        = 0
-} SC_ENUM_TYPE;
-#define SC_MANAGER_CONNECT             0x0001
-#define SC_MANAGER_CREATE_SERVICE      0x0002
-#define SC_MANAGER_ENUMERATE_SERVICE   0x0004
-#define SERVICE_ACTIVE                 0x00000001
-#define SERVICE_INACTIVE               0x00000002
-#define SERVICE_STATE_ALL              (SERVICE_ACTIVE   | \
-                                        SERVICE_INACTIVE)
-typedef struct _SERVICE_STATUS_PROCESS {
-    DWORD   dwServiceType;
-    DWORD   dwCurrentState;
-    DWORD   dwControlsAccepted;
-    DWORD   dwWin32ExitCode;
-    DWORD   dwServiceSpecificExitCode;
-    DWORD   dwCheckPoint;
-    DWORD   dwWaitHint;
-    DWORD   dwProcessId;
-    DWORD   dwServiceFlags;
-} SERVICE_STATUS_PROCESS, *LPSERVICE_STATUS_PROCESS;
-typedef struct _ENUM_SERVICE_STATUS_PROCESSA {
-    LPSTR                     lpServiceName;
-    LPSTR                     lpDisplayName;
-    SERVICE_STATUS_PROCESS    ServiceStatusProcess;
-} ENUM_SERVICE_STATUS_PROCESSA, *LPENUM_SERVICE_STATUS_PROCESSA;
-typedef struct _ENUM_SERVICE_STATUS_PROCESSW {
-    LPWSTR                    lpServiceName;
-    LPWSTR                    lpDisplayName;
-    SERVICE_STATUS_PROCESS    ServiceStatusProcess;
-} ENUM_SERVICE_STATUS_PROCESSW, *LPENUM_SERVICE_STATUS_PROCESSW;
-#ifdef UNICODE
-typedef ENUM_SERVICE_STATUS_PROCESSW ENUM_SERVICE_STATUS_PROCESS;
-typedef LPENUM_SERVICE_STATUS_PROCESSW LPENUM_SERVICE_STATUS_PROCESS;
-#else
-typedef ENUM_SERVICE_STATUS_PROCESSA ENUM_SERVICE_STATUS_PROCESS;
-typedef LPENUM_SERVICE_STATUS_PROCESSA LPENUM_SERVICE_STATUS_PROCESS;
-#endif // UNICODE
-
-QT_END_NAMESPACE
-
-QT_END_HEADER
-
-#endif // Q_OS_WINCE
-#endif // Q_NETWORK_FUNCTIONS_WCE_H
diff --git a/src/network/kernel/qnetworkinterface_win.cpp b/src/network/kernel/qnetworkinterface_win.cpp
deleted file mode 100644 (file)
index 852a678..0000000
+++ /dev/null
@@ -1,321 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qnetworkinterface.h"
-#include "qnetworkinterface_p.h"
-
-#ifndef QT_NO_NETWORKINTERFACE
-
-#include "qnetworkinterface_win_p.h"
-#include <qhostinfo.h>
-#include <qhash.h>
-#include <qurl.h>
-#include <qsystemlibrary_p.h>
-
-QT_BEGIN_NAMESPACE
-
-typedef DWORD (WINAPI *PtrGetAdaptersInfo)(PIP_ADAPTER_INFO, PULONG);
-static PtrGetAdaptersInfo ptrGetAdaptersInfo = 0;
-typedef ULONG (WINAPI *PtrGetAdaptersAddresses)(ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
-static PtrGetAdaptersAddresses ptrGetAdaptersAddresses = 0;
-typedef DWORD (WINAPI *PtrGetNetworkParams)(PFIXED_INFO, PULONG);
-static PtrGetNetworkParams ptrGetNetworkParams = 0;
-
-static void resolveLibs()
-{
-    // try to find the functions we need from Iphlpapi.dll
-    static bool done = false;
-    if (!done) {
-        QSystemLibrary iphlpapi(QLatin1String("iphlpapi"));
-        if (iphlpapi.load()) {
-            ptrGetAdaptersInfo = (PtrGetAdaptersInfo)iphlpapi.resolve("GetAdaptersInfo");
-            ptrGetAdaptersAddresses = (PtrGetAdaptersAddresses)iphlpapi.resolve("GetAdaptersAddresses");
-            ptrGetNetworkParams = (PtrGetNetworkParams)iphlpapi.resolve("GetNetworkParams");
-        }
-        done = true;
-    }
-}
-
-static QHostAddress addressFromSockaddr(sockaddr *sa)
-{
-    QHostAddress address;
-    if (!sa)
-        return address;
-
-    if (sa->sa_family == AF_INET)
-        address.setAddress(htonl(((sockaddr_in *)sa)->sin_addr.s_addr));
-    else if (sa->sa_family == AF_INET6) {
-        address.setAddress(((qt_sockaddr_in6 *)sa)->sin6_addr.qt_s6_addr);
-        int scope = ((qt_sockaddr_in6 *)sa)->sin6_scope_id;
-        if (scope)
-            address.setScopeId(QString::number(scope));
-    } else
-        qWarning("Got unknown socket family %d", sa->sa_family);
-    return address;
-
-}
-
-static QHash<QHostAddress, QHostAddress> ipv4Netmasks()
-{
-    //Retrieve all the IPV4 addresses & netmasks
-    IP_ADAPTER_INFO staticBuf[2]; // 2 is arbitrary
-    PIP_ADAPTER_INFO pAdapter = staticBuf;
-    ULONG bufSize = sizeof staticBuf;
-    QHash<QHostAddress, QHostAddress> ipv4netmasks; 
-
-    DWORD retval = ptrGetAdaptersInfo(pAdapter, &bufSize);
-    if (retval == ERROR_BUFFER_OVERFLOW) {
-        // need more memory
-        pAdapter = (IP_ADAPTER_INFO *)malloc(bufSize);
-        if (!pAdapter)
-            return ipv4netmasks;
-        // try again
-        if (ptrGetAdaptersInfo(pAdapter, &bufSize) != ERROR_SUCCESS) {
-            free(pAdapter);
-            return ipv4netmasks;
-        }
-    } else if (retval != ERROR_SUCCESS) {
-        // error
-        return ipv4netmasks;
-    }
-
-    // iterate over the list and add the entries to our listing
-    for (PIP_ADAPTER_INFO ptr = pAdapter; ptr; ptr = ptr->Next) {
-        for (PIP_ADDR_STRING addr = &ptr->IpAddressList; addr; addr = addr->Next) {
-            QHostAddress address(QLatin1String(addr->IpAddress.String));
-            QHostAddress mask(QLatin1String(addr->IpMask.String));
-            ipv4netmasks[address] = mask;
-        }
-    }
-    if (pAdapter != staticBuf)
-        free(pAdapter);
-
-    return ipv4netmasks;
-
-}
-
-static QList<QNetworkInterfacePrivate *> interfaceListingWinXP()
-{
-    QList<QNetworkInterfacePrivate *> interfaces;
-    IP_ADAPTER_ADDRESSES staticBuf[2]; // 2 is arbitrary
-    PIP_ADAPTER_ADDRESSES pAdapter = staticBuf;
-    ULONG bufSize = sizeof staticBuf;
-
-    const QHash<QHostAddress, QHostAddress> &ipv4netmasks = ipv4Netmasks();
-    ULONG flags = GAA_FLAG_INCLUDE_PREFIX |
-                  GAA_FLAG_SKIP_DNS_SERVER |
-                  GAA_FLAG_SKIP_MULTICAST;
-    ULONG retval = ptrGetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapter, &bufSize);
-    if (retval == ERROR_BUFFER_OVERFLOW) {
-        // need more memory
-        pAdapter = (IP_ADAPTER_ADDRESSES *)malloc(bufSize);
-        if (!pAdapter)
-            return interfaces;
-        // try again
-        if (ptrGetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAdapter, &bufSize) != ERROR_SUCCESS) {
-            free(pAdapter);
-            return interfaces;
-        }
-    } else if (retval != ERROR_SUCCESS) {
-        // error
-        return interfaces;
-    }
-
-    // iterate over the list and add the entries to our listing
-    for (PIP_ADAPTER_ADDRESSES ptr = pAdapter; ptr; ptr = ptr->Next) {
-        QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
-        interfaces << iface;
-
-        iface->index = 0;
-        if (ptr->Length >= offsetof(IP_ADAPTER_ADDRESSES, Ipv6IfIndex) && ptr->Ipv6IfIndex != 0)
-            iface->index = ptr->Ipv6IfIndex;
-        else if (ptr->IfIndex != 0)
-            iface->index = ptr->IfIndex;
-
-        iface->flags = QNetworkInterface::CanBroadcast;
-        if (ptr->OperStatus == IfOperStatusUp)
-            iface->flags |= QNetworkInterface::IsUp | QNetworkInterface::IsRunning;
-        if ((ptr->Flags & IP_ADAPTER_NO_MULTICAST) == 0)
-            iface->flags |= QNetworkInterface::CanMulticast;
-
-        iface->name = QString::fromLocal8Bit(ptr->AdapterName);
-        iface->friendlyName = QString::fromWCharArray(ptr->FriendlyName);
-        if (ptr->PhysicalAddressLength)
-            iface->hardwareAddress = iface->makeHwAddress(ptr->PhysicalAddressLength,
-                                                          ptr->PhysicalAddress);
-        else
-            // loopback if it has no address
-            iface->flags |= QNetworkInterface::IsLoopBack;
-
-        // The GetAdaptersAddresses call has an interesting semantic:
-        // It can return a number N of addresses and a number M of prefixes.
-        // But if you have IPv6 addresses, generally N > M.
-        // I cannot find a way to relate the Address to the Prefix, aside from stopping
-        // the iteration at the last Prefix entry and assume that it applies to all addresses
-        // from that point on.
-        PIP_ADAPTER_PREFIX pprefix = 0;
-        if (ptr->Length >= offsetof(IP_ADAPTER_ADDRESSES, FirstPrefix))
-            pprefix = ptr->FirstPrefix;
-        for (PIP_ADAPTER_UNICAST_ADDRESS addr = ptr->FirstUnicastAddress; addr; addr = addr->Next) {
-            QNetworkAddressEntry entry;
-            entry.setIp(addressFromSockaddr(addr->Address.lpSockaddr));
-            if (pprefix) {
-                if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
-                    entry.setNetmask(ipv4netmasks[entry.ip()]);
-
-                    // broadcast address is set on postProcess()
-                } else { //IPV6
-                    entry.setPrefixLength(pprefix->PrefixLength);
-                }
-                pprefix = pprefix->Next ? pprefix->Next : pprefix;
-            }
-            iface->addressEntries << entry;
-        }
-    }
-
-    if (pAdapter != staticBuf)
-        free(pAdapter);
-
-    return interfaces;
-}
-
-static QList<QNetworkInterfacePrivate *> interfaceListingWin2k()
-{
-    QList<QNetworkInterfacePrivate *> interfaces;
-    IP_ADAPTER_INFO staticBuf[2]; // 2 is arbitrary
-    PIP_ADAPTER_INFO pAdapter = staticBuf;
-    ULONG bufSize = sizeof staticBuf;
-
-    DWORD retval = ptrGetAdaptersInfo(pAdapter, &bufSize);
-    if (retval == ERROR_BUFFER_OVERFLOW) {
-        // need more memory
-        pAdapter = (IP_ADAPTER_INFO *)malloc(bufSize);
-        if (!pAdapter)
-            return interfaces;
-        // try again
-        if (ptrGetAdaptersInfo(pAdapter, &bufSize) != ERROR_SUCCESS) {
-            free(pAdapter);
-            return interfaces;
-        }
-    } else if (retval != ERROR_SUCCESS) {
-        // error
-        return interfaces;
-    }
-
-    // iterate over the list and add the entries to our listing
-    for (PIP_ADAPTER_INFO ptr = pAdapter; ptr; ptr = ptr->Next) {
-        QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
-        interfaces << iface;
-
-        iface->index = ptr->Index;
-        iface->flags = QNetworkInterface::IsUp | QNetworkInterface::IsRunning;
-        if (ptr->Type == MIB_IF_TYPE_PPP)
-            iface->flags |= QNetworkInterface::IsPointToPoint;
-        else
-            iface->flags |= QNetworkInterface::CanBroadcast;
-        iface->name = QString::fromLocal8Bit(ptr->AdapterName);
-        iface->hardwareAddress = QNetworkInterfacePrivate::makeHwAddress(ptr->AddressLength,
-                                                                         ptr->Address);
-
-        for (PIP_ADDR_STRING addr = &ptr->IpAddressList; addr; addr = addr->Next) {
-            QNetworkAddressEntry entry;
-            entry.setIp(QHostAddress(QLatin1String(addr->IpAddress.String)));
-            entry.setNetmask(QHostAddress(QLatin1String(addr->IpMask.String)));
-            // broadcast address is set on postProcess()
-
-            iface->addressEntries << entry;
-        }
-    }
-
-    if (pAdapter != staticBuf)
-        free(pAdapter);
-
-    return interfaces;
-}
-
-static QList<QNetworkInterfacePrivate *> interfaceListing()
-{
-    resolveLibs();
-    if (ptrGetAdaptersAddresses != NULL)
-        return interfaceListingWinXP();
-    else if (ptrGetAdaptersInfo != NULL)
-        return interfaceListingWin2k();
-
-    // failed
-    return QList<QNetworkInterfacePrivate *>();
-}
-
-QList<QNetworkInterfacePrivate *> QNetworkInterfaceManager::scan()
-{
-    return interfaceListing();
-}
-
-QString QHostInfo::localDomainName()
-{
-    resolveLibs();
-    if (ptrGetNetworkParams == NULL)
-        return QString();       // couldn't resolve
-
-    FIXED_INFO info, *pinfo;
-    ULONG bufSize = sizeof info;
-    pinfo = &info;
-    if (ptrGetNetworkParams(pinfo, &bufSize) == ERROR_BUFFER_OVERFLOW) {
-        pinfo = (FIXED_INFO *)malloc(bufSize);
-        if (!pinfo)
-            return QString();
-        // try again
-        if (ptrGetNetworkParams(pinfo, &bufSize) != ERROR_SUCCESS) {
-            free(pinfo);
-            return QString();   // error
-        }
-    }
-
-    QString domainName = QUrl::fromAce(pinfo->DomainName);
-
-    if (pinfo != &info)
-        free(pinfo);
-
-    return domainName;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_NETWORKINTERFACE
diff --git a/src/network/kernel/qnetworkinterface_win_p.h b/src/network/kernel/qnetworkinterface_win_p.h
deleted file mode 100644 (file)
index 7e1f196..0000000
+++ /dev/null
@@ -1,257 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QNETWORKINTERFACE_WIN_P_H
-#define QNETWORKINTERFACE_WIN_P_H
-
-//
-//  W A R N I N G
-//  -------------
-//
-// This file is not part of the Qt API.  It exists for the convenience
-// of the QLibrary class.  This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <winsock2.h>
-#include <qt_windows.h>
-#include <time.h>
-
-#include "qnativesocketengine_p.h"
-
-QT_BEGIN_NAMESPACE
-
-#ifndef GAA_FLAG_INCLUDE_ALL_INTERFACES
-# define GAA_FLAG_INCLUDE_ALL_INTERFACES 0x0100
-#endif
-#ifndef MAX_ADAPTER_ADDRESS_LENGTH
-// definitions from iptypes.h
-# define MAX_ADAPTER_DESCRIPTION_LENGTH  128 // arb.
-# define MAX_ADAPTER_NAME_LENGTH         256 // arb.
-# define MAX_ADAPTER_ADDRESS_LENGTH      8   // arb.
-# define DEFAULT_MINIMUM_ENTITIES        32  // arb.
-# define MAX_HOSTNAME_LEN                128 // arb.
-# define MAX_DOMAIN_NAME_LEN             128 // arb.
-# define MAX_SCOPE_ID_LEN                256 // arb.
-
-# define GAA_FLAG_SKIP_UNICAST       0x0001
-# define GAA_FLAG_SKIP_ANYCAST       0x0002
-# define GAA_FLAG_SKIP_MULTICAST     0x0004
-# define GAA_FLAG_SKIP_DNS_SERVER    0x0008
-# define GAA_FLAG_INCLUDE_PREFIX     0x0010
-# define GAA_FLAG_SKIP_FRIENDLY_NAME 0x0020
-
-# define IP_ADAPTER_DDNS_ENABLED               0x01
-# define IP_ADAPTER_REGISTER_ADAPTER_SUFFIX    0x02
-# define IP_ADAPTER_DHCP_ENABLED               0x04
-# define IP_ADAPTER_RECEIVE_ONLY               0x08
-# define IP_ADAPTER_NO_MULTICAST               0x10
-# define IP_ADAPTER_IPV6_OTHER_STATEFUL_CONFIG 0x20
-
-# define MIB_IF_TYPE_OTHER               1
-# define MIB_IF_TYPE_ETHERNET            6
-# define MIB_IF_TYPE_TOKENRING           9
-# define MIB_IF_TYPE_FDDI                15
-# define MIB_IF_TYPE_PPP                 23
-# define MIB_IF_TYPE_LOOPBACK            24
-# define MIB_IF_TYPE_SLIP                28
-
-#endif
-
-// copied from MSDN online help
-typedef enum {
-  IpPrefixOriginOther = 0, 
-  IpPrefixOriginManual, 
-  IpPrefixOriginWellKnown, 
-  IpPrefixOriginDhcp, 
-  IpPrefixOriginRouterAdvertisement
-} IP_PREFIX_ORIGIN;
-
-typedef enum {
-  IpSuffixOriginOther = 0, 
-  IpSuffixOriginManual, 
-  IpSuffixOriginWellKnown, 
-  IpSuffixOriginDhcp, 
-  IpSuffixOriginLinkLayerAddress, 
-  IpSuffixOriginRandom
-} IP_SUFFIX_ORIGIN;
-
-typedef enum {
-    IpDadStateInvalid    = 0,
-    IpDadStateTentative,
-    IpDadStateDuplicate,
-    IpDadStateDeprecated,
-    IpDadStatePreferred,
-} IP_DAD_STATE;
-
-typedef enum {
-    IfOperStatusUp = 1,
-    IfOperStatusDown,
-    IfOperStatusTesting,
-    IfOperStatusUnknown,
-    IfOperStatusDormant,
-    IfOperStatusNotPresent,
-    IfOperStatusLowerLayerDown
-} IF_OPER_STATUS;
-
-typedef struct _IP_ADAPTER_UNICAST_ADDRESS {
-  union {
-    ULONGLONG Alignment;
-    struct {
-      ULONG Length;
-      DWORD Flags;
-    };
-  };
-  struct _IP_ADAPTER_UNICAST_ADDRESS* Next;
-  SOCKET_ADDRESS Address;
-  IP_PREFIX_ORIGIN PrefixOrigin;
-  IP_SUFFIX_ORIGIN SuffixOrigin;
-  IP_DAD_STATE DadState;
-  ULONG ValidLifetime;
-  ULONG PreferredLifetime;
-  ULONG LeaseLifetime;
-} IP_ADAPTER_UNICAST_ADDRESS, *PIP_ADAPTER_UNICAST_ADDRESS;
-
-typedef struct _IP_ADAPTER_ANYCAST_ADDRESS 
- IP_ADAPTER_ANYCAST_ADDRESS, *PIP_ADAPTER_ANYCAST_ADDRESS;
-
-typedef struct _IP_ADAPTER_MULTICAST_ADDRESS 
- IP_ADAPTER_MULTICAST_ADDRESS, 
- *PIP_ADAPTER_MULTICAST_ADDRESS;
-
-typedef struct _IP_ADAPTER_DNS_SERVER_ADDRESS
- IP_ADAPTER_DNS_SERVER_ADDRESS,
- *PIP_ADAPTER_DNS_SERVER_ADDRESS;
-
-typedef struct _IP_ADAPTER_PREFIX {
-  union {
-    ULONGLONG  Alignment;
-    struct {
-      ULONG Length;
-      DWORD Flags;
-    };
-  };
-  struct _IP_ADAPTER_PREFIX* Next;
-  SOCKET_ADDRESS Address;
-  ULONG PrefixLength;
-} IP_ADAPTER_PREFIX, 
- *PIP_ADAPTER_PREFIX;
-
-typedef struct _IP_ADAPTER_ADDRESSES {
-  union {
-    ULONGLONG Alignment;
-    struct {
-      ULONG Length;
-      DWORD IfIndex;
-    };
-  };
-  struct _IP_ADAPTER_ADDRESSES* Next;
-  PCHAR AdapterName;
-  PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress;
-  PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress;
-  PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress;
-  PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress;
-  PWCHAR DnsSuffix;
-  PWCHAR Description;
-  PWCHAR FriendlyName;
-  BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH];
-  DWORD PhysicalAddressLength;
-  DWORD Flags;
-  DWORD Mtu;
-  DWORD IfType;
-  IF_OPER_STATUS OperStatus;
-  DWORD Ipv6IfIndex;
-  DWORD ZoneIndices[16];
-  PIP_ADAPTER_PREFIX FirstPrefix;
-} IP_ADAPTER_ADDRESSES, 
- *PIP_ADAPTER_ADDRESSES;
-
-typedef struct {
-    char String[4 * 4];
-} IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING;
-
-typedef struct _IP_ADDR_STRING {
-  struct _IP_ADDR_STRING* Next;
-  IP_ADDRESS_STRING IpAddress;
-  IP_MASK_STRING IpMask;
-  DWORD Context;
-} IP_ADDR_STRING, 
- *PIP_ADDR_STRING;
-
-typedef struct _IP_ADAPTER_INFO {
-  struct _IP_ADAPTER_INFO* Next;
-  DWORD ComboIndex;
-  char AdapterName[MAX_ADAPTER_NAME_LENGTH + 4];
-  char Description[MAX_ADAPTER_DESCRIPTION_LENGTH + 4];
-  UINT AddressLength;
-  BYTE Address[MAX_ADAPTER_ADDRESS_LENGTH];
-  DWORD Index;
-  UINT Type;
-  UINT DhcpEnabled;
-  PIP_ADDR_STRING CurrentIpAddress;
-  IP_ADDR_STRING IpAddressList;
-  IP_ADDR_STRING GatewayList;
-  IP_ADDR_STRING DhcpServer;
-  BOOL HaveWins;
-  IP_ADDR_STRING PrimaryWinsServer;
-  IP_ADDR_STRING SecondaryWinsServer;
-  time_t LeaseObtained;
-  time_t LeaseExpires;
-} IP_ADAPTER_INFO, 
- *PIP_ADAPTER_INFO;
-
-typedef struct {
-  char HostName[MAX_HOSTNAME_LEN + 4];
-  char DomainName[MAX_DOMAIN_NAME_LEN + 4];
-  PIP_ADDR_STRING CurrentDnsServer;
-  IP_ADDR_STRING DnsServerList;
-  UINT NodeType;
-  char ScopeId[MAX_SCOPE_ID_LEN + 4];
-  UINT EnableRouting;
-  UINT EnableProxy;
-  UINT EnableDns;
-} FIXED_INFO, *PFIXED_INFO;
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/network/kernel/qnetworkproxy_blackberry.cpp b/src/network/kernel/qnetworkproxy_blackberry.cpp
deleted file mode 100644 (file)
index 08f907f..0000000
+++ /dev/null
@@ -1,172 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Research In Motion
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/**
- * Some notes about the code:
- *
- * ** It is assumed that the system proxies are for url based requests
- *  ie. HTTP/HTTPS based.
- */
-
-#include <QtNetwork/qnetworkproxy.h>
-
-#ifndef QT_NO_NETWORKPROXY
-
-
-#include <QtCore/qurl.h>
-#include <QtNetwork/qnetworkconfiguration.h>
-
-#include <bps/netstatus.h>
-#include <errno.h>
-
-
-QT_BEGIN_NAMESPACE
-
-QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &query)
-{
-    if (query.url().scheme() == QLatin1String("file")
-            || query.url().scheme() == QLatin1String("qrc"))
-        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
-
-    if (query.queryType() != QNetworkProxyQuery::UrlRequest
-            && query.queryType() != QNetworkProxyQuery::TcpSocket) {
-        qWarning("Unsupported query type: %d", query.queryType());
-        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
-    }
-
-    QUrl url;
-    if (query.queryType() == QNetworkProxyQuery::UrlRequest) {
-        url = query.url();
-    } else if (query.queryType() == QNetworkProxyQuery::TcpSocket
-               && !query.peerHostName().isEmpty()) {
-        url.setHost(query.peerHostName());
-        switch (query.peerPort()) {
-        case 443:
-            url.setScheme(QLatin1String("https"));
-            break;
-        case 21:
-            url.setScheme(QLatin1String("ftp"));
-            break;
-        default:
-            // for unknown ports, we just pretend we are dealing
-            // with a HTTP URL, otherwise we will not get a proxy
-            // from the netstatus API
-            url.setScheme(QLatin1String("http"));
-        }
-    }
-
-    if (!url.isValid()) {
-        qWarning("Invalid URL: %s", qPrintable(url.toString()));
-        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
-    }
-
-    netstatus_proxy_details_t details;
-    memset(&details, 0, sizeof(netstatus_proxy_details_t));
-
-#if BPS_VERSION >= 3001001
-
-    QByteArray bUrl(url.toEncoded());
-    QString sInterface(query.networkConfiguration().name());
-    QByteArray bInterface;
-    if (!sInterface.isEmpty()) {
-        if (query.networkConfiguration().type() != QNetworkConfiguration::InternetAccessPoint) {
-            qWarning("Unsupported configuration type: %d", query.networkConfiguration().type());
-            return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
-        }
-        bInterface = sInterface.toUtf8();
-    }
-
-    if (netstatus_get_proxy_details_for_url(bUrl.constData(), (bInterface.isEmpty() ? NULL : bInterface.constData()), &details) != BPS_SUCCESS) {
-        qWarning("netstatus_get_proxy_details_for_url failed! errno: %d", errno);
-        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
-    }
-
-#else
-
-    if (netstatus_get_proxy_details(&details) != BPS_SUCCESS) {
-        qWarning("netstatus_get_proxy_details failed! errno: %d", errno);
-        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
-    }
-
-#endif
-
-    if (details.http_proxy_host == NULL) { // No proxy
-        netstatus_free_proxy_details(&details);
-        return QList<QNetworkProxy>() << QNetworkProxy(QNetworkProxy::NoProxy);
-    }
-
-    QNetworkProxy proxy;
-
-    QString protocol = query.protocolTag();
-    if (protocol.startsWith(QLatin1String("http"), Qt::CaseInsensitive)) { // http, https
-        proxy.setType((QNetworkProxy::HttpProxy));
-    } else if (protocol == QLatin1String("ftp")) {
-        proxy.setType(QNetworkProxy::FtpCachingProxy);
-    } else { // assume http proxy
-        qDebug("Proxy type: %s assumed to be http proxy", qPrintable(protocol));
-        proxy.setType((QNetworkProxy::HttpProxy));
-    }
-
-    // Set host
-    // Note: ftp and https proxy type fields *are* obsolete.
-    // The user interface allows only one host/port which gets duplicated
-    // to all proxy type fields.
-    proxy.setHostName(QString::fromUtf8(details.http_proxy_host));
-
-    // Set port
-    proxy.setPort(details.http_proxy_port);
-
-    // Set username
-    if (details.http_proxy_login_user)
-        proxy.setUser(QString::fromUtf8(details.http_proxy_login_user));
-
-    // Set password
-    if (details.http_proxy_login_password)
-        proxy.setPassword(QString::fromUtf8(details.http_proxy_login_password));
-
-    netstatus_free_proxy_details(&details);
-
-    return QList<QNetworkProxy>() << proxy;
-}
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/network/kernel/qnetworkproxy_mac.cpp b/src/network/kernel/qnetworkproxy_mac.cpp
deleted file mode 100644 (file)
index 86672c7..0000000
+++ /dev/null
@@ -1,350 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qnetworkproxy.h"
-
-#ifndef QT_NO_NETWORKPROXY
-
-#include <CoreFoundation/CoreFoundation.h>
-#include <SystemConfiguration/SystemConfiguration.h>
-
-#include <QtCore/QRegExp>
-#include <QtCore/QStringList>
-#include <QtCore/QUrl>
-#include <QtCore/qendian.h>
-#include <QtCore/qstringlist.h>
-#include "qcore_mac_p.h"
-
-/*
- * MacOS X has a proxy configuration module in System Preferences (on
- * MacOS X 10.5, it's in Network, Advanced), where one can set the
- * proxy settings for:
- *
- * \list
- *   \o FTP proxy
- *   \o Web Proxy (HTTP)
- *   \o Secure Web Proxy (HTTPS)
- *   \o Streaming Proxy (RTSP)
- *   \o SOCKS Proxy
- *   \o Gopher Proxy
- *   \o URL for Automatic Proxy Configuration (PAC scripts)
- *   \o Bypass list (by default: *.local, 169.254/16)
- * \endlist
- *
- * The matching configuration can be obtained by calling SCDynamicStoreCopyProxies
- * (from <SystemConfiguration/SCDynamicStoreCopySpecific.h>). See
- * Apple's documentation:
- *
- * http://developer.apple.com/DOCUMENTATION/Networking/Reference/SysConfig/SCDynamicStoreCopySpecific/CompositePage.html#//apple_ref/c/func/SCDynamicStoreCopyProxies
- *
- */
-
-QT_BEGIN_NAMESPACE
-
-static bool isHostExcluded(CFDictionaryRef dict, const QString &host)
-{
-    if (host.isEmpty())
-        return true;
-
-    bool isSimple = !host.contains(QLatin1Char('.')) && !host.contains(QLatin1Char(':'));
-    CFNumberRef excludeSimples;
-    if (isSimple &&
-        (excludeSimples = (CFNumberRef)CFDictionaryGetValue(dict, kSCPropNetProxiesExcludeSimpleHostnames))) {
-        int enabled;
-        if (CFNumberGetValue(excludeSimples, kCFNumberIntType, &enabled) && enabled)
-            return true;
-    }
-
-    QHostAddress ipAddress;
-    bool isIpAddress = ipAddress.setAddress(host);
-
-    // not a simple host name
-    // does it match the list of exclusions?
-    CFArrayRef exclusionList = (CFArrayRef)CFDictionaryGetValue(dict, kSCPropNetProxiesExceptionsList);
-    if (!exclusionList)
-        return false;
-
-    CFIndex size = CFArrayGetCount(exclusionList);
-    for (CFIndex i = 0; i < size; ++i) {
-        CFStringRef cfentry = (CFStringRef)CFArrayGetValueAtIndex(exclusionList, i);
-        QString entry = QCFString::toQString(cfentry);
-
-        if (isIpAddress && ipAddress.isInSubnet(QHostAddress::parseSubnet(entry))) {
-            return true;        // excluded
-        } else {
-            // do wildcard matching
-            QRegExp rx(entry, Qt::CaseInsensitive, QRegExp::Wildcard);
-            if (rx.exactMatch(host))
-                return true;
-        }
-    }
-
-    // host was not excluded
-    return false;
-}
-
-static QNetworkProxy proxyFromDictionary(CFDictionaryRef dict, QNetworkProxy::ProxyType type,
-                                         CFStringRef enableKey, CFStringRef hostKey,
-                                         CFStringRef portKey)
-{
-    CFNumberRef protoEnabled;
-    CFNumberRef protoPort;
-    CFStringRef protoHost;
-    if (enableKey
-        && (protoEnabled = (CFNumberRef)CFDictionaryGetValue(dict, enableKey))
-        && (protoHost = (CFStringRef)CFDictionaryGetValue(dict, hostKey))
-        && (protoPort = (CFNumberRef)CFDictionaryGetValue(dict, portKey))) {
-        int enabled;
-        if (CFNumberGetValue(protoEnabled, kCFNumberIntType, &enabled) && enabled) {
-            QString host = QCFString::toQString(protoHost);
-
-            int port;
-            CFNumberGetValue(protoPort, kCFNumberIntType, &port);
-
-            return QNetworkProxy(type, host, port);
-        }
-    }
-
-    // proxy not enabled
-    return QNetworkProxy();
-}
-
-
-static QNetworkProxy proxyFromDictionary(CFDictionaryRef dict)
-{
-    QNetworkProxy::ProxyType proxyType = QNetworkProxy::DefaultProxy;
-    QString hostName;
-    quint16 port = 0;
-    QString user;
-    QString password;
-
-    CFStringRef cfProxyType = (CFStringRef)CFDictionaryGetValue(dict, kCFProxyTypeKey);
-    if (CFStringCompare(cfProxyType, kCFProxyTypeNone, 0) == kCFCompareEqualTo) {
-        proxyType = QNetworkProxy::NoProxy;
-    } else if (CFStringCompare(cfProxyType, kCFProxyTypeFTP, 0) == kCFCompareEqualTo) {
-        proxyType = QNetworkProxy::FtpCachingProxy;
-    } else if (CFStringCompare(cfProxyType, kCFProxyTypeHTTP, 0) == kCFCompareEqualTo) {
-        proxyType = QNetworkProxy::HttpProxy;
-    } else if (CFStringCompare(cfProxyType, kCFProxyTypeHTTPS, 0) == kCFCompareEqualTo) {
-        proxyType = QNetworkProxy::HttpProxy;
-    } else if (CFStringCompare(cfProxyType, kCFProxyTypeSOCKS, 0) == kCFCompareEqualTo) {
-        proxyType = QNetworkProxy::Socks5Proxy;
-    }
-
-    hostName = QCFString::toQString((CFStringRef)CFDictionaryGetValue(dict, kCFProxyHostNameKey));
-    user     = QCFString::toQString((CFStringRef)CFDictionaryGetValue(dict, kCFProxyUsernameKey));
-    password = QCFString::toQString((CFStringRef)CFDictionaryGetValue(dict, kCFProxyPasswordKey));
-
-    CFNumberRef portNumber = (CFNumberRef)CFDictionaryGetValue(dict, kCFProxyPortNumberKey);
-    if (portNumber) {
-        CFNumberGetValue(portNumber, kCFNumberSInt16Type, &port);
-    }
-
-    return QNetworkProxy(proxyType, hostName, port, user, password);
-}
-
-const char * cfurlErrorDescription(SInt32 errorCode)
-{
-    switch (errorCode) {
-        case kCFURLUnknownError:
-            return "Unknown Error";
-        case kCFURLUnknownSchemeError:
-            return "Unknown Scheme";
-        case kCFURLResourceNotFoundError:
-            return "Resource Not Found";
-        case kCFURLResourceAccessViolationError:
-            return "Resource Access Violation";
-        case kCFURLRemoteHostUnavailableError:
-            return "Remote Host Unavailable";
-        case kCFURLImproperArgumentsError:
-            return "Improper Arguments";
-        case kCFURLUnknownPropertyKeyError:
-            return "Unknown Property Key";
-        case kCFURLPropertyKeyUnavailableError:
-            return "Property Key Unavailable";
-        case kCFURLTimeoutError:
-            return "Timeout";
-        default:
-            return "Really Unknown Error";
-    }
-}
-
-QList<QNetworkProxy> macQueryInternal(const QNetworkProxyQuery &query)
-{
-    QList<QNetworkProxy> result;
-
-    // obtain a dictionary to the proxy settings:
-    CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);
-    if (!dict) {
-        qWarning("QNetworkProxyFactory::systemProxyForQuery: SCDynamicStoreCopyProxies returned NULL");
-        return result;          // failed
-    }
-
-    if (isHostExcluded(dict, query.peerHostName())) {
-        CFRelease(dict);
-        return result;          // no proxy for this host
-    }
-
-    // is there a PAC enabled? If so, use it first.
-    CFNumberRef pacEnabled;
-    if ((pacEnabled = (CFNumberRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigEnable))) {
-        int enabled;
-        if (CFNumberGetValue(pacEnabled, kCFNumberIntType, &enabled) && enabled) {
-            // PAC is enabled
-            CFStringRef cfPacLocation = (CFStringRef)CFDictionaryGetValue(dict, kSCPropNetProxiesProxyAutoConfigURLString);
-
-#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
-            if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
-                QCFType<CFDataRef> pacData;
-                QCFType<CFURLRef> pacUrl = CFURLCreateWithString(kCFAllocatorDefault, cfPacLocation, NULL);
-                SInt32 errorCode;
-                if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault, pacUrl, &pacData, NULL, NULL, &errorCode)) {
-                    QString pacLocation = QCFString::toQString(cfPacLocation);
-                    qWarning("Unable to get the PAC script at \"%s\" (%s)", qPrintable(pacLocation), cfurlErrorDescription(errorCode));
-                    return result;
-                }
-
-                QCFType<CFStringRef> pacScript = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, pacData, kCFStringEncodingISOLatin1);
-                if (!pacScript) {
-                    // This should never happen, but the documentation says it may return NULL if there was a problem creating the object.
-                    QString pacLocation = QCFString::toQString(cfPacLocation);
-                    qWarning("Unable to read the PAC script at \"%s\"", qPrintable(pacLocation));
-                    return result;
-                }
-
-                QByteArray encodedURL = query.url().toEncoded(); // converted to UTF-8
-                if (encodedURL.isEmpty()) {
-                    return result; // Invalid URL, abort
-                }
-
-                QCFType<CFURLRef> targetURL = CFURLCreateWithBytes(kCFAllocatorDefault, (UInt8*)encodedURL.data(), encodedURL.size(), kCFStringEncodingUTF8, NULL);
-                if (!targetURL) {
-                    return result; // URL creation problem, abort
-                }
-
-                QCFType<CFErrorRef> pacError;
-                QCFType<CFArrayRef> proxies = CFNetworkCopyProxiesForAutoConfigurationScript(pacScript, targetURL, &pacError);
-                if (!proxies) {
-                    QString pacLocation = QCFString::toQString(cfPacLocation);
-                    QCFType<CFStringRef> pacErrorDescription = CFErrorCopyDescription(pacError);
-                    qWarning("Execution of PAC script at \"%s\" failed: %s", qPrintable(pacLocation), qPrintable(QCFString::toQString(pacErrorDescription)));
-                    return result;
-                }
-
-                CFIndex size = CFArrayGetCount(proxies);
-                for (CFIndex i = 0; i < size; ++i) {
-                    CFDictionaryRef proxy = (CFDictionaryRef)CFArrayGetValueAtIndex(proxies, i);
-                    result << proxyFromDictionary(proxy);
-                }
-                return result;
-            } else
-#endif
-            {
-                QString pacLocation = QCFString::toQString(cfPacLocation);
-                qWarning("Mac system proxy: PAC script at \"%s\" not handled", qPrintable(pacLocation));
-            }
-        }
-    }
-
-    // no PAC, decide which proxy we're looking for based on the query
-    bool isHttps = false;
-    QString protocol = query.protocolTag().toLower();
-
-    // try the protocol-specific proxy
-    QNetworkProxy protocolSpecificProxy;
-    if (protocol == QLatin1String("ftp")) {
-        protocolSpecificProxy =
-            proxyFromDictionary(dict, QNetworkProxy::FtpCachingProxy,
-                                kSCPropNetProxiesFTPEnable,
-                                kSCPropNetProxiesFTPProxy,
-                                kSCPropNetProxiesFTPPort);
-    } else if (protocol == QLatin1String("http")) {
-        protocolSpecificProxy =
-            proxyFromDictionary(dict, QNetworkProxy::HttpProxy,
-                                kSCPropNetProxiesHTTPEnable,
-                                kSCPropNetProxiesHTTPProxy,
-                                kSCPropNetProxiesHTTPPort);
-    } else if (protocol == QLatin1String("https")) {
-        isHttps = true;
-        protocolSpecificProxy =
-            proxyFromDictionary(dict, QNetworkProxy::HttpProxy,
-                                kSCPropNetProxiesHTTPSEnable,
-                                kSCPropNetProxiesHTTPSProxy,
-                                kSCPropNetProxiesHTTPSPort);
-    }
-    if (protocolSpecificProxy.type() != QNetworkProxy::DefaultProxy)
-        result << protocolSpecificProxy;
-
-    // let's add SOCKSv5 if present too
-    QNetworkProxy socks5 = proxyFromDictionary(dict, QNetworkProxy::Socks5Proxy,
-                                               kSCPropNetProxiesSOCKSEnable,
-                                               kSCPropNetProxiesSOCKSProxy,
-                                               kSCPropNetProxiesSOCKSPort);
-    if (socks5.type() != QNetworkProxy::DefaultProxy)
-        result << socks5;
-
-    // let's add the HTTPS proxy if present (and if we haven't added
-    // yet)
-    if (!isHttps) {
-        QNetworkProxy https = proxyFromDictionary(dict, QNetworkProxy::HttpProxy,
-                                                  kSCPropNetProxiesHTTPSEnable,
-                                                  kSCPropNetProxiesHTTPSProxy,
-                                                  kSCPropNetProxiesHTTPSPort);
-        if (https.type() != QNetworkProxy::DefaultProxy && https != protocolSpecificProxy)
-            result << https;
-    }
-
-    CFRelease(dict);
-    return result;
-}
-
-QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &query)
-{
-    QList<QNetworkProxy> result = macQueryInternal(query);
-    if (result.isEmpty())
-        result << QNetworkProxy::NoProxy;
-
-    return result;
-}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/network/kernel/qnetworkproxy_win.cpp b/src/network/kernel/qnetworkproxy_win.cpp
deleted file mode 100644 (file)
index f25ea00..0000000
+++ /dev/null
@@ -1,601 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qnetworkproxy.h"
-
-#ifndef QT_NO_NETWORKPROXY
-
-#include <qmutex.h>
-#include <qstringlist.h>
-#include <qregexp.h>
-#include <qurl.h>
-#include <qnetworkinterface.h>
-
-#include <string.h>
-#include <qt_windows.h>
-#include <wininet.h>
-#include <qsystemlibrary_p.h>
-#include "qnetworkfunctions_wince.h"
-
-/*
- * Information on the WinHTTP DLL:
- *  http://msdn.microsoft.com/en-us/library/aa384122(VS.85).aspx example for WPAD
- *
- *  http://msdn.microsoft.com/en-us/library/aa384097(VS.85).aspx WinHttpGetProxyForUrl
- *  http://msdn.microsoft.com/en-us/library/aa384096(VS.85).aspx WinHttpGetIEProxyConfigForCurrentUs
- *  http://msdn.microsoft.com/en-us/library/aa384095(VS.85).aspx WinHttpGetDefaultProxyConfiguration
- */
-
-// We don't want to include winhttp.h because that's not
-// present in some Windows SDKs (I don't know why)
-// So, instead, copy the definitions here
-
-typedef struct {
-  DWORD dwFlags;
-  DWORD dwAutoDetectFlags;
-  LPCWSTR lpszAutoConfigUrl;
-  LPVOID lpvReserved;
-  DWORD dwReserved;
-  BOOL fAutoLogonIfChallenged;
-} WINHTTP_AUTOPROXY_OPTIONS;
-
-typedef struct {
-  DWORD dwAccessType;
-  LPWSTR lpszProxy;
-  LPWSTR lpszProxyBypass;
-} WINHTTP_PROXY_INFO;
-
-typedef struct {
-  BOOL fAutoDetect;
-  LPWSTR lpszAutoConfigUrl;
-  LPWSTR lpszProxy;
-  LPWSTR lpszProxyBypass;
-} WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
-
-#define WINHTTP_AUTOPROXY_AUTO_DETECT           0x00000001
-#define WINHTTP_AUTOPROXY_CONFIG_URL            0x00000002
-
-#define WINHTTP_AUTO_DETECT_TYPE_DHCP           0x00000001
-#define WINHTTP_AUTO_DETECT_TYPE_DNS_A          0x00000002
-
-#define WINHTTP_ACCESS_TYPE_DEFAULT_PROXY               0
-#define WINHTTP_ACCESS_TYPE_NO_PROXY                    1
-#define WINHTTP_ACCESS_TYPE_NAMED_PROXY                 3
-
-#define WINHTTP_NO_PROXY_NAME     NULL
-#define WINHTTP_NO_PROXY_BYPASS   NULL
-
-#define WINHTTP_ERROR_BASE                      12000
-#define ERROR_WINHTTP_LOGIN_FAILURE             (WINHTTP_ERROR_BASE + 15)
-#define ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT (WINHTTP_ERROR_BASE + 167)
-#define ERROR_WINHTTP_AUTODETECTION_FAILED      (WINHTTP_ERROR_BASE + 180)
-
-QT_BEGIN_NAMESPACE
-
-typedef BOOL (WINAPI * PtrWinHttpGetProxyForUrl)(HINTERNET, LPCWSTR, WINHTTP_AUTOPROXY_OPTIONS*, WINHTTP_PROXY_INFO*);
-typedef HINTERNET (WINAPI * PtrWinHttpOpen)(LPCWSTR, DWORD, LPCWSTR, LPCWSTR,DWORD);
-typedef BOOL (WINAPI * PtrWinHttpGetDefaultProxyConfiguration)(WINHTTP_PROXY_INFO*);
-typedef BOOL (WINAPI * PtrWinHttpGetIEProxyConfigForCurrentUser)(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG*);
-typedef BOOL (WINAPI * PtrWinHttpCloseHandle)(HINTERNET);
-typedef SC_HANDLE (WINAPI * PtrOpenSCManager)(LPCWSTR lpMachineName, LPCWSTR lpDatabaseName, DWORD dwDesiredAccess);
-typedef BOOL (WINAPI * PtrEnumServicesStatusEx)(SC_HANDLE hSCManager, SC_ENUM_TYPE InfoLevel, DWORD dwServiceType, DWORD dwServiceState, LPBYTE lpServices, DWORD cbBufSize, LPDWORD pcbBytesNeeded,
-    LPDWORD lpServicesReturned, LPDWORD lpResumeHandle, LPCWSTR pszGroupName);
-typedef BOOL (WINAPI * PtrCloseServiceHandle)(SC_HANDLE hSCObject);
-static PtrWinHttpGetProxyForUrl ptrWinHttpGetProxyForUrl = 0;
-static PtrWinHttpOpen ptrWinHttpOpen = 0;
-static PtrWinHttpGetDefaultProxyConfiguration ptrWinHttpGetDefaultProxyConfiguration = 0;
-static PtrWinHttpGetIEProxyConfigForCurrentUser ptrWinHttpGetIEProxyConfigForCurrentUser = 0;
-static PtrWinHttpCloseHandle ptrWinHttpCloseHandle = 0;
-static PtrOpenSCManager ptrOpenSCManager = 0;
-static PtrEnumServicesStatusEx ptrEnumServicesStatusEx = 0;
-static PtrCloseServiceHandle ptrCloseServiceHandle = 0;
-
-
-static bool currentProcessIsService()
-{
-    if (!ptrOpenSCManager || !ptrEnumServicesStatusEx|| !ptrCloseServiceHandle)
-        return false;
-
-    SC_HANDLE hSCM = ptrOpenSCManager(0, 0, SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT);
-    if (!hSCM)
-        return false;
-
-    ULONG bufSize = 0;
-    ULONG nbServices = 0;
-    if (ptrEnumServicesStatusEx(hSCM, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_ACTIVE, 0, bufSize, &bufSize, &nbServices, 0, 0))
-        return false; //error case
-
-    LPENUM_SERVICE_STATUS_PROCESS info = reinterpret_cast<LPENUM_SERVICE_STATUS_PROCESS>(malloc(bufSize));
-    bool foundService = false;
-    if (ptrEnumServicesStatusEx(hSCM, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_ACTIVE, (LPBYTE)info, bufSize, &bufSize, &nbServices, 0, 0)) {
-        DWORD currProcId = GetCurrentProcessId();
-        for (ULONG i = 0; i < nbServices && !foundService; i++) {
-            if (info[i].ServiceStatusProcess.dwProcessId == currProcId)
-                foundService = true;
-        }
-    }
-
-    ptrCloseServiceHandle(hSCM);
-    free(info);
-    return foundService;
-}
-
-static QStringList splitSpaceSemicolon(const QString &source)
-{
-    QStringList list;
-    int start = 0;
-    int end;
-    while (true) {
-        int space = source.indexOf(QLatin1Char(' '), start);
-        int semicolon = source.indexOf(QLatin1Char(';'), start);
-        end = space;
-        if (semicolon != -1 && (end == -1 || semicolon < end))
-            end = semicolon;
-
-        if (end == -1) {
-            if (start != source.length())
-                list.append(source.mid(start));
-            return list;
-        }
-        if (start != end)
-            list.append(source.mid(start, end - start));
-        start = end + 1;
-    }
-    return list;
-}
-
-static bool isBypassed(const QString &host, const QStringList &bypassList)
-{
-    if (host.isEmpty())
-        return false;
-
-    bool isSimple = !host.contains(QLatin1Char('.')) && !host.contains(QLatin1Char(':'));
-
-    QHostAddress ipAddress;
-    bool isIpAddress = ipAddress.setAddress(host);
-
-    // always exclude loopback
-    if (isIpAddress && (ipAddress == QHostAddress::LocalHost || ipAddress == QHostAddress::LocalHostIPv6))
-        return true;
-
-    // does it match the list of exclusions?
-    foreach (const QString &entry, bypassList) {
-        if (entry == QLatin1String("<local>")) {
-            if (isSimple)
-                return true;
-            if (isIpAddress) {
-                //exclude all local subnets
-                foreach (const QNetworkInterface &iface, QNetworkInterface::allInterfaces()) {
-                    foreach (const QNetworkAddressEntry netaddr, iface.addressEntries()) {
-                        if (ipAddress.isInSubnet(netaddr.ip(), netaddr.prefixLength())) {
-                            return true;
-                        }
-                    }
-                }
-            }
-        }
-        if (isIpAddress && ipAddress.isInSubnet(QHostAddress::parseSubnet(entry))) {
-            return true;        // excluded
-        } else {
-            // do wildcard matching
-            QRegExp rx(entry, Qt::CaseInsensitive, QRegExp::Wildcard);
-            if (rx.exactMatch(host))
-                return true;
-        }
-    }
-
-    // host was not excluded
-    return false;
-}
-
-static QList<QNetworkProxy> filterProxyListByCapabilities(const QList<QNetworkProxy> &proxyList, const QNetworkProxyQuery &query)
-{
-    QNetworkProxy::Capabilities requiredCaps;
-    switch (query.queryType()) {
-    case QNetworkProxyQuery::TcpSocket:
-        requiredCaps = QNetworkProxy::TunnelingCapability;
-        break;
-    case QNetworkProxyQuery::UdpSocket:
-        requiredCaps = QNetworkProxy::UdpTunnelingCapability;
-        break;
-    case QNetworkProxyQuery::TcpServer:
-        requiredCaps = QNetworkProxy::ListeningCapability;
-        break;
-    default:
-        return proxyList;
-        break;
-    }
-    QList<QNetworkProxy> result;
-    foreach (const QNetworkProxy& proxy, proxyList) {
-        if (proxy.capabilities() & requiredCaps)
-            result.append(proxy);
-    }
-    return result;
-}
-
-static QList<QNetworkProxy> removeDuplicateProxies(const QList<QNetworkProxy> &proxyList)
-{
-    QList<QNetworkProxy> result;
-     foreach (QNetworkProxy proxy, proxyList) {
-         bool append = true;
-         for (int i=0; i < result.count(); i++) {
-             if (proxy.hostName() == result.at(i).hostName()
-                 && proxy.port() == result.at(i).port()) {
-                     append = false;
-                     // HttpProxy trumps FtpCachingProxy or HttpCachingProxy on the same host/port
-                     if (proxy.type() == QNetworkProxy::HttpProxy)
-                         result[i] = proxy;
-             }
-         }
-         if (append)
-             result.append(proxy);
-     }
-     return result;
-}
-
-static QList<QNetworkProxy> parseServerList(const QNetworkProxyQuery &query, const QStringList &proxyList)
-{
-    // Reference documentation from Microsoft:
-    // http://msdn.microsoft.com/en-us/library/aa383912(VS.85).aspx
-    //
-    // According to the website, the proxy server list is
-    // one or more of the space- or semicolon-separated strings in the format:
-    //   ([<scheme>=][<scheme>"://"]<server>[":"<port>])
-    // The first scheme relates to the protocol tag
-    // The second scheme, if present, overrides the proxy type
-
-    QList<QNetworkProxy> result;
-    QHash<QString, QNetworkProxy> taggedProxies;
-    const QString requiredTag = query.protocolTag();
-    bool checkTags = !requiredTag.isEmpty() && query.queryType() != QNetworkProxyQuery::TcpServer; //windows tags are only for clients
-    foreach (const QString &entry, proxyList) {
-        int server = 0;
-
-        QNetworkProxy::ProxyType proxyType = QNetworkProxy::HttpProxy;
-        quint16 port = 8080;
-
-        int pos = entry.indexOf(QLatin1Char('='));
-        QStringRef scheme;
-        QStringRef protocolTag;
-        if (pos != -1) {
-            scheme = protocolTag = entry.leftRef(pos);
-            server = pos + 1;
-        }
-        pos = entry.indexOf(QLatin1String("://"), server);
-        if (pos != -1) {
-            scheme = entry.midRef(server, pos - server);
-            server = pos + 3;
-        }
-
-        if (!scheme.isEmpty()) {
-            if (scheme == QLatin1String("http") || scheme == QLatin1String("https")) {
-                // no-op
-                // defaults are above
-            } else if (scheme == QLatin1String("socks") || scheme == QLatin1String("socks5")) {
-                proxyType = QNetworkProxy::Socks5Proxy;
-                port = 1080;
-            } else if (scheme == QLatin1String("ftp")) {
-                proxyType = QNetworkProxy::FtpCachingProxy;
-                port = 2121;
-            } else {
-                // unknown proxy type
-                continue;
-            }
-        }
-
-        pos = entry.indexOf(QLatin1Char(':'), server);
-        if (pos != -1) {
-            bool ok;
-            uint value = entry.mid(pos + 1).toUInt(&ok);
-            if (!ok || value > 65535)
-                continue;       // invalid port number
-
-            port = value;
-        } else {
-            pos = entry.length();
-        }
-
-        result << QNetworkProxy(proxyType, entry.mid(server, pos - server), port);
-        if (!protocolTag.isEmpty())
-            taggedProxies.insert(protocolTag.toString(), result.last());
-    }
-
-    if (checkTags && taggedProxies.contains(requiredTag)) {
-        if (query.queryType() == QNetworkProxyQuery::UrlRequest) {
-            result.clear();
-            result.append(taggedProxies.value(requiredTag));
-            return result;
-        } else {
-            result.prepend(taggedProxies.value(requiredTag));
-        }
-    }
-    if (!checkTags || requiredTag != QLatin1String("http")) {
-        // if there are different http proxies for http and https, prefer the https one (more likely to be capable of CONNECT)
-        QNetworkProxy httpProxy = taggedProxies.value(QLatin1String("http"));
-        QNetworkProxy httpsProxy = taggedProxies.value(QLatin1String("http"));
-        if (httpProxy != httpsProxy && httpProxy.type() == QNetworkProxy::HttpProxy && httpsProxy.type() == QNetworkProxy::HttpProxy) {
-            for (int i = 0; i < result.count(); i++) {
-                if (httpProxy == result.at(i))
-                    result[i].setType(QNetworkProxy::HttpCachingProxy);
-            }
-        }
-    }
-    result = filterProxyListByCapabilities(result, query);
-    return removeDuplicateProxies(result);
-}
-
-class QWindowsSystemProxy
-{
-public:
-    QWindowsSystemProxy();
-    ~QWindowsSystemProxy();
-    void init();
-
-    QMutex mutex;
-
-    HINTERNET hHttpSession;
-    WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions;
-
-    QString autoConfigUrl;
-    QStringList proxyServerList;
-    QStringList proxyBypass;
-    QList<QNetworkProxy> defaultResult;
-
-    bool initialized;
-    bool functional;
-    bool isAutoConfig;
-};
-
-Q_GLOBAL_STATIC(QWindowsSystemProxy, systemProxy)
-
-QWindowsSystemProxy::QWindowsSystemProxy()
-    : hHttpSession(0), initialized(false), functional(false), isAutoConfig(false)
-{
-    defaultResult << QNetworkProxy::NoProxy;
-}
-
-QWindowsSystemProxy::~QWindowsSystemProxy()
-{
-    if (hHttpSession)
-        ptrWinHttpCloseHandle(hHttpSession);
-}
-
-void QWindowsSystemProxy::init()
-{
-    if (initialized)
-        return;
-    initialized = true;
-
-#ifdef Q_OS_WINCE
-    // Windows CE does not have any of the following API
-    return;
-#else
-    // load the winhttp.dll library
-    QSystemLibrary lib(L"winhttp");
-    if (!lib.load())
-        return;                 // failed to load
-
-    ptrWinHttpOpen = (PtrWinHttpOpen)lib.resolve("WinHttpOpen");
-    ptrWinHttpCloseHandle = (PtrWinHttpCloseHandle)lib.resolve("WinHttpCloseHandle");
-    ptrWinHttpGetProxyForUrl = (PtrWinHttpGetProxyForUrl)lib.resolve("WinHttpGetProxyForUrl");
-    ptrWinHttpGetDefaultProxyConfiguration = (PtrWinHttpGetDefaultProxyConfiguration)lib.resolve("WinHttpGetDefaultProxyConfiguration");
-    ptrWinHttpGetIEProxyConfigForCurrentUser = (PtrWinHttpGetIEProxyConfigForCurrentUser)lib.resolve("WinHttpGetIEProxyConfigForCurrentUser");
-    ptrOpenSCManager = (PtrOpenSCManager) QSystemLibrary(L"advapi32").resolve("OpenSCManagerW");
-    ptrEnumServicesStatusEx = (PtrEnumServicesStatusEx) QSystemLibrary(L"advapi32").resolve("EnumServicesStatusExW");
-    ptrCloseServiceHandle = (PtrCloseServiceHandle) QSystemLibrary(L"advapi32").resolve("CloseServiceHandle");
-
-    // Try to obtain the Internet Explorer configuration.
-    WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig;
-    const bool hasIEConfig = ptrWinHttpGetIEProxyConfigForCurrentUser(&ieProxyConfig);
-    if (hasIEConfig) {
-        if (ieProxyConfig.lpszAutoConfigUrl) {
-            autoConfigUrl = QString::fromWCharArray(ieProxyConfig.lpszAutoConfigUrl);
-            GlobalFree(ieProxyConfig.lpszAutoConfigUrl);
-        }
-        if (ieProxyConfig.lpszProxy) {
-            // http://msdn.microsoft.com/en-us/library/aa384250%28VS.85%29.aspx speaks only about a "proxy URL",
-            // not multiple URLs. However we tested this and it can return multiple URLs. So we use splitSpaceSemicolon
-            // on it.
-            proxyServerList = splitSpaceSemicolon(QString::fromWCharArray(ieProxyConfig.lpszProxy));
-            GlobalFree(ieProxyConfig.lpszProxy);
-        }
-        if (ieProxyConfig.lpszProxyBypass) {
-            proxyBypass = splitSpaceSemicolon(QString::fromWCharArray(ieProxyConfig.lpszProxyBypass));
-            GlobalFree(ieProxyConfig.lpszProxyBypass);
-        }
-    }
-
-    if (!hasIEConfig ||
-        (currentProcessIsService() && proxyServerList.isEmpty() && proxyBypass.isEmpty())) {
-        // no user configuration
-        // attempt to get the default configuration instead
-        // that config will serve as default if WPAD fails
-        WINHTTP_PROXY_INFO proxyInfo;
-        if (ptrWinHttpGetDefaultProxyConfiguration(&proxyInfo) &&
-            proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NAMED_PROXY) {
-            // we got information from the registry
-            // overwrite the IE configuration, if any
-
-            proxyBypass = splitSpaceSemicolon(QString::fromWCharArray(proxyInfo.lpszProxyBypass));
-            proxyServerList = splitSpaceSemicolon(QString::fromWCharArray(proxyInfo.lpszProxy));
-        }
-
-        if (proxyInfo.lpszProxy)
-            GlobalFree(proxyInfo.lpszProxy);
-        if (proxyInfo.lpszProxyBypass)
-            GlobalFree(proxyInfo.lpszProxyBypass);
-    }
-
-    hHttpSession = NULL;
-    if (ieProxyConfig.fAutoDetect || !autoConfigUrl.isEmpty()) {
-        // open the handle and obtain the options
-        hHttpSession = ptrWinHttpOpen(L"Qt System Proxy access/1.0",
-                                      WINHTTP_ACCESS_TYPE_NO_PROXY,
-                                      WINHTTP_NO_PROXY_NAME,
-                                      WINHTTP_NO_PROXY_BYPASS,
-                                      0);
-        if (!hHttpSession)
-            return;
-
-        isAutoConfig = true;
-        memset(&autoProxyOptions, 0, sizeof autoProxyOptions);
-        autoProxyOptions.fAutoLogonIfChallenged = false;
-        //Although it is possible to specify dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT | WINHTTP_AUTOPROXY_CONFIG_URL
-        //this has poor performance (WPAD is attempted for every url, taking 2.5 seconds per interface,
-        //before the configured pac file is used)
-        if (ieProxyConfig.fAutoDetect) {
-            autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
-            autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP |
-                                                 WINHTTP_AUTO_DETECT_TYPE_DNS_A;
-        } else {
-            autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
-            autoProxyOptions.lpszAutoConfigUrl = (LPCWSTR)autoConfigUrl.utf16();
-        }
-    }
-
-    functional = isAutoConfig || !proxyServerList.isEmpty();
-#endif
-}
-
-QList<QNetworkProxy> QNetworkProxyFactory::systemProxyForQuery(const QNetworkProxyQuery &query)
-{
-    QWindowsSystemProxy *sp = systemProxy();
-    if (!sp)
-        return QList<QNetworkProxy>() << QNetworkProxy();
-
-    QMutexLocker locker(&sp->mutex);
-    sp->init();
-    if (!sp->functional)
-        return sp->defaultResult;
-
-    if (sp->isAutoConfig) {
-        WINHTTP_PROXY_INFO proxyInfo;
-
-        // try to get the proxy config for the URL
-        QUrl url = query.url();
-        // url could be empty, e.g. from QNetworkProxy::applicationProxy(), that's fine,
-        // we'll still ask for the proxy.
-        // But for a file url, we know we don't need one.
-        if (url.scheme() == QLatin1String("file") || url.scheme() == QLatin1String("qrc"))
-            return sp->defaultResult;
-        if (query.queryType() != QNetworkProxyQuery::UrlRequest) {
-            // change the scheme to https, maybe it'll work
-            url.setScheme(QLatin1String("https"));
-        }
-
-        bool getProxySucceeded = ptrWinHttpGetProxyForUrl(sp->hHttpSession,
-                                                (LPCWSTR)url.toString().utf16(),
-                                                &sp->autoProxyOptions,
-                                                &proxyInfo);
-        DWORD getProxyError = GetLastError();
-
-        if (!getProxySucceeded
-            && (ERROR_WINHTTP_AUTODETECTION_FAILED == getProxyError)) {
-            // WPAD failed
-            if (sp->autoConfigUrl.isEmpty()) {
-                //No config file could be retrieved on the network.
-                //Don't search for it next time again.
-                sp->isAutoConfig = false;
-            } else {
-                //pac file URL is specified as well, try using that
-                sp->autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
-                sp->autoProxyOptions.lpszAutoConfigUrl = (LPCWSTR)sp->autoConfigUrl.utf16();
-                getProxySucceeded = ptrWinHttpGetProxyForUrl(sp->hHttpSession,
-                                                (LPCWSTR)url.toString().utf16(),
-                                                &sp->autoProxyOptions,
-                                                &proxyInfo);
-                getProxyError = GetLastError();
-            }
-        }
-
-        if (!getProxySucceeded
-            && (ERROR_WINHTTP_LOGIN_FAILURE == getProxyError)) {
-            // We first tried without AutoLogon, because this might prevent caching the result.
-            // But now we've to enable it (http://msdn.microsoft.com/en-us/library/aa383153%28v=VS.85%29.aspx)
-            sp->autoProxyOptions.fAutoLogonIfChallenged = TRUE;
-            getProxySucceeded = ptrWinHttpGetProxyForUrl(sp->hHttpSession,
-                                               (LPCWSTR)url.toString().utf16(),
-                                                &sp->autoProxyOptions,
-                                                &proxyInfo);
-            getProxyError = GetLastError();
-        }
-
-        if (!getProxySucceeded
-            && (ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT == getProxyError)) {
-            // PAC file url is not connectable, or server returned error (e.g. http 404)
-            //Don't search for it next time again.
-            sp->isAutoConfig = false;
-        }
-
-        if (getProxySucceeded) {
-            // yes, we got a config for this URL
-            QString proxyBypass = QString::fromWCharArray(proxyInfo.lpszProxyBypass);
-            QStringList proxyServerList = splitSpaceSemicolon(QString::fromWCharArray(proxyInfo.lpszProxy));
-            if (proxyInfo.lpszProxy)
-                GlobalFree(proxyInfo.lpszProxy);
-            if (proxyInfo.lpszProxyBypass)
-                GlobalFree(proxyInfo.lpszProxyBypass);
-
-            if (proxyInfo.dwAccessType == WINHTTP_ACCESS_TYPE_NO_PROXY)
-                return sp->defaultResult; //i.e. the PAC file result was "DIRECT"
-            if (isBypassed(query.peerHostName(), splitSpaceSemicolon(proxyBypass)))
-                return sp->defaultResult;
-            return parseServerList(query, proxyServerList);
-        }
-
-        // GetProxyForUrl failed, fall back to static configuration
-    }
-
-    // static configuration
-    if (isBypassed(query.peerHostName(), sp->proxyBypass))
-        return sp->defaultResult;
-
-    QList<QNetworkProxy> result = parseServerList(query, sp->proxyServerList);
-    // In some cases, this was empty. See SF task 00062670
-    if (result.isEmpty())
-        return sp->defaultResult;
-
-    return result;
-}
-
-QT_END_NAMESPACE
-
-#endif
index 9bbbd1c..1991410 100644 (file)
@@ -274,14 +274,8 @@ QLocalSocket *QLocalServer::nextPendingConnection()
     if (d->pendingConnections.isEmpty())
         return 0;
     QLocalSocket *nextSocket = d->pendingConnections.dequeue();
-#ifndef QT_LOCALSOCKET_TCP
     if (d->pendingConnections.size() <= d->maxPendingConnections)
-#ifndef Q_OS_WIN
         d->socketNotifier->setEnabled(true);
-#else
-        d->connectionEventNotifier->setEnabled(true);
-#endif
-#endif
     return nextSocket;
 }
 
index 19aea8a..cddb27f 100644 (file)
 #include "qlocalserver.h"
 #include "qobject_p.h"
 #include <qqueue.h>
-
-#if defined(QT_LOCALSOCKET_TCP)
-#   include <qtcpserver.h>
-#elif defined(Q_OS_WIN)
-#   include <qt_windows.h>
-#   include <qwineventnotifier_p.h>
-#else
-#   include <qabstractsocketengine_p.h>
-#   include <qsocketnotifier.h>
-#endif
+#include <qabstractsocketengine_p.h>
+#include <qsocketnotifier.h>
 
 QT_BEGIN_NAMESPACE
 
@@ -77,9 +69,7 @@ class QLocalServerPrivate : public QObjectPrivate
 
 public:
     QLocalServerPrivate() :
-#if !defined(QT_LOCALSOCKET_TCP) && !defined(Q_OS_WIN)
             listenSocket(-1), socketNotifier(0),
-#endif
             maxPendingConnections(30), error(QAbstractSocket::UnknownSocketError)
     {
     }
@@ -91,29 +81,10 @@ public:
     void waitForNewConnection(int msec, bool *timedOut);
     void _q_onNewConnection();
 
-#if defined(QT_LOCALSOCKET_TCP)
-
-    QTcpServer tcpServer;
-    QMap<quintptr, QTcpSocket*> socketMap;
-#elif defined(Q_OS_WIN)
-    struct Listener {
-        HANDLE handle;
-        OVERLAPPED overlapped;
-        bool connected;
-    };
-
-    void setError(const QString &function);
-    bool addListener();
-
-    QList<Listener> listeners;
-    HANDLE eventHandle;
-    QWinEventNotifier *connectionEventNotifier;
-#else
     void setError(const QString &function);
 
     int listenSocket;
     QSocketNotifier *socketNotifier;
-#endif
 
     QString serverName;
     QString fullServerName;
diff --git a/src/network/socket/qlocalserver_win.cpp b/src/network/socket/qlocalserver_win.cpp
deleted file mode 100644 (file)
index 2484787..0000000
+++ /dev/null
@@ -1,210 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qlocalserver.h"
-#include "qlocalserver_p.h"
-#include "qlocalsocket.h"
-
-#include <qdebug.h>
-
-// The buffer size need to be 0 otherwise data could be
-// lost if the socket that has written data closes the connection
-// before it is read.  Pipewriter is used for write buffering.
-#define BUFSIZE 0
-
-// ###: This should be a property. Should replace the insane 50 on unix as well.
-#define SYSTEM_MAX_PENDING_SOCKETS 8
-
-QT_BEGIN_NAMESPACE
-
-bool QLocalServerPrivate::addListener()
-{
-    // The object must not change its address once the
-    // contained OVERLAPPED struct is passed to Windows.
-    listeners << Listener();
-    Listener &listener = listeners.last();
-
-    listener.handle = CreateNamedPipe(
-                 (const wchar_t *)fullServerName.utf16(), // pipe name
-                 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,       // read/write access
-                 PIPE_TYPE_BYTE |          // byte type pipe
-                 PIPE_READMODE_BYTE |      // byte-read mode
-                 PIPE_WAIT,                // blocking mode
-                 PIPE_UNLIMITED_INSTANCES, // max. instances
-                 BUFSIZE,                  // output buffer size
-                 BUFSIZE,                  // input buffer size
-                 3000,                     // client time-out
-                 NULL);
-
-    if (listener.handle == INVALID_HANDLE_VALUE) {
-        setError(QLatin1String("QLocalServerPrivate::addListener"));
-        listeners.removeLast();
-        return false;
-    }
-
-    memset(&listener.overlapped, 0, sizeof(listener.overlapped));
-    listener.overlapped.hEvent = eventHandle;
-    if (!ConnectNamedPipe(listener.handle, &listener.overlapped)) {
-        switch (GetLastError()) {
-        case ERROR_IO_PENDING:
-            listener.connected = false;
-            break;
-        case ERROR_PIPE_CONNECTED:
-            listener.connected = true;
-            SetEvent(eventHandle);
-            break;
-        default:
-            CloseHandle(listener.handle);
-            setError(QLatin1String("QLocalServerPrivate::addListener"));
-            listeners.removeLast();
-            return false;
-        }
-    } else {
-        Q_ASSERT_X(false, "QLocalServerPrivate::addListener", "The impossible happened");
-        SetEvent(eventHandle);
-    }
-    return true;
-}
-
-void QLocalServerPrivate::setError(const QString &function)
-{
-    int windowsError = GetLastError();
-    errorString = QString::fromLatin1("%1: %2").arg(function).arg(qt_error_string(windowsError));
-    error = QAbstractSocket::UnknownSocketError;
-}
-
-void QLocalServerPrivate::init()
-{
-}
-
-bool QLocalServerPrivate::removeServer(const QString &name)
-{
-    Q_UNUSED(name);
-    return true;
-}
-
-bool QLocalServerPrivate::listen(const QString &name)
-{
-    Q_Q(QLocalServer);
-
-    QString pipePath = QLatin1String("\\\\.\\pipe\\");
-    if (name.startsWith(pipePath))
-        fullServerName = name;
-    else
-        fullServerName = pipePath + name;
-
-    // Use only one event for all listeners of one socket.
-    // The idea is that listener events are rare, so polling all listeners once in a while is
-    // cheap compared to waiting for N additional events in each iteration of the main loop.
-    eventHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
-    connectionEventNotifier = new QWinEventNotifier(eventHandle , q);
-    q->connect(connectionEventNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_onNewConnection()));
-
-    for (int i = 0; i < SYSTEM_MAX_PENDING_SOCKETS; ++i)
-        if (!addListener())
-            return false;
-    return true;
-}
-
-void QLocalServerPrivate::_q_onNewConnection()
-{
-    Q_Q(QLocalServer);
-    DWORD dummy;
-
-    // Reset first, otherwise we could reset an event which was asserted
-    // immediately after we checked the conn status.
-    ResetEvent(eventHandle);
-
-    // Testing shows that there is indeed absolutely no guarantee which listener gets
-    // a client connection first, so there is no way around polling all of them.
-    for (int i = 0; i < listeners.size(); ) {
-        HANDLE handle = listeners[i].handle;
-        if (listeners[i].connected
-            || GetOverlappedResult(handle, &listeners[i].overlapped, &dummy, FALSE))
-        {
-            listeners.removeAt(i);
-
-            addListener();
-
-            if (pendingConnections.size() > maxPendingConnections)
-                connectionEventNotifier->setEnabled(false);
-
-            // Make this the last thing so connected slots can wreak the least havoc
-            q->incomingConnection((quintptr)handle);
-        } else {
-            if (GetLastError() != ERROR_IO_INCOMPLETE) {
-                q->close();
-                setError(QLatin1String("QLocalServerPrivate::_q_onNewConnection"));
-                return;
-            }
-
-            ++i;
-        }
-    }
-}
-
-void QLocalServerPrivate::closeServer()
-{
-    connectionEventNotifier->setEnabled(false); // Otherwise, closed handle is checked before deleter runs
-    connectionEventNotifier->deleteLater();
-    connectionEventNotifier = 0;
-    CloseHandle(eventHandle);
-    for (int i = 0; i < listeners.size(); ++i)
-        CloseHandle(listeners[i].handle);
-    listeners.clear();
-}
-
-void QLocalServerPrivate::waitForNewConnection(int msecs, bool *timedOut)
-{
-    Q_Q(QLocalServer);
-    if (!pendingConnections.isEmpty() || !q->isListening())
-        return;
-
-    DWORD result = WaitForSingleObject(eventHandle, (msecs == -1) ? INFINITE : msecs);
-    if (result == WAIT_TIMEOUT) {
-        if (timedOut)
-            *timedOut = true;
-    } else {
-        _q_onNewConnection();
-    }
-}
-
-QT_END_NAMESPACE
index f68fe32..1160c3b 100644 (file)
@@ -346,10 +346,8 @@ QLocalSocket::QLocalSocket(QObject * parent)
 QLocalSocket::~QLocalSocket()
 {
     close();
-#if !defined(Q_OS_WIN) && !defined(QT_LOCALSOCKET_TCP)
     Q_D(QLocalSocket);
     d->unixSocket.setParent(0);
-#endif
 }
 
 /*!
index 599e834..80afb9b 100644 (file)
@@ -126,20 +126,10 @@ protected:
 
 private:
     Q_DISABLE_COPY(QLocalSocket)
-#if defined(QT_LOCALSOCKET_TCP)
-    Q_PRIVATE_SLOT(d_func(), void _q_stateChanged(QAbstractSocket::SocketState))
-    Q_PRIVATE_SLOT(d_func(), void _q_error(QAbstractSocket::SocketError))
-#elif defined(Q_OS_WIN)
-    Q_PRIVATE_SLOT(d_func(), void _q_notified())
-    Q_PRIVATE_SLOT(d_func(), void _q_canWrite())
-    Q_PRIVATE_SLOT(d_func(), void _q_pipeClosed())
-    Q_PRIVATE_SLOT(d_func(), void _q_emitReadyRead())
-#else
     Q_PRIVATE_SLOT(d_func(), void _q_stateChanged(QAbstractSocket::SocketState))
     Q_PRIVATE_SLOT(d_func(), void _q_error(QAbstractSocket::SocketError))
     Q_PRIVATE_SLOT(d_func(), void _q_connectToSocket())
     Q_PRIVATE_SLOT(d_func(), void _q_abortConnectionAttempt())
-#endif
 };
 
 #ifndef QT_NO_DEBUG_STREAM
index 49c47c3..0be199a 100644 (file)
 #include "qiodevice_p.h"
 
 #include <qtimer.h>
-
-#if defined(QT_LOCALSOCKET_TCP)
-#   include "qtcpsocket.h"
-#elif defined(Q_OS_WIN)
-#   include "qwindowspipewriter_p.h"
-#   include "qringbuffer_p.h"
-#   include <qwineventnotifier_p.h>
-#else
-#   include "qabstractsocketengine_p.h"
-#   include <qtcpsocket.h>
-#   include <qsocketnotifier.h>
-#   include <errno.h>
-#endif
+#include "qabstractsocketengine_p.h"
+#include <qtcpsocket.h>
+#include <qsocketnotifier.h>
+#include <errno.h>
 
 QT_BEGIN_NAMESPACE
 
-#if !defined(Q_OS_WIN) || defined(QT_LOCALSOCKET_TCP)
-class QLocalUnixSocket : public QTcpSocket
-{
-
-public:
-    QLocalUnixSocket() : QTcpSocket()
-    {
-    };
-
-    inline void setSocketState(QAbstractSocket::SocketState state)
-    {
-        QTcpSocket::setSocketState(state);
-    };
-
-    inline void setErrorString(const QString &string)
-    {
-        QTcpSocket::setErrorString(string);
-    }
-
-    inline void setSocketError(QAbstractSocket::SocketError error)
-    {
-        QTcpSocket::setSocketError(error);
-    }
-
-    inline qint64 readData(char *data, qint64 maxSize)
-    {
-        return QTcpSocket::readData(data, maxSize);
-    }
-
-    inline qint64 writeData(const char *data, qint64 maxSize)
-    {
-        return QTcpSocket::writeData(data, maxSize);
-    }
-};
-#endif //#if !defined(Q_OS_WIN) || defined(QT_LOCALSOCKET_TCP)
-
 class QLocalSocketPrivate : public QIODevicePrivate
 {
     Q_DECLARE_PUBLIC(QLocalSocket)
@@ -119,40 +74,7 @@ public:
     QLocalSocketPrivate();
     void init();
 
-#if defined(QT_LOCALSOCKET_TCP)
-    QLocalUnixSocket* tcpSocket;
-    bool ownsTcpSocket;
-    void setSocket(QLocalUnixSocket*);
-    QString generateErrorString(QLocalSocket::LocalSocketError, const QString &function) const;
-    void errorOccurred(QLocalSocket::LocalSocketError, const QString &function);
-    void _q_stateChanged(QAbstractSocket::SocketState newState);
-    void _q_error(QAbstractSocket::SocketError newError);
-#elif defined(Q_OS_WIN)
-    ~QLocalSocketPrivate();
-    void destroyPipeHandles();
-    void setErrorString(const QString &function);
-    void _q_notified();
-    void _q_canWrite();
-    void _q_pipeClosed();
-    void _q_emitReadyRead();
-    DWORD checkPipeState();
-    void startAsyncRead();
-    bool completeAsyncRead();
-    void checkReadyRead();
-    HANDLE handle;
-    OVERLAPPED overlapped;
-    QWindowsPipeWriter *pipeWriter;
-    qint64 readBufferMaxSize;
-    QRingBuffer readBuffer;
-    int actualReadBufferSize;
-    QWinEventNotifier *dataReadNotifier;
-    QLocalSocket::LocalSocketError error;
-    bool readSequenceStarted;
-    bool pendingReadyRead;
-    bool pipeClosed;
-    static const qint64 initialReadBufferSize = 4096;
-#else
-    QLocalUnixSocket unixSocket;
+    QTcpSocket unixSocket;
     QString generateErrorString(QLocalSocket::LocalSocketError, const QString &function) const;
     void errorOccurred(QLocalSocket::LocalSocketError, const QString &function);
     void _q_stateChanged(QAbstractSocket::SocketState newState);
@@ -165,7 +87,6 @@ public:
     int connectingSocket;
     QString connectingName;
     QIODevice::OpenMode connectingOpenMode;
-#endif
 
     QString serverName;
     QString fullServerName;
index 5a9a52c..2f46f02 100644 (file)
@@ -58,10 +58,10 @@ QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(),
 
 void QLocalSocketPrivate::init()
 {
-    setSocket(new QLocalUnixSocket);
+    setSocket(new QTcpSocket);
 }
 
-void QLocalSocketPrivate::setSocket(QLocalUnixSocket* socket)
+void QLocalSocketPrivate::setSocket(QTcpSocket* socket)
 {
     if (ownsTcpSocket)
         delete tcpSocket;
@@ -275,7 +275,7 @@ bool QLocalSocket::setSocketDescriptor(quintptr socketDescriptor,
         foreach (QObject* child, localServer->children()) {
             QTcpSocket* childTcpSocket = qobject_cast<QTcpSocket*>(child);
             if (childTcpSocket && childTcpSocket->socketDescriptor() == socketDescriptor) {
-                d->setSocket( static_cast<QLocalUnixSocket*>(childTcpSocket) );
+                d->setSocket( childTcpSocket );
                 return true;
             }
         }
diff --git a/src/network/socket/qlocalsocket_win.cpp b/src/network/socket/qlocalsocket_win.cpp
deleted file mode 100644 (file)
index acab523..0000000
+++ /dev/null
@@ -1,633 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qlocalsocket_p.h"
-
-#include <qthread_p.h>
-#include <qcoreapplication.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-void QLocalSocketPrivate::init()
-{
-    Q_Q(QLocalSocket);
-    memset(&overlapped, 0, sizeof(overlapped));
-    overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
-    dataReadNotifier = new QWinEventNotifier(overlapped.hEvent, q);
-    q->connect(dataReadNotifier, SIGNAL(activated(HANDLE)), q, SLOT(_q_notified()));
-}
-
-void QLocalSocketPrivate::setErrorString(const QString &function)
-{
-    Q_Q(QLocalSocket);
-    BOOL windowsError = GetLastError();
-    QLocalSocket::LocalSocketState currentState = state;
-
-    // If the connectToServer fails due to WaitNamedPipe() time-out, assume ConnectionError  
-    if (state == QLocalSocket::ConnectingState && windowsError == ERROR_SEM_TIMEOUT)
-        windowsError = ERROR_NO_DATA;
-
-    switch (windowsError) {
-    case ERROR_PIPE_NOT_CONNECTED:
-    case ERROR_BROKEN_PIPE:
-    case ERROR_NO_DATA:
-        error = QLocalSocket::ConnectionError;
-        errorString = QLocalSocket::tr("%1: Connection error").arg(function);
-        state = QLocalSocket::UnconnectedState;
-        break;
-    case ERROR_FILE_NOT_FOUND:
-        error = QLocalSocket::ServerNotFoundError;
-        errorString = QLocalSocket::tr("%1: Invalid name").arg(function);
-        state = QLocalSocket::UnconnectedState;
-        break;
-    case ERROR_ACCESS_DENIED:
-        error = QLocalSocket::SocketAccessError;
-        errorString = QLocalSocket::tr("%1: Access denied").arg(function);
-        state = QLocalSocket::UnconnectedState;
-        break;
-    default:
-        error = QLocalSocket::UnknownSocketError;
-        errorString = QLocalSocket::tr("%1: Unknown error %2").arg(function).arg(windowsError);
-#if defined QLOCALSOCKET_DEBUG
-        qWarning() << "QLocalSocket error not handled:" << errorString;
-#endif
-        state = QLocalSocket::UnconnectedState;
-    }
-
-    if (currentState != state) {
-        q->emit stateChanged(state);
-        if (state == QLocalSocket::UnconnectedState)
-            q->emit disconnected();
-    }
-    emit q->error(error);
-}
-
-QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(),
-       handle(INVALID_HANDLE_VALUE),
-       pipeWriter(0),
-       readBufferMaxSize(0),
-       actualReadBufferSize(0),
-       error(QLocalSocket::UnknownSocketError),
-       readSequenceStarted(false),
-       pendingReadyRead(false),
-       pipeClosed(false),
-       state(QLocalSocket::UnconnectedState)
-{
-}
-
-QLocalSocketPrivate::~QLocalSocketPrivate()
-{
-    destroyPipeHandles();
-    CloseHandle(overlapped.hEvent);
-}
-
-void QLocalSocketPrivate::destroyPipeHandles()
-{
-    if (handle != INVALID_HANDLE_VALUE) {
-        DisconnectNamedPipe(handle);
-        CloseHandle(handle);
-    }
-}
-
-void QLocalSocket::connectToServer(const QString &name, OpenMode openMode)
-{
-    Q_D(QLocalSocket);
-    if (state() == ConnectedState || state() == ConnectingState)
-        return;
-
-    d->error = QLocalSocket::UnknownSocketError;
-    d->errorString = QString();
-    d->state = ConnectingState;
-    emit stateChanged(d->state);
-    if (name.isEmpty()) {
-        d->error = QLocalSocket::ServerNotFoundError;
-        setErrorString(QLocalSocket::tr("%1: Invalid name").arg(QLatin1String("QLocalSocket::connectToServer")));
-        d->state = UnconnectedState;
-        emit error(d->error);
-        emit stateChanged(d->state);
-        return;
-    }
-
-    QString pipePath = QLatin1String("\\\\.\\pipe\\");
-    if (name.startsWith(pipePath))
-        d->fullServerName = name;
-    else
-        d->fullServerName = pipePath + name;
-    // Try to open a named pipe
-    HANDLE localSocket;
-    forever {
-        DWORD permissions = (openMode & QIODevice::ReadOnly) ? GENERIC_READ : 0;
-        permissions |= (openMode & QIODevice::WriteOnly) ? GENERIC_WRITE : 0;
-        localSocket = CreateFile((const wchar_t *)d->fullServerName.utf16(),   // pipe name
-                                 permissions,
-                                 0,              // no sharing
-                                 NULL,           // default security attributes
-                                 OPEN_EXISTING,  // opens existing pipe
-                                 FILE_FLAG_OVERLAPPED,
-                                 NULL);          // no template file
-
-        if (localSocket != INVALID_HANDLE_VALUE)
-            break;
-        DWORD error = GetLastError();
-        // It is really an error only if it is not ERROR_PIPE_BUSY
-        if (ERROR_PIPE_BUSY != error) {
-            break;
-        }
-
-        // All pipe instances are busy, so wait until connected or up to 5 seconds.
-        if (!WaitNamedPipe((const wchar_t *)d->fullServerName.utf16(), 5000))
-            break;
-    }
-
-    if (localSocket == INVALID_HANDLE_VALUE) {
-        d->setErrorString(QLatin1String("QLocalSocket::connectToServer"));
-        d->fullServerName = QString();
-        return;
-    }
-
-    // we have a valid handle
-    d->serverName = name;
-    if (setSocketDescriptor((quintptr)localSocket, ConnectedState, openMode)) {
-        d->handle = localSocket;
-        emit connected();
-    }
-}
-
-// This is reading from the buffer
-qint64 QLocalSocket::readData(char *data, qint64 maxSize)
-{
-    Q_D(QLocalSocket);
-
-    if (d->pipeClosed && d->actualReadBufferSize == 0)
-        return -1;  // signal EOF
-
-    qint64 readSoFar;
-    // If startAsyncRead() read data, copy it to its destination.
-    if (maxSize == 1 && d->actualReadBufferSize > 0) {
-        *data = d->readBuffer.getChar();
-        d->actualReadBufferSize--;
-        readSoFar = 1;
-    } else {
-        qint64 bytesToRead = qMin(qint64(d->actualReadBufferSize), maxSize);
-        readSoFar = 0;
-        while (readSoFar < bytesToRead) {
-            const char *ptr = d->readBuffer.readPointer();
-            int bytesToReadFromThisBlock = qMin(bytesToRead - readSoFar,
-                                                qint64(d->readBuffer.nextDataBlockSize()));
-            memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
-            readSoFar += bytesToReadFromThisBlock;
-            d->readBuffer.free(bytesToReadFromThisBlock);
-            d->actualReadBufferSize -= bytesToReadFromThisBlock;
-        }
-    }
-
-    if (d->pipeClosed) {
-        if (d->actualReadBufferSize == 0)
-            QTimer::singleShot(0, this, SLOT(_q_pipeClosed()));
-    } else {
-        if (!d->readSequenceStarted)
-            d->startAsyncRead();
-        d->checkReadyRead();
-    }
-
-    return readSoFar;
-}
-
-/*!
-    \internal
-    Schedules or cancels a readyRead() emission depending on actual data availability
- */
-void QLocalSocketPrivate::checkReadyRead()
-{
-    if (actualReadBufferSize > 0) {
-        if (!pendingReadyRead) {
-            Q_Q(QLocalSocket);
-            QTimer::singleShot(0, q, SLOT(_q_emitReadyRead()));
-            pendingReadyRead = true;
-        }
-    } else {
-        pendingReadyRead = false;
-    }
-}
-
-/*!
-    \internal
-    Reads data from the socket into the readbuffer
- */
-void QLocalSocketPrivate::startAsyncRead()
-{
-    do {
-        DWORD bytesToRead = checkPipeState();
-        if (pipeClosed)
-            return;
-
-        if (bytesToRead == 0) {
-            // There are no bytes in the pipe but we need to
-            // start the overlapped read with some buffer size.
-            bytesToRead = initialReadBufferSize;
-        }
-
-        if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - readBuffer.size())) {
-            bytesToRead = readBufferMaxSize - readBuffer.size();
-            if (bytesToRead == 0) {
-                // Buffer is full. User must read data from the buffer
-                // before we can read more from the pipe.
-                return;
-            }
-        }
-
-        char *ptr = readBuffer.reserve(bytesToRead);
-
-        readSequenceStarted = true;
-        if (ReadFile(handle, ptr, bytesToRead, NULL, &overlapped)) {
-            completeAsyncRead();
-        } else {
-            switch (GetLastError()) {
-                case ERROR_IO_PENDING:
-                    // This is not an error. We're getting notified, when data arrives.
-                    return;
-                case ERROR_MORE_DATA:
-                    // This is not an error. The synchronous read succeeded.
-                    // We're connected to a message mode pipe and the message
-                    // didn't fit into the pipe's system buffer.
-                    completeAsyncRead();
-                    break;
-                case ERROR_PIPE_NOT_CONNECTED:
-                    {
-                        // It may happen, that the other side closes the connection directly
-                        // after writing data. Then we must set the appropriate socket state.
-                        pipeClosed = true;
-                        Q_Q(QLocalSocket);
-                        emit q->readChannelFinished();
-                        return;
-                    }
-                default:
-                    setErrorString(QLatin1String("QLocalSocketPrivate::startAsyncRead"));
-                    return;
-            }
-        }
-    } while (!readSequenceStarted);
-}
-
-/*!
-    \internal
-    Sets the correct size of the read buffer after a read operation.
-    Returns false, if an error occurred or the connection dropped.
- */
-bool QLocalSocketPrivate::completeAsyncRead()
-{
-    ResetEvent(overlapped.hEvent);
-    readSequenceStarted = false;
-
-    DWORD bytesRead;
-    if (!GetOverlappedResult(handle, &overlapped, &bytesRead, TRUE)) {
-        switch (GetLastError()) {
-        case ERROR_MORE_DATA:
-            // This is not an error. We're connected to a message mode
-            // pipe and the message didn't fit into the pipe's system
-            // buffer. We will read the remaining data in the next call.
-            break;
-        case ERROR_PIPE_NOT_CONNECTED:
-            return false;
-        default:
-            setErrorString(QLatin1String("QLocalSocketPrivate::completeAsyncRead"));
-            return false;
-        }
-    }
-
-    actualReadBufferSize += bytesRead;
-    readBuffer.truncate(actualReadBufferSize);
-    return true;
-}
-
-qint64 QLocalSocket::writeData(const char *data, qint64 maxSize)
-{
-    Q_D(QLocalSocket);
-    if (!d->pipeWriter) {
-        d->pipeWriter = new QWindowsPipeWriter(d->handle, this);
-        connect(d->pipeWriter, SIGNAL(canWrite()), this, SLOT(_q_canWrite()));
-        connect(d->pipeWriter, SIGNAL(bytesWritten(qint64)), this, SIGNAL(bytesWritten(qint64)));
-        d->pipeWriter->start();
-    }
-    return d->pipeWriter->write(data, maxSize);
-}
-
-void QLocalSocket::abort()
-{
-    Q_D(QLocalSocket);
-    if (d->pipeWriter) {
-        delete d->pipeWriter;
-        d->pipeWriter = 0;
-    }
-    close();
-}
-
-/*!
-    \internal
-    Returns the number of available bytes in the pipe.
-    Sets QLocalSocketPrivate::pipeClosed to true if the connection is broken.
- */
-DWORD QLocalSocketPrivate::checkPipeState()
-{
-    Q_Q(QLocalSocket);
-    DWORD bytes;
-    if (PeekNamedPipe(handle, NULL, 0, NULL, &bytes, NULL)) {
-        return bytes;
-    } else {
-        if (!pipeClosed) {
-            pipeClosed = true;
-            emit q->readChannelFinished();
-            if (actualReadBufferSize == 0)
-                QTimer::singleShot(0, q, SLOT(_q_pipeClosed()));
-        }
-    }
-    return 0;
-}
-
-void QLocalSocketPrivate::_q_pipeClosed()
-{
-    Q_Q(QLocalSocket);
-    q->close();
-}
-
-qint64 QLocalSocket::bytesAvailable() const
-{
-    Q_D(const QLocalSocket);
-    qint64 available = QIODevice::bytesAvailable();
-    available += (qint64) d->actualReadBufferSize;
-    return available;
-}
-
-qint64 QLocalSocket::bytesToWrite() const
-{
-    Q_D(const QLocalSocket);
-    return (d->pipeWriter) ? d->pipeWriter->bytesToWrite() : 0;
-}
-
-bool QLocalSocket::canReadLine() const
-{
-    Q_D(const QLocalSocket);
-    if (state() != ConnectedState)
-        return false;
-    return (QIODevice::canReadLine()
-            || d->readBuffer.indexOf('\n', d->actualReadBufferSize) != -1);
-}
-
-void QLocalSocket::close()
-{
-    Q_D(QLocalSocket);
-    if (state() == UnconnectedState)
-        return;
-
-    QIODevice::close();
-    d->state = ClosingState;
-    emit stateChanged(d->state);
-    if (!d->pipeClosed)
-        emit readChannelFinished();
-    d->serverName = QString();
-    d->fullServerName = QString();
-
-    if (state() != UnconnectedState && bytesToWrite() > 0) {
-        disconnectFromServer();
-        return;
-    }
-    d->readSequenceStarted = false;
-    d->pendingReadyRead = false;
-    d->pipeClosed = false;
-    d->destroyPipeHandles();
-    d->handle = INVALID_HANDLE_VALUE;
-    ResetEvent(d->overlapped.hEvent);
-    d->state = UnconnectedState;
-    emit stateChanged(d->state);
-    emit disconnected();
-    if (d->pipeWriter) {
-        delete d->pipeWriter;
-        d->pipeWriter = 0;
-    }
-}
-
-bool QLocalSocket::flush()
-{
-    Q_D(QLocalSocket);
-    if (d->pipeWriter)
-        return d->pipeWriter->waitForWrite(0);
-    return false;
-}
-
-void QLocalSocket::disconnectFromServer()
-{
-    Q_D(QLocalSocket);
-
-    // Are we still connected?
-    if (!isValid()) {
-        // If we have unwritten data, the pipeWriter is still present.
-        // It must be destroyed before close() to prevent an infinite loop.
-        delete d->pipeWriter;
-        d->pipeWriter = 0;
-    }
-
-    flush();
-    if (d->pipeWriter && d->pipeWriter->bytesToWrite() != 0) {
-        d->state = QLocalSocket::ClosingState;
-        emit stateChanged(d->state);
-    } else {
-        close();
-    }
-}
-
-QLocalSocket::LocalSocketError QLocalSocket::error() const
-{
-    Q_D(const QLocalSocket);
-    return d->error;
-}
-
-bool QLocalSocket::setSocketDescriptor(quintptr socketDescriptor,
-              LocalSocketState socketState, OpenMode openMode)
-{
-    Q_D(QLocalSocket);
-    d->readBuffer.clear();
-    d->actualReadBufferSize = 0;
-    QIODevice::open(openMode);
-    d->handle = (int*)socketDescriptor;
-    d->state = socketState;
-    emit stateChanged(d->state);
-    if (d->state == ConnectedState && openMode.testFlag(QIODevice::ReadOnly)) {
-        d->startAsyncRead();
-        d->checkReadyRead();
-    }
-    return true;
-}
-
-void QLocalSocketPrivate::_q_canWrite()
-{
-    Q_Q(QLocalSocket);
-    if (state == QLocalSocket::ClosingState)
-        q->close();
-}
-
-void QLocalSocketPrivate::_q_notified()
-{
-    Q_Q(QLocalSocket);
-    if (!completeAsyncRead()) {
-        pipeClosed = true;
-        emit q->readChannelFinished();
-        if (actualReadBufferSize == 0)
-            QTimer::singleShot(0, q, SLOT(_q_pipeClosed()));
-        return;
-    }
-    startAsyncRead();
-    pendingReadyRead = false;
-    emit q->readyRead();
-}
-
-void QLocalSocketPrivate::_q_emitReadyRead()
-{
-    if (pendingReadyRead) {
-        Q_Q(QLocalSocket);
-        pendingReadyRead = false;
-        emit q->readyRead();
-    }
-}
-
-quintptr QLocalSocket::socketDescriptor() const
-{
-    Q_D(const QLocalSocket);
-    return (quintptr)d->handle;
-}
-
-qint64 QLocalSocket::readBufferSize() const
-{
-    Q_D(const QLocalSocket);
-    return d->readBufferMaxSize;
-}
-
-void QLocalSocket::setReadBufferSize(qint64 size)
-{
-    Q_D(QLocalSocket);
-    d->readBufferMaxSize = size;
-}
-
-bool QLocalSocket::waitForConnected(int msecs)
-{
-    Q_UNUSED(msecs);
-    return (state() == ConnectedState);
-}
-
-bool QLocalSocket::waitForDisconnected(int msecs)
-{
-    Q_D(QLocalSocket);
-    if (state() == UnconnectedState)
-        return false;
-    if (!openMode().testFlag(QIODevice::ReadOnly)) {
-        qWarning("QLocalSocket::waitForDisconnected isn't supported for write only pipes.");
-        return false;
-    }
-    QIncrementalSleepTimer timer(msecs);
-    forever {
-        d->checkPipeState();
-        if (d->pipeClosed)
-            close();
-        if (state() == UnconnectedState)
-            return true;
-        Sleep(timer.nextSleepTime());
-        if (timer.hasTimedOut())
-            break;
-    }
-
-    return false;
-}
-
-bool QLocalSocket::isValid() const
-{
-    Q_D(const QLocalSocket);
-    return d->handle != INVALID_HANDLE_VALUE;
-}
-
-bool QLocalSocket::waitForReadyRead(int msecs)
-{
-    Q_D(QLocalSocket);
-
-    if (bytesAvailable() > 0)
-        return true;
-
-    if (d->state != QLocalSocket::ConnectedState)
-        return false;
-
-    // We already know that the pipe is gone, but did not enter the event loop yet.
-    if (d->pipeClosed) {
-        close();
-        return false;
-    }
-
-    Q_ASSERT(d->readSequenceStarted);
-    DWORD result = WaitForSingleObject(d->overlapped.hEvent, msecs == -1 ? INFINITE : msecs);
-    switch (result) {
-        case WAIT_OBJECT_0:
-            d->_q_notified();
-            // We just noticed that the pipe is gone.
-            if (d->pipeClosed && !bytesAvailable()) {
-                close();
-                return false;
-            }
-            return true;
-        case WAIT_TIMEOUT:
-            return false;
-    }
-
-    qWarning("QLocalSocket::waitForReadyRead WaitForSingleObject failed with error code %d.", int(GetLastError()));
-    return false;
-}
-
-bool QLocalSocket::waitForBytesWritten(int msecs)
-{
-    Q_D(const QLocalSocket);
-    if (!d->pipeWriter)
-        return false;
-
-    // Wait for the pipe writer to acknowledge that it has
-    // written. This will succeed if either the pipe writer has
-    // already written the data, or if it manages to write data
-    // within the given timeout.
-    return d->pipeWriter->waitForWrite(msecs);
-}
-
-QT_END_NAMESPACE
diff --git a/src/network/socket/qnativesocketengine_win.cpp b/src/network/socket/qnativesocketengine_win.cpp
deleted file mode 100644 (file)
index 631d9fb..0000000
+++ /dev/null
@@ -1,1445 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <winsock2.h>
-#include <ws2tcpip.h>
-
-#include "qnativesocketengine_p.h"
-
-#include <qabstracteventdispatcher.h>
-#include <qsocketnotifier.h>
-#include <qdebug.h>
-#include <qdatetime.h>
-#include <qnetworkinterface.h>
-
-//#define QNATIVESOCKETENGINE_DEBUG
-#if defined(QNATIVESOCKETENGINE_DEBUG)
-#   include <qstring.h>
-#   include <qbytearray.h>
-#endif
-
-QT_BEGIN_NAMESPACE
-
-#if defined(QNATIVESOCKETENGINE_DEBUG)
-
-void verboseWSErrorDebug(int r)
-{
-    switch (r) {
-        case WSANOTINITIALISED : qDebug("WSA error : WSANOTINITIALISED"); break;
-        case WSAEINTR: qDebug("WSA error : WSAEINTR"); break;
-        case WSAEBADF: qDebug("WSA error : WSAEBADF"); break;
-        case WSAEACCES: qDebug("WSA error : WSAEACCES"); break;
-        case WSAEFAULT: qDebug("WSA error : WSAEFAULT"); break;
-        case WSAEINVAL: qDebug("WSA error : WSAEINVAL"); break;
-        case WSAEMFILE: qDebug("WSA error : WSAEMFILE"); break;
-        case WSAEWOULDBLOCK: qDebug("WSA error : WSAEWOULDBLOCK"); break;
-        case WSAEINPROGRESS: qDebug("WSA error : WSAEINPROGRESS"); break;
-        case WSAEALREADY: qDebug("WSA error : WSAEALREADY"); break;
-        case WSAENOTSOCK: qDebug("WSA error : WSAENOTSOCK"); break;
-        case WSAEDESTADDRREQ: qDebug("WSA error : WSAEDESTADDRREQ"); break;
-        case WSAEMSGSIZE: qDebug("WSA error : WSAEMSGSIZE"); break;
-        case WSAEPROTOTYPE: qDebug("WSA error : WSAEPROTOTYPE"); break;
-        case WSAENOPROTOOPT: qDebug("WSA error : WSAENOPROTOOPT"); break;
-        case WSAEPROTONOSUPPORT: qDebug("WSA error : WSAEPROTONOSUPPORT"); break;
-        case WSAESOCKTNOSUPPORT: qDebug("WSA error : WSAESOCKTNOSUPPORT"); break;
-        case WSAEOPNOTSUPP: qDebug("WSA error : WSAEOPNOTSUPP"); break;
-        case WSAEPFNOSUPPORT: qDebug("WSA error : WSAEPFNOSUPPORT"); break;
-        case WSAEAFNOSUPPORT: qDebug("WSA error : WSAEAFNOSUPPORT"); break;
-        case WSAEADDRINUSE: qDebug("WSA error : WSAEADDRINUSE"); break;
-        case WSAEADDRNOTAVAIL: qDebug("WSA error : WSAEADDRNOTAVAIL"); break;
-        case WSAENETDOWN: qDebug("WSA error : WSAENETDOWN"); break;
-        case WSAENETUNREACH: qDebug("WSA error : WSAENETUNREACH"); break;
-        case WSAENETRESET: qDebug("WSA error : WSAENETRESET"); break;
-        case WSAECONNABORTED: qDebug("WSA error : WSAECONNABORTED"); break;
-        case WSAECONNRESET: qDebug("WSA error : WSAECONNRESET"); break;
-        case WSAENOBUFS: qDebug("WSA error : WSAENOBUFS"); break;
-        case WSAEISCONN: qDebug("WSA error : WSAEISCONN"); break;
-        case WSAENOTCONN: qDebug("WSA error : WSAENOTCONN"); break;
-        case WSAESHUTDOWN: qDebug("WSA error : WSAESHUTDOWN"); break;
-        case WSAETOOMANYREFS: qDebug("WSA error : WSAETOOMANYREFS"); break;
-        case WSAETIMEDOUT: qDebug("WSA error : WSAETIMEDOUT"); break;
-        case WSAECONNREFUSED: qDebug("WSA error : WSAECONNREFUSED"); break;
-        case WSAELOOP: qDebug("WSA error : WSAELOOP"); break;
-        case WSAENAMETOOLONG: qDebug("WSA error : WSAENAMETOOLONG"); break;
-        case WSAEHOSTDOWN: qDebug("WSA error : WSAEHOSTDOWN"); break;
-        case WSAEHOSTUNREACH: qDebug("WSA error : WSAEHOSTUNREACH"); break;
-        case WSAENOTEMPTY: qDebug("WSA error : WSAENOTEMPTY"); break;
-        case WSAEPROCLIM: qDebug("WSA error : WSAEPROCLIM"); break;
-        case WSAEUSERS: qDebug("WSA error : WSAEUSERS"); break;
-        case WSAEDQUOT: qDebug("WSA error : WSAEDQUOT"); break;
-        case WSAESTALE: qDebug("WSA error : WSAESTALE"); break;
-        case WSAEREMOTE: qDebug("WSA error : WSAEREMOTE"); break;
-        case WSAEDISCON: qDebug("WSA error : WSAEDISCON"); break;
-        default: qDebug("WSA error : Unknown"); break;
-    }
-    qErrnoWarning(r, "more details");
-}
-
-/*
-    Returns a human readable representation of the first \a len
-    characters in \a data.
-*/
-static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
-{
-    if (!data) return "(null)";
-    QByteArray out;
-    for (int i = 0; i < len; ++i) {
-        char c = data[i];
-        if (isprint(int(uchar(c)))) {
-            out += c;
-        } else switch (c) {
-        case '\n': out += "\\n"; break;
-        case '\r': out += "\\r"; break;
-        case '\t': out += "\\t"; break;
-        default:
-            QString tmp;
-            tmp.sprintf("\\%o", c);
-            out += tmp.toLatin1().constData();
-        }
-    }
-
-    if (len < maxLength)
-        out += "...";
-
-    return out;
-}
-
-
-#define WS_ERROR_DEBUG(x) verboseWSErrorDebug(x);
-
-#else
-
-#define WS_ERROR_DEBUG(x) Q_UNUSED(x)
-
-#endif
-
-#ifndef AF_INET6
-#define AF_INET6        23              /* Internetwork Version 6 */
-#endif
-
-#ifndef SO_EXCLUSIVEADDRUSE
-#define SO_EXCLUSIVEADDRUSE ((int)(~SO_REUSEADDR)) /* disallow local address reuse */
-#endif
-
-//###
-#define QT_SOCKLEN_T int
-#define QT_SOCKOPTLEN_T int
-
-
-/*
-    Extracts the port and address from a sockaddr, and stores them in
-    \a port and \a addr if they are non-null.
-*/
-static inline void qt_socket_getPortAndAddress(SOCKET socketDescriptor, const qt_sockaddr *sa, quint16 *port, QHostAddress *address)
-{
-#if !defined (QT_NO_IPV6)
-    if (sa->a.sa_family == AF_INET6) {
-        const qt_sockaddr_in6 *sa6 = &sa->a6;
-        Q_IPV6ADDR tmp;
-        for (int i = 0; i < 16; ++i)
-            tmp.c[i] = sa6->sin6_addr.qt_s6_addr[i];
-        if (address) {
-            QHostAddress a;
-            a.setAddress(tmp);
-            a.setScopeId(QString::number(sa6->sin6_scope_id));
-            *address = a;
-        }
-        if (port)
-           WSANtohs(socketDescriptor, sa6->sin6_port, port);
-    } else
-#endif
-    if (sa->a.sa_family == AF_INET) {
-        const sockaddr_in *sa4 = &sa->a4;
-        unsigned long addr;
-        WSANtohl(socketDescriptor, sa4->sin_addr.s_addr, &addr);
-        QHostAddress a;
-       a.setAddress(addr);
-       if (address)
-           *address = a;
-        if (port)
-           WSANtohs(socketDescriptor, sa4->sin_port, port);
-    }
-}
-
-
-/*! \internal
-
-    Sets the port and address to a sockaddr. Requires that sa point to the IPv6 struct if the address is IPv6.
-*/
-static inline void qt_socket_setPortAndAddress(SOCKET socketDescriptor, sockaddr_in * sockAddrIPv4, qt_sockaddr_in6 * sockAddrIPv6,
-                                               quint16 port, const QHostAddress & address, sockaddr ** sockAddrPtr, QT_SOCKLEN_T *sockAddrSize)
-{
-#if !defined(QT_NO_IPV6)
-    if (address.protocol() == QAbstractSocket::IPv6Protocol) {
-        memset(sockAddrIPv6, 0, sizeof(qt_sockaddr_in6));
-        sockAddrIPv6->sin6_family = AF_INET6;
-        sockAddrIPv6->sin6_scope_id = address.scopeId().toInt();
-        WSAHtons(socketDescriptor, port, &(sockAddrIPv6->sin6_port));
-        Q_IPV6ADDR tmp = address.toIPv6Address();
-        memcpy(&(sockAddrIPv6->sin6_addr.qt_s6_addr), &tmp, sizeof(tmp));
-        *sockAddrSize = sizeof(qt_sockaddr_in6);
-        *sockAddrPtr = (struct sockaddr *) sockAddrIPv6;
-    } else
-#endif
-    if (address.protocol() == QAbstractSocket::IPv4Protocol
-        || address.protocol() == QAbstractSocket::UnknownNetworkLayerProtocol) {
-        memset(sockAddrIPv4, 0, sizeof(sockaddr_in));
-        sockAddrIPv4->sin_family = AF_INET;
-        WSAHtons(socketDescriptor, port, &(sockAddrIPv4->sin_port));
-        WSAHtonl(socketDescriptor, address.toIPv4Address(), &(sockAddrIPv4->sin_addr.s_addr));
-        *sockAddrSize = sizeof(sockaddr_in);
-        *sockAddrPtr = (struct sockaddr *) sockAddrIPv4;
-    } else {
-        // unreachable
-    }
-}
-
-/*! \internal
-
-*/
-static inline QAbstractSocket::SocketType qt_socket_getType(int socketDescriptor)
-{
-    int value = 0;
-    QT_SOCKLEN_T valueSize = sizeof(value);
-    if (::getsockopt(socketDescriptor, SOL_SOCKET, SO_TYPE, (char *) &value, &valueSize) != 0) {
-        WS_ERROR_DEBUG(WSAGetLastError());
-    } else {
-        if (value == SOCK_STREAM)
-            return QAbstractSocket::TcpSocket;
-        else if (value == SOCK_DGRAM)
-            return QAbstractSocket::UdpSocket;
-    }
-    return QAbstractSocket::UnknownSocketType;
-}
-
-/*! \internal
-
-*/
-static inline int qt_socket_getMaxMsgSize(int socketDescriptor)
-{
-    int value = 0;
-    QT_SOCKLEN_T valueSize = sizeof(value);
-    if (::getsockopt(socketDescriptor, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *) &value, &valueSize) != 0) {
-        WS_ERROR_DEBUG(WSAGetLastError());
-    }
-    return value;
-}
-
-QWindowsSockInit::QWindowsSockInit()
-:   version(0)
-{
-    //### should we try for 2.2 on all platforms ??
-    WSAData wsadata;
-
-    // IPv6 requires Winsock v2.0 or better.
-    if (WSAStartup(MAKEWORD(2,0), &wsadata) != 0) {
-       qWarning("QTcpSocketAPI: WinSock v2.0 initialization failed.");
-    } else {
-        version = 0x20;
-    }
-}
-
-QWindowsSockInit::~QWindowsSockInit()
-{
-    WSACleanup();
-}
-
-// MS Transport Provider IOCTL to control
-// reporting PORT_UNREACHABLE messages
-// on UDP sockets via recv/WSARecv/etc.
-// Path TRUE in input buffer to enable (default if supported),
-// FALSE to disable.
-#ifndef SIO_UDP_CONNRESET
-#  ifndef IOC_VENDOR
-#    define IOC_VENDOR 0x18000000
-#  endif
-#  ifndef _WSAIOW
-#    define _WSAIOW(x,y) (IOC_IN|(x)|(y))
-#  endif
-#  define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR,12)
-#endif
-
-bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol socketProtocol)
-{
-
-    //### no ip6 support on winsocket 1.1 but we will try not to use this !!!!!!!!!!!!1
-    /*
-    if (winsockVersion < 0x20 && socketProtocol == QAbstractSocket::IPv6Protocol) {
-        //### no ip6 support
-        return -1;
-    }
-    */
-
-    int protocol = (socketProtocol == QAbstractSocket::IPv6Protocol) ? AF_INET6 : AF_INET;
-    int type = (socketType == QAbstractSocket::UdpSocket) ? SOCK_DGRAM : SOCK_STREAM;
-    // MSDN KB179942 states that on winnt 4 WSA_FLAG_OVERLAPPED is needed if socket is to be non blocking
-    // and recomends alwasy doing it for cross windows version comapablity.
-    SOCKET socket = ::WSASocket(protocol, type, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
-
-    if (socket == INVALID_SOCKET) {
-        int err = WSAGetLastError();
-        WS_ERROR_DEBUG(err);
-        switch (err) {
-        case WSANOTINITIALISED:
-            //###
-            break;
-        case WSAEAFNOSUPPORT:
-        case WSAESOCKTNOSUPPORT:
-        case WSAEPROTOTYPE:
-        case WSAEINVAL:
-            setError(QAbstractSocket::UnsupportedSocketOperationError, ProtocolUnsupportedErrorString);
-            break;
-        case WSAEMFILE:
-        case WSAENOBUFS:
-            setError(QAbstractSocket::SocketResourceError, ResourceErrorString);
-            break;
-        default:
-            break;
-        }
-
-        return false;
-    }
-
-#if !defined(Q_OS_WINCE)
-    if (socketType == QAbstractSocket::UdpSocket) {
-        // enable new behavior using
-        // SIO_UDP_CONNRESET
-        DWORD dwBytesReturned = 0;
-        int bNewBehavior = 1;
-        if (::WSAIoctl(socket, SIO_UDP_CONNRESET, &bNewBehavior, sizeof(bNewBehavior),
-                       NULL, 0, &dwBytesReturned, NULL, NULL) == SOCKET_ERROR) {
-            // not to worry isBogusUdpReadNotification() should handle this otherwise
-            int err = WSAGetLastError();
-            WS_ERROR_DEBUG(err);
-        }
-    }
-#endif
-
-    socketDescriptor = socket;
-    return true;
-
-}
-
-/*! \internal
-
-    Returns the value of the socket option \a opt.
-*/
-int QNativeSocketEnginePrivate::option(QNativeSocketEngine::SocketOption opt) const
-{
-    Q_Q(const QNativeSocketEngine);
-    if (!q->isValid())
-        return -1;
-
-    int n = -1;
-    int level = SOL_SOCKET; // default
-
-    switch (opt) {
-    case QNativeSocketEngine::ReceiveBufferSocketOption:
-        n = SO_RCVBUF;
-        break;
-    case QNativeSocketEngine::SendBufferSocketOption:
-        n = SO_SNDBUF;
-        break;
-    case QNativeSocketEngine::BroadcastSocketOption:
-        n = SO_BROADCAST;
-        break;
-    case QNativeSocketEngine::NonBlockingSocketOption: {
-        unsigned long buf = 0;
-        if (WSAIoctl(socketDescriptor, FIONBIO, 0,0, &buf, sizeof(buf), 0,0,0) == 0)
-            return buf;
-        else
-            return -1;
-        break;
-    }
-    case QNativeSocketEngine::AddressReusable:
-        n = SO_REUSEADDR;
-        break;
-    case QNativeSocketEngine::BindExclusively:
-        n = SO_EXCLUSIVEADDRUSE;
-        break;
-    case QNativeSocketEngine::ReceiveOutOfBandData:
-        n = SO_OOBINLINE;
-        break;
-    case QNativeSocketEngine::LowDelayOption:
-        level = IPPROTO_TCP;
-        n = TCP_NODELAY;
-        break;
-    case QNativeSocketEngine::KeepAliveOption:
-        n = SO_KEEPALIVE;
-        break;
-    case QNativeSocketEngine::MulticastTtlOption:
-#ifndef QT_NO_IPV6
-        if (socketProtocol == QAbstractSocket::IPv6Protocol) {
-            level = IPPROTO_IPV6;
-            n = IPV6_MULTICAST_HOPS;
-        } else
-#endif
-        {
-            level = IPPROTO_IP;
-            n = IP_MULTICAST_TTL;
-        }
-        break;
-    case QNativeSocketEngine::MulticastLoopbackOption:
-#ifndef QT_NO_IPV6
-        if (socketProtocol == QAbstractSocket::IPv6Protocol) {
-            level = IPPROTO_IPV6;
-            n = IPV6_MULTICAST_LOOP;
-        } else
-#endif
-        {
-            level = IPPROTO_IP;
-            n = IP_MULTICAST_LOOP;
-        }
-        break;
-    }
-
-#if Q_BYTE_ORDER != Q_LITTLE_ENDIAN
-#error code assumes windows is little endian
-#endif
-    int v = 0; //note: windows doesn't write to all bytes if the option type is smaller than int
-    QT_SOCKOPTLEN_T len = sizeof(v);
-    if (getsockopt(socketDescriptor, level, n, (char *) &v, &len) == 0)
-        return v;
-    WS_ERROR_DEBUG(WSAGetLastError());
-    return -1;
-}
-
-
-/*! \internal
-    Sets the socket option \a opt to \a v.
-*/
-bool QNativeSocketEnginePrivate::setOption(QNativeSocketEngine::SocketOption opt, int v)
-{
-    Q_Q(const QNativeSocketEngine);
-    if (!q->isValid())
-        return false;
-
-    int n = 0;
-    int level = SOL_SOCKET; // default
-
-    switch (opt) {
-    case QNativeSocketEngine::ReceiveBufferSocketOption:
-        n = SO_RCVBUF;
-        break;
-    case QNativeSocketEngine::SendBufferSocketOption:
-        n = SO_SNDBUF;
-        break;
-    case QNativeSocketEngine::BroadcastSocketOption:
-        n = SO_BROADCAST;
-        break;
-    case QNativeSocketEngine::NonBlockingSocketOption:
-        {
-        unsigned long buf = v;
-        unsigned long outBuf;
-        DWORD sizeWritten = 0;
-        if (::WSAIoctl(socketDescriptor, FIONBIO, &buf, sizeof(unsigned long), &outBuf, sizeof(unsigned long), &sizeWritten, 0,0) == SOCKET_ERROR) {
-            WS_ERROR_DEBUG(WSAGetLastError());
-            return false;
-        }
-        return true;
-        break;
-        }
-    case QNativeSocketEngine::AddressReusable:
-        n = SO_REUSEADDR;
-        break;
-    case QNativeSocketEngine::BindExclusively:
-        n = SO_EXCLUSIVEADDRUSE;
-        break;
-    case QNativeSocketEngine::ReceiveOutOfBandData:
-        n = SO_OOBINLINE;
-        break;
-    case QNativeSocketEngine::LowDelayOption:
-        level = IPPROTO_TCP;
-        n = TCP_NODELAY;
-        break;
-    case QNativeSocketEngine::KeepAliveOption:
-        n = SO_KEEPALIVE;
-        break;
-    case QNativeSocketEngine::MulticastTtlOption:
-#ifndef QT_NO_IPV6
-        if (socketProtocol == QAbstractSocket::IPv6Protocol) {
-            level = IPPROTO_IPV6;
-            n = IPV6_MULTICAST_HOPS;
-        } else
-#endif
-        {
-            level = IPPROTO_IP;
-            n = IP_MULTICAST_TTL;
-        }
-        break;
-    case QNativeSocketEngine::MulticastLoopbackOption:
-#ifndef QT_NO_IPV6
-        if (socketProtocol == QAbstractSocket::IPv6Protocol) {
-            level = IPPROTO_IPV6;
-            n = IPV6_MULTICAST_LOOP;
-        } else
-#endif
-        {
-            level = IPPROTO_IP;
-            n = IP_MULTICAST_LOOP;
-        }
-        break;
-    }
-
-    if (::setsockopt(socketDescriptor, level, n, (char*)&v, sizeof(v)) != 0) {
-        WS_ERROR_DEBUG(WSAGetLastError());
-        return false;
-    }
-    return true;
-}
-
-/*!
-    Fetches information about both ends of the connection: whatever is
-    available.
-*/
-bool QNativeSocketEnginePrivate::fetchConnectionParameters()
-{
-    localPort = 0;
-    localAddress.clear();
-    peerPort = 0;
-    peerAddress.clear();
-
-    if (socketDescriptor == -1)
-       return false;
-
-    qt_sockaddr sa;
-    QT_SOCKLEN_T sockAddrSize = sizeof(sa);
-
-    // Determine local address
-    memset(&sa, 0, sizeof(sa));
-    if (::getsockname(socketDescriptor, &sa.a, &sockAddrSize) == 0) {
-        qt_socket_getPortAndAddress(socketDescriptor, &sa, &localPort, &localAddress);
-        // Determine protocol family
-        switch (sa.a.sa_family) {
-        case AF_INET:
-            socketProtocol = QAbstractSocket::IPv4Protocol;
-            break;
-#if !defined (QT_NO_IPV6)
-        case AF_INET6:
-            socketProtocol = QAbstractSocket::IPv6Protocol;
-            break;
-#endif
-        default:
-            socketProtocol = QAbstractSocket::UnknownNetworkLayerProtocol;
-            break;
-        }
-    } else {
-        int err = WSAGetLastError();
-        WS_ERROR_DEBUG(err);
-        if (err == WSAENOTSOCK) {
-            setError(QAbstractSocket::UnsupportedSocketOperationError,
-                InvalidSocketErrorString);
-            return false;
-        }
-    }
-
-    memset(&sa, 0, sizeof(sa));
-    if (::getpeername(socketDescriptor, &sa.a, &sockAddrSize) == 0) {
-        qt_socket_getPortAndAddress(socketDescriptor, &sa, &peerPort, &peerAddress);
-    } else {
-        WS_ERROR_DEBUG(WSAGetLastError());
-    }
-
-    socketType = qt_socket_getType(socketDescriptor);
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    QString socketProtocolStr = "UnknownProtocol";
-    if (socketProtocol == QAbstractSocket::IPv4Protocol) socketProtocolStr = "IPv4Protocol";
-    else if (socketProtocol == QAbstractSocket::IPv6Protocol) socketProtocolStr = "IPv6Protocol";
-
-    QString socketTypeStr = "UnknownSocketType";
-    if (socketType == QAbstractSocket::TcpSocket) socketTypeStr = "TcpSocket";
-    else if (socketType == QAbstractSocket::UdpSocket) socketTypeStr = "UdpSocket";
-
-    qDebug("QNativeSocketEnginePrivate::fetchConnectionParameters() localAddress == %s, localPort = %i, peerAddress == %s, peerPort = %i, socketProtocol == %s, socketType == %s", localAddress.toString().toLatin1().constData(), localPort, peerAddress.toString().toLatin1().constData(), peerPort, socketProtocolStr.toLatin1().constData(), socketTypeStr.toLatin1().constData());
-#endif
-
-    return true;
-}
-
-
-bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quint16 port)
-{
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeConnect() to %s :: %i", address.toString().toLatin1().constData(), port);
-#endif
-
-    struct sockaddr_in sockAddrIPv4;
-    qt_sockaddr_in6 sockAddrIPv6;
-    struct sockaddr *sockAddrPtr = 0;
-    QT_SOCKLEN_T sockAddrSize = 0;
-
-    qt_socket_setPortAndAddress(socketDescriptor, &sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
-
-    forever {
-        int connectResult = ::WSAConnect(socketDescriptor, sockAddrPtr, sockAddrSize, 0,0,0,0);
-        if (connectResult == SOCKET_ERROR) {
-            int err = WSAGetLastError();
-            WS_ERROR_DEBUG(err);
-
-            switch (err) {
-            case WSANOTINITIALISED:
-                //###
-                break;
-            case WSAEISCONN:
-                socketState = QAbstractSocket::ConnectedState;
-                break;
-            case WSAEWOULDBLOCK: {
-                // If WSAConnect returns WSAEWOULDBLOCK on the second
-                // connection attempt, we have to check SO_ERROR's
-                // value to detect ECONNREFUSED. If we don't get
-                // ECONNREFUSED, we'll have to treat it as an
-                // unfinished operation.
-                int value = 0;
-                QT_SOCKLEN_T valueSize = sizeof(value);
-                if (::getsockopt(socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) {
-                    if (value == WSAECONNREFUSED) {
-                        setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
-                        socketState = QAbstractSocket::UnconnectedState;
-                        break;
-                    }
-                    if (value == WSAETIMEDOUT) {
-                        setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
-                        socketState = QAbstractSocket::UnconnectedState;
-                        break;
-                    }
-                    if (value == WSAEHOSTUNREACH) {
-                        setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
-                        socketState = QAbstractSocket::UnconnectedState;
-                        break;
-                    }
-                    if (value == WSAEADDRNOTAVAIL) {
-                        setError(QAbstractSocket::NetworkError, AddressNotAvailableErrorString);
-                        socketState = QAbstractSocket::UnconnectedState;
-                        break;
-                    }
-                }
-                // fall through
-            }
-            case WSAEINPROGRESS:
-                setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
-                socketState = QAbstractSocket::ConnectingState;
-                break;
-            case WSAEADDRINUSE:
-                setError(QAbstractSocket::NetworkError, AddressInuseErrorString);
-                break;
-            case WSAECONNREFUSED:
-                setError(QAbstractSocket::ConnectionRefusedError, ConnectionRefusedErrorString);
-                socketState = QAbstractSocket::UnconnectedState;
-                break;
-            case WSAETIMEDOUT:
-                setError(QAbstractSocket::NetworkError, ConnectionTimeOutErrorString);
-                break;
-            case WSAEACCES:
-                setError(QAbstractSocket::SocketAccessError, AccessErrorString);
-                socketState = QAbstractSocket::UnconnectedState;
-                break;
-            case WSAEHOSTUNREACH:
-                setError(QAbstractSocket::NetworkError, HostUnreachableErrorString);
-                socketState = QAbstractSocket::UnconnectedState;
-                break;
-            case WSAENETUNREACH:
-                setError(QAbstractSocket::NetworkError, NetworkUnreachableErrorString);
-                socketState = QAbstractSocket::UnconnectedState;
-                break;
-            case WSAEINVAL:
-            case WSAEALREADY:
-                setError(QAbstractSocket::UnfinishedSocketOperationError, InvalidSocketErrorString);
-                break;
-            default:
-                break;
-            }
-            if (socketState != QAbstractSocket::ConnectedState) {
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-                qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == false (%s)",
-                        address.toString().toLatin1().constData(), port,
-                        socketState == QAbstractSocket::ConnectingState
-                        ? "Connection in progress" : socketErrorString.toLatin1().constData());
-#endif
-                return false;
-            }
-        }
-        break;
-    }
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeConnect(%s, %i) == true",
-           address.toString().toLatin1().constData(), port);
-#endif
-
-    socketState = QAbstractSocket::ConnectedState;
-    return true;
-}
-
-
-bool QNativeSocketEnginePrivate::nativeBind(const QHostAddress &a, quint16 port)
-{
-    QHostAddress address = a;
-    switch (address.protocol()) {
-    case QAbstractSocket::IPv6Protocol:
-        if (address.toIPv6Address()[0] == 0xff) {
-            // binding to a multicast address
-            address = QHostAddress(QHostAddress::AnyIPv6);
-        }
-        break;
-    case QAbstractSocket::IPv4Protocol:
-        if ((address.toIPv4Address() & 0xffff0000) == 0xefff0000) {
-            // binding to a multicast address
-            address = QHostAddress(QHostAddress::Any);
-        }
-        break;
-    default:
-        break;
-    }
-
-    struct sockaddr_in sockAddrIPv4;
-    qt_sockaddr_in6 sockAddrIPv6;
-    struct sockaddr *sockAddrPtr = 0;
-    QT_SOCKLEN_T sockAddrSize = 0;
-
-    qt_socket_setPortAndAddress(socketDescriptor, &sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
-
-
-    int bindResult = ::bind(socketDescriptor, sockAddrPtr, sockAddrSize);
-    if (bindResult == SOCKET_ERROR) {
-        int err = WSAGetLastError();
-        WS_ERROR_DEBUG(err);
-        switch (err) {
-        case WSANOTINITIALISED:
-            //###
-            break;
-        case WSAEADDRINUSE:
-        case WSAEINVAL:
-            setError(QAbstractSocket::AddressInUseError, AddressInuseErrorString);
-            break;
-        case WSAEACCES:
-            setError(QAbstractSocket::SocketAccessError, AddressProtectedErrorString);
-            break;
-        case WSAEADDRNOTAVAIL:
-            setError(QAbstractSocket::SocketAddressNotAvailableError, AddressNotAvailableErrorString);
-            break;
-        default:
-            break;
-        }
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-        qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == false (%s)",
-               address.toString().toLatin1().constData(), port, socketErrorString.toLatin1().constData());
-#endif
-
-        return false;
-    }
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeBind(%s, %i) == true",
-           address.toString().toLatin1().constData(), port);
-#endif
-    socketState = QAbstractSocket::BoundState;
-    return true;
-}
-
-
-bool QNativeSocketEnginePrivate::nativeListen(int backlog)
-{
-    if (::listen(socketDescriptor, backlog) == SOCKET_ERROR) {
-        int err = WSAGetLastError();
-        WS_ERROR_DEBUG(err);
-        switch (err) {
-        case WSANOTINITIALISED:
-            //###
-            break;
-        case WSAEADDRINUSE:
-            setError(QAbstractSocket::AddressInUseError,
-                     PortInuseErrorString);
-            break;
-        default:
-            break;
-        }
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-        qDebug("QNativeSocketEnginePrivate::nativeListen(%i) == false (%s)",
-               backlog, socketErrorString.toLatin1().constData());
-#endif
-        return false;
-    }
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeListen(%i) == true", backlog);
-#endif
-
-    socketState = QAbstractSocket::ListeningState;
-    return true;
-}
-
-int QNativeSocketEnginePrivate::nativeAccept()
-{
-    int acceptedDescriptor = WSAAccept(socketDescriptor, 0,0,0,0);
-       if (acceptedDescriptor != -1 && QAbstractEventDispatcher::instance()) {
-               // Because of WSAAsyncSelect() WSAAccept returns a non blocking socket
-               // with the same attributes as the listening socket including the current
-               // WSAAsyncSelect(). To be able to change the socket to blocking mode the
-               // WSAAsyncSelect() call must be cancled.
-               QSocketNotifier n(acceptedDescriptor, QSocketNotifier::Read);
-               n.setEnabled(true);
-               n.setEnabled(false);
-       }
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeAccept() == %i", acceptedDescriptor);
-#endif
-    return acceptedDescriptor;
-}
-
-static bool multicastMembershipHelper(QNativeSocketEnginePrivate *d,
-                                      int how6,
-                                      int how4,
-                                      const QHostAddress &groupAddress,
-                                      const QNetworkInterface &iface)
-{
-    int level = 0;
-    int sockOpt = 0;
-    char *sockArg;
-    int sockArgSize;
-
-    struct ip_mreq mreq4;
-#ifndef QT_NO_IPV6
-    struct ipv6_mreq mreq6;
-
-    if (groupAddress.protocol() == QAbstractSocket::IPv6Protocol) {
-        level = IPPROTO_IPV6;
-        sockOpt = how6;
-        sockArg = reinterpret_cast<char *>(&mreq6);
-        sockArgSize = sizeof(mreq6);
-        memset(&mreq6, 0, sizeof(mreq6));
-        Q_IPV6ADDR ip6 = groupAddress.toIPv6Address();
-        memcpy(&mreq6.ipv6mr_multiaddr, &ip6, sizeof(ip6));
-        mreq6.ipv6mr_interface = iface.index();
-    } else
-#endif
-    if (groupAddress.protocol() == QAbstractSocket::IPv4Protocol) {
-        level = IPPROTO_IP;
-        sockOpt = how4;
-        sockArg = reinterpret_cast<char *>(&mreq4);
-        sockArgSize = sizeof(mreq4);
-        memset(&mreq4, 0, sizeof(mreq4));
-        mreq4.imr_multiaddr.s_addr = htonl(groupAddress.toIPv4Address());
-
-        if (iface.isValid()) {
-            QList<QNetworkAddressEntry> addressEntries = iface.addressEntries();
-            if (!addressEntries.isEmpty()) {
-                QHostAddress firstIP = addressEntries.first().ip();
-                mreq4.imr_interface.s_addr = htonl(firstIP.toIPv4Address());
-            } else {
-                d->setError(QAbstractSocket::NetworkError,
-                            QNativeSocketEnginePrivate::NetworkUnreachableErrorString);
-                return false;
-            }
-        } else {
-            mreq4.imr_interface.s_addr = INADDR_ANY;
-        }
-    } else {
-        // unreachable
-        d->setError(QAbstractSocket::UnsupportedSocketOperationError,
-                    QNativeSocketEnginePrivate::ProtocolUnsupportedErrorString);
-        return false;
-    }
-
-    int res = setsockopt(d->socketDescriptor, level, sockOpt, sockArg, sockArgSize);
-    if (res == -1) {
-        d->setError(QAbstractSocket::UnsupportedSocketOperationError,
-                    QNativeSocketEnginePrivate::OperationUnsupportedErrorString);
-        return false;
-    }
-    return true;
-}
-
-bool QNativeSocketEnginePrivate::nativeJoinMulticastGroup(const QHostAddress &groupAddress,
-                                                          const QNetworkInterface &iface)
-{
-    return multicastMembershipHelper(this,
-#ifndef QT_NO_IPV6
-                                     IPV6_JOIN_GROUP,
-#else
-                                     0,
-#endif
-                                     IP_ADD_MEMBERSHIP,
-                                     groupAddress,
-                                     iface);
-}
-
-bool QNativeSocketEnginePrivate::nativeLeaveMulticastGroup(const QHostAddress &groupAddress,
-                                                           const QNetworkInterface &iface)
-{
-    return multicastMembershipHelper(this,
-#ifndef QT_NO_IPV6
-                                     IPV6_LEAVE_GROUP,
-#else
-                                     0,
-#endif
-                                     IP_DROP_MEMBERSHIP,
-                                     groupAddress,
-                                     iface);
-}
-
-QNetworkInterface QNativeSocketEnginePrivate::nativeMulticastInterface() const
-{
-#ifndef QT_NO_IPV6
-    if (socketProtocol == QAbstractSocket::IPv6Protocol) {
-        uint v;
-        QT_SOCKOPTLEN_T sizeofv = sizeof(v);
-        if (::getsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *) &v, &sizeofv) == -1)
-            return QNetworkInterface();
-        return QNetworkInterface::interfaceFromIndex(v);
-    }
-#endif
-
-    struct in_addr v;
-    v.s_addr = 0;
-    QT_SOCKOPTLEN_T sizeofv = sizeof(v);
-    if (::getsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_IF, (char *) &v, &sizeofv) == -1)
-        return QNetworkInterface();
-    if (v.s_addr != 0 && sizeofv >= QT_SOCKOPTLEN_T(sizeof(v))) {
-        QHostAddress ipv4(ntohl(v.s_addr));
-        QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
-        for (int i = 0; i < ifaces.count(); ++i) {
-            const QNetworkInterface &iface = ifaces.at(i);
-            if (!(iface.flags() & QNetworkInterface::CanMulticast))
-                continue;
-            QList<QNetworkAddressEntry> entries = iface.addressEntries();
-            for (int j = 0; j < entries.count(); ++j) {
-                const QNetworkAddressEntry &entry = entries.at(j);
-                if (entry.ip() == ipv4)
-                    return iface;
-            }
-        }
-    }
-    return QNetworkInterface();
-}
-
-bool QNativeSocketEnginePrivate::nativeSetMulticastInterface(const QNetworkInterface &iface)
-{
-#ifndef QT_NO_IPV6
-    if (socketProtocol == QAbstractSocket::IPv6Protocol) {
-        uint v = iface.isValid() ? iface.index() : 0;
-        return (::setsockopt(socketDescriptor, IPPROTO_IPV6, IPV6_MULTICAST_IF, (char *) &v, sizeof(v)) != -1);
-    }
-#endif
-
-    struct in_addr v;
-    if (iface.isValid()) {
-        QList<QNetworkAddressEntry> entries = iface.addressEntries();
-        for (int i = 0; i < entries.count(); ++i) {
-            const QNetworkAddressEntry &entry = entries.at(i);
-            const QHostAddress &ip = entry.ip();
-            if (ip.protocol() == QAbstractSocket::IPv4Protocol) {
-                v.s_addr = htonl(ip.toIPv4Address());
-                int r = ::setsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_IF, (char *) &v, sizeof(v));
-                if (r != -1)
-                    return true;
-            }
-        }
-        return false;
-    }
-
-    v.s_addr = INADDR_ANY;
-    return (::setsockopt(socketDescriptor, IPPROTO_IP, IP_MULTICAST_IF, (char *) &v, sizeof(v)) != -1);
-}
-
-qint64 QNativeSocketEnginePrivate::nativeBytesAvailable() const
-{
-    unsigned long  nbytes = 0;
-    unsigned long dummy = 0;
-    DWORD sizeWritten = 0;
-    if (::WSAIoctl(socketDescriptor, FIONREAD, &dummy, sizeof(dummy), &nbytes, sizeof(nbytes), &sizeWritten, 0,0) == SOCKET_ERROR) {
-        WS_ERROR_DEBUG(WSAGetLastError());
-        return -1;
-    }
-
-    // ioctlsocket sometimes reports 1 byte available for datagrams
-    // while the following recvfrom returns -1 and claims connection
-    // was reset (udp is connectionless). so we peek one byte to
-    // catch this case and return 0 bytes available if recvfrom
-    // fails.
-    if (nbytes == 1 && socketType == QAbstractSocket::UdpSocket) {
-        char c;
-        WSABUF buf;
-        buf.buf = &c;
-        buf.len = sizeof(c);
-        DWORD flags = MSG_PEEK;
-        if (::WSARecvFrom(socketDescriptor, &buf, 1, 0, &flags, 0,0,0,0) == SOCKET_ERROR)
-            return 0;
-    }
-    return nbytes;
-}
-
-
-bool QNativeSocketEnginePrivate::nativeHasPendingDatagrams() const
-{
-#if !defined(Q_OS_WINCE)
-    // Create a sockaddr struct and reset its port number.
-    qt_sockaddr storage;
-    QT_SOCKLEN_T storageSize = sizeof(storage);
-    memset(&storage, 0, storageSize);
-
-    bool result = false;
-
-    // Peek 0 bytes into the next message. The size of the message may
-    // well be 0, so we check if there was a sender.
-    char c;
-    WSABUF buf;
-    buf.buf = &c;
-    buf.len = sizeof(c);
-    DWORD available = 0;
-    DWORD flags = MSG_PEEK;
-    int ret = ::WSARecvFrom(socketDescriptor, &buf, 1, &available, &flags, &storage.a, &storageSize,0,0);
-    int err = WSAGetLastError();
-    if (ret == SOCKET_ERROR && err !=  WSAEMSGSIZE) {
-        WS_ERROR_DEBUG(err);
-        if (err == WSAECONNRESET || err == WSAENETRESET) {
-            // Discard error message to prevent QAbstractSocket from
-            // getting this message repeatedly after reenabling the
-            // notifiers.
-            flags = 0;
-            ::WSARecvFrom(socketDescriptor, &buf, 1, &available, &flags,
-                          &storage.a, &storageSize, 0, 0);
-        }
-    } else {
-        // If there's no error, or if our buffer was too small, there must be
-        // a pending datagram.
-        result = true;
-    }
-
-#else // Q_OS_WINCE
-    bool result = false;
-    fd_set readS;
-    FD_ZERO(&readS);
-    FD_SET((SOCKET)socketDescriptor, &readS);
-    timeval timeout;
-    timeout.tv_sec = 0;
-    timeout.tv_usec = 5000;
-    int available = ::select(1, &readS, 0, 0, &timeout);
-    result = available > 0 ? true : false;
-#endif
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeHasPendingDatagrams() == %s",
-           result ? "true" : "false");
-#endif
-    return result;
-}
-
-
-qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const
-{
-    qint64 ret = -1;
-#if !defined(Q_OS_WINCE)
-    int recvResult = 0;
-    DWORD flags;
-    DWORD bufferCount = 5;
-    WSABUF * buf = 0;
-    for (;;) {
-        // the data written to udpMessagePeekBuffer is discarded, so
-        // this function is still reentrant although it might not look
-        // so.
-        static char udpMessagePeekBuffer[8192];
-
-        buf = new WSABUF[bufferCount];
-        for (DWORD i=0; i<bufferCount; i++) {
-           buf[i].buf = udpMessagePeekBuffer;
-           buf[i].len = sizeof(udpMessagePeekBuffer);
-        }
-        flags = MSG_PEEK;
-        DWORD bytesRead = 0;
-        recvResult = ::WSARecv(socketDescriptor, buf, bufferCount, &bytesRead, &flags, 0,0);
-        int err = WSAGetLastError();
-        if (recvResult != SOCKET_ERROR) {
-            ret = qint64(bytesRead);
-            break;
-        } else if (recvResult == SOCKET_ERROR && err == WSAEMSGSIZE) {
-           bufferCount += 5;
-           delete[] buf;
-        } else if (recvResult == SOCKET_ERROR) {
-            WS_ERROR_DEBUG(err);
-            ret = -1;
-            break;
-        }
-    }
-
-    if (buf)
-        delete[] buf;
-
-#else // Q_OS_WINCE
-    DWORD size = -1;
-    DWORD bytesReturned;
-    int ioResult = WSAIoctl(socketDescriptor, FIONREAD, 0,0, &size, sizeof(size), &bytesReturned, 0, 0);
-    if (ioResult == SOCKET_ERROR) {
-        int err = WSAGetLastError();
-        WS_ERROR_DEBUG(err);
-    } else {
-        ret = qint64(size);
-    }
-#endif
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativePendingDatagramSize() == %li", ret);
-#endif
-
-    return ret;
-}
-
-
-qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxLength,
-                                                      QHostAddress *address, quint16 *port)
-{
-    qint64 ret = 0;
-
-    qt_sockaddr aa;
-    memset(&aa, 0, sizeof(aa));
-    QT_SOCKLEN_T sz;
-    sz = sizeof(aa);
-
-    WSABUF buf;
-    buf.buf = data;
-    buf.len = maxLength;
-#if !defined(Q_OS_WINCE)
-    buf.buf = data;
-    buf.len = maxLength;
-#else
-    char tmpChar;
-    buf.buf = data ? data : &tmpChar;
-    buf.len = maxLength;
-#endif
-
-    DWORD flags = 0;
-    DWORD bytesRead = 0;
-    int wsaRet = ::WSARecvFrom(socketDescriptor, &buf, 1, &bytesRead, &flags, &aa.a, &sz,0,0);
-    if (wsaRet == SOCKET_ERROR) {
-        int err = WSAGetLastError();
-        if (err == WSAEMSGSIZE) {
-            // it is ok the buffer was to small if bytesRead is larger than
-            // maxLength then assume bytes read is really maxLenth
-            ret = qint64(bytesRead) > maxLength ? maxLength : qint64(bytesRead);
-        } else {
-            WS_ERROR_DEBUG(err);
-            setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString);
-            ret = -1;
-        }
-    } else {
-        ret = qint64(bytesRead);
-    }
-
-    qt_socket_getPortAndAddress(socketDescriptor, &aa, port, address);
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeReceiveDatagram(%p \"%s\", %li, %s, %i) == %li",
-           data, qt_prettyDebug(data, qMin<qint64>(ret, 16), ret).data(), maxLength,
-           address ? address->toString().toLatin1().constData() : "(nil)",
-           port ? *port : 0, ret);
-#endif
-
-    return ret;
-}
-
-
-qint64 QNativeSocketEnginePrivate::nativeSendDatagram(const char *data, qint64 len,
-                                                   const QHostAddress &address, quint16 port)
-{
-    qint64 ret = -1;
-    struct sockaddr_in sockAddrIPv4;
-    qt_sockaddr_in6 sockAddrIPv6;
-    struct sockaddr *sockAddrPtr = 0;
-    QT_SOCKLEN_T sockAddrSize = 0;
-
-    qt_socket_setPortAndAddress(socketDescriptor, &sockAddrIPv4, &sockAddrIPv6, port, address, &sockAddrPtr, &sockAddrSize);
-
-    WSABUF buf;
-#if !defined(Q_OS_WINCE)
-    buf.buf = len ? (char*)data : 0;
-#else
-    char tmp;
-    buf.buf = len ? (char*)data : &tmp;
-#endif
-    buf.len = len;
-    DWORD flags = 0;
-    DWORD bytesSent = 0;
-    if (::WSASendTo(socketDescriptor, &buf, 1, &bytesSent, flags, sockAddrPtr, sockAddrSize, 0,0) ==  SOCKET_ERROR) {
-        int err = WSAGetLastError();
-        WS_ERROR_DEBUG(err);
-        switch (err) {
-        case WSAEMSGSIZE:
-            setError(QAbstractSocket::DatagramTooLargeError, DatagramTooLargeErrorString);
-            break;
-        default:
-            setError(QAbstractSocket::NetworkError, SendDatagramErrorString);
-            break;
-        }
-        ret = -1;
-    } else {
-        ret = qint64(bytesSent);
-    }
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeSendDatagram(%p \"%s\", %li, \"%s\", %i) == %li", data,
-           qt_prettyDebug(data, qMin<qint64>(len, 16), len).data(), 0, address.toString().toLatin1().constData(),
-           port, ret);
-#endif
-
-    return ret;
-}
-
-
-qint64 QNativeSocketEnginePrivate::nativeWrite(const char *data, qint64 len)
-{
-    Q_Q(QNativeSocketEngine);
-    qint64 ret = 0;
-    qint64 bytesToSend = len;
-
-    for (;;) {
-        WSABUF buf;
-        buf.buf = (char*)data + ret;
-        buf.len = bytesToSend;
-        DWORD flags = 0;
-        DWORD bytesWritten = 0;
-
-        int socketRet = ::WSASend(socketDescriptor, &buf, 1, &bytesWritten, flags, 0,0);
-
-        ret += qint64(bytesWritten);
-
-        int err;
-        if (socketRet != SOCKET_ERROR) {
-            if (ret == len)
-                break;
-            else
-                continue;
-        } else if ((err = WSAGetLastError()) == WSAEWOULDBLOCK) {
-            break;
-        } else if (err == WSAENOBUFS) {
-            // this function used to not send more than 49152 per call to WSASendTo
-            // to avoid getting a WSAENOBUFS. However this is a performance regression
-            // and we think it only appears with old windows versions. We now handle the
-            // WSAENOBUFS and hope it never appears anyway.
-            // just go on, the next loop run we will try a smaller number
-        } else {
-            WS_ERROR_DEBUG(err);
-            switch (err) {
-            case WSAECONNRESET:
-            case WSAECONNABORTED:
-                ret = -1;
-                setError(QAbstractSocket::NetworkError, WriteErrorString);
-                q->close();
-                break;
-            default:
-                break;
-            }
-            break;
-        }
-
-        // for next send:
-        bytesToSend = qMin<qint64>(49152, len - ret);
-    }
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeWrite(%p \"%s\", %li) == %li",
-           data, qt_prettyDebug(data, qMin((int)ret, 16), (int)ret).data(), (int)len, (int)ret);
-#endif
-
-    return ret;
-}
-
-qint64 QNativeSocketEnginePrivate::nativeRead(char *data, qint64 maxLength)
-{
-    qint64 ret = -1;
-    WSABUF buf;
-    buf.buf = data;
-    buf.len = maxLength;
-    DWORD flags = 0;
-    DWORD bytesRead = 0;
-#if defined(Q_OS_WINCE)
-    WSASetLastError(0);
-#endif
-    if (::WSARecv(socketDescriptor, &buf, 1, &bytesRead, &flags, 0,0) ==  SOCKET_ERROR) {
-        int err = WSAGetLastError();
-        WS_ERROR_DEBUG(err);
-        switch (err) {
-        case WSAEWOULDBLOCK:
-            ret = -2;
-            break;
-        case WSAEBADF:
-        case WSAEINVAL:
-            //error string is now set in read(), not here in nativeRead()
-            break;
-        case WSAECONNRESET:
-        case WSAECONNABORTED:
-            // for tcp sockets this will be handled in QNativeSocketEngine::read
-            ret = 0;
-            break;
-        default:
-            break;
-        }
-    } else {
-        if (WSAGetLastError() == WSAEWOULDBLOCK)
-            ret = -2;
-        else
-            ret = qint64(bytesRead);
-    }
-
-#if defined (QNATIVESOCKETENGINE_DEBUG)
-    if (ret != -2) {
-        qDebug("QNativeSocketEnginePrivate::nativeRead(%p \"%s\", %l) == %li",
-               data, qt_prettyDebug(data, qMin((int)bytesRead, 16), (int)bytesRead).data(), (int)maxLength, (int)ret);
-    } else {
-        qDebug("QNativeSocketEnginePrivate::nativeRead(%p, %l) == -2 (WOULD BLOCK)",
-               data, int(maxLength));
-    }
-#endif
-
-    return ret;
-}
-
-int QNativeSocketEnginePrivate::nativeSelect(int timeout, bool selectForRead) const
-{
-    bool readEnabled = selectForRead && readNotifier && readNotifier->isEnabled();
-    if (readEnabled)
-        readNotifier->setEnabled(false);
-    
-    fd_set fds;
-
-    int ret = 0;
-
-    memset(&fds, 0, sizeof(fd_set));
-    fds.fd_count = 1;
-    fds.fd_array[0] = (SOCKET)socketDescriptor;
-
-    struct timeval tv;
-    tv.tv_sec = timeout / 1000;
-    tv.tv_usec = (timeout % 1000) * 1000;
-
-    if (selectForRead) {
-        ret = select(0, &fds, 0, 0, timeout < 0 ? 0 : &tv);
-    } else {
-        // select for write
-
-        // Windows needs this to report errors when connecting a socket ...
-        fd_set fdexception;
-        FD_ZERO(&fdexception);
-        FD_SET((SOCKET)socketDescriptor, &fdexception);
-
-        ret = select(0, 0, &fds, &fdexception, timeout < 0 ? 0 : &tv);
-
-        // ... but if it is actually set, pretend it did not happen
-        if (ret > 0 && FD_ISSET((SOCKET)socketDescriptor, &fdexception))
-            ret--;
-    }
-
-    if (readEnabled)
-        readNotifier->setEnabled(true);
-
-    return ret;
-}
-
-int QNativeSocketEnginePrivate::nativeSelect(int timeout,
-                                      bool checkRead, bool checkWrite,
-                                      bool *selectForRead, bool *selectForWrite) const
-{
-    bool readEnabled = checkRead && readNotifier && readNotifier->isEnabled();
-    if (readEnabled)
-        readNotifier->setEnabled(false);
-
-    fd_set fdread;
-    fd_set fdwrite;
-    fd_set fdexception;
-
-    int ret = 0;
-
-    memset(&fdread, 0, sizeof(fd_set));
-    if (checkRead) {
-        fdread.fd_count = 1;
-        fdread.fd_array[0] = (SOCKET)socketDescriptor;
-    }
-    memset(&fdwrite, 0, sizeof(fd_set));
-    FD_ZERO(&fdexception);
-    if (checkWrite) {
-        fdwrite.fd_count = 1;
-        fdwrite.fd_array[0] = (SOCKET)socketDescriptor;
-
-        // Windows needs this to report errors when connecting a socket
-        FD_SET((SOCKET)socketDescriptor, &fdexception);
-    }
-
-    struct timeval tv;
-    tv.tv_sec = timeout / 1000;
-    tv.tv_usec = (timeout % 1000) * 1000;
-
-#if !defined(Q_OS_WINCE)
-    ret = select(socketDescriptor + 1, &fdread, &fdwrite, &fdexception, timeout < 0 ? 0 : &tv);
-#else
-    ret = select(1, &fdread, &fdwrite, &fdexception, timeout < 0 ? 0 : &tv);
-#endif
-
-     //... but if it is actually set, pretend it did not happen
-    if (ret > 0 && FD_ISSET((SOCKET)socketDescriptor, &fdexception))
-        ret--;
-
-    if (readEnabled)
-        readNotifier->setEnabled(true);
-
-    if (ret <= 0)
-        return ret;
-
-    *selectForRead = FD_ISSET((SOCKET)socketDescriptor, &fdread);
-    *selectForWrite = FD_ISSET((SOCKET)socketDescriptor, &fdwrite);
-
-    return ret;
-}
-
-void QNativeSocketEnginePrivate::nativeClose()
-{
-#if defined (QTCPSOCKETENGINE_DEBUG)
-    qDebug("QNativeSocketEnginePrivate::nativeClose()");
-#endif
-    // We were doing a setsockopt here before with SO_DONTLINGER. (However with kind of wrong
-    // usage of parameters, it wants a BOOL but we used a struct and pretended it to be bool).
-    // We don't think setting this option should be done here, if a user wants it she/he can
-     // do it manually with socketDescriptor()/setSocketDescriptor();
-    ::closesocket(socketDescriptor);
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qgl_mac.mm b/src/opengl/qgl_mac.mm
deleted file mode 100644 (file)
index c1f3475..0000000
+++ /dev/null
@@ -1,992 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qgl.h"
-
-// There are functions that are deprecated in 10.5, but really there's no way around them
-// for Carbon, so just undefine them.
-#undef DEPRECATED_ATTRIBUTE
-#define DEPRECATED_ATTRIBUTE
-#if defined(Q_WS_MAC)
-#ifndef QT_MAC_USE_COCOA
-#ifdef qDebug
-#    undef qDebug
-#    include <AGL/agl.h>
-#    include <AGL/aglRenderers.h>
-#    include <OpenGL/gl.h>
-#    ifdef QT_NO_DEBUG
-#        define qDebug qt_noop(),1?(void)0:qDebug
-#    endif
-#else
-#    include <AGL/agl.h>
-#    include <AGL/aglRenderers.h>
-#    include <OpenGL/gl.h>
-#endif
-#else
-#include <qcocoaview_mac_p.h>
-#endif
-
-
-#include <OpenGL/gl.h>
-#include <CoreServices/CoreServices.h>
-#include <qfont_p.h>
-#include <qfontengine_p.h>
-#include <qgl_p.h>
-#include <qpaintengine_opengl_p.h>
-#include <qt_mac_p.h>
-#include <qpixmap.h>
-#include <qtimer.h>
-#include <qapplication.h>
-#include <qstack.h>
-#include <qdesktopwidget.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-#ifdef QT_MAC_USE_COCOA
-QT_END_NAMESPACE
-
-QT_FORWARD_DECLARE_CLASS(QWidget)
-QT_FORWARD_DECLARE_CLASS(QWidgetPrivate)
-QT_FORWARD_DECLARE_CLASS(QGLWidgetPrivate)
-
-QT_BEGIN_NAMESPACE
-
-void *qt_current_nsopengl_context()
-{
-    return [NSOpenGLContext currentContext];
-}
-
-static GLint attribValue(NSOpenGLPixelFormat *fmt, NSOpenGLPixelFormatAttribute attrib)
-{
-    GLint res;
-    [fmt getValues:&res forAttribute:attrib forVirtualScreen:0];
-    return res;
-}
-
-static int def(int val, int defVal)
-{
-    return val != -1 ? val : defVal;
-}
-#else
-QRegion qt_mac_get_widget_rgn(const QWidget *widget);
-#endif
-
-extern quint32 *qt_mac_pixmap_get_base(const QPixmap *);
-extern int qt_mac_pixmap_get_bytes_per_line(const QPixmap *);
-extern RgnHandle qt_mac_get_rgn(); //qregion_mac.cpp
-extern void qt_mac_dispose_rgn(RgnHandle); //qregion_mac.cpp
-extern QRegion qt_mac_convert_mac_region(RgnHandle); //qregion_mac.cpp
-
-/*
-    QGLTemporaryContext implementation
-*/
-
-class QGLTemporaryContextPrivate
-{
-public:
-#ifndef QT_MAC_USE_COCOA
-    AGLContext ctx;
-#else
-    NSOpenGLContext *ctx;
-#endif
-};
-
-QGLTemporaryContext::QGLTemporaryContext(bool, QWidget *)
-    : d(new QGLTemporaryContextPrivate)
-{
-    d->ctx = 0;
-#ifndef QT_MAC_USE_COCOA
-    GLint attribs[] = {AGL_RGBA, AGL_NONE};
-    AGLPixelFormat fmt = aglChoosePixelFormat(0, 0, attribs);
-    if (!fmt) {
-        qDebug("QGLTemporaryContext: Couldn't find any RGB visuals");
-        return;
-    }
-    d->ctx = aglCreateContext(fmt, 0);
-    if (!d->ctx)
-        qDebug("QGLTemporaryContext: Unable to create context");
-    else
-        aglSetCurrentContext(d->ctx);
-    aglDestroyPixelFormat(fmt);
-#else
-    QMacCocoaAutoReleasePool pool;
-    NSOpenGLPixelFormatAttribute attribs[] = { 0 };
-    NSOpenGLPixelFormat *fmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
-    if (!fmt) {
-        qWarning("QGLTemporaryContext: Cannot find any visuals");
-        return;
-    }
-
-    d->ctx = [[NSOpenGLContext alloc] initWithFormat:fmt shareContext:0];
-    if (!d->ctx)
-        qWarning("QGLTemporaryContext: Cannot create context");
-    else
-        [d->ctx makeCurrentContext];
-    [fmt release];
-#endif
-}
-
-QGLTemporaryContext::~QGLTemporaryContext()
-{
-    if (d->ctx) {
-#ifndef QT_MAC_USE_COCOA
-        aglSetCurrentContext(0);
-        aglDestroyContext(d->ctx);
-#else
-        [NSOpenGLContext clearCurrentContext];
-        [d->ctx release];
-#endif
-    }
-}
-
-bool QGLFormat::hasOpenGL()
-{
-    return true;
-}
-
-bool QGLFormat::hasOpenGLOverlays()
-{
-    return false;
-}
-
-bool QGLContext::chooseContext(const QGLContext *shareContext)
-{
-    QMacCocoaAutoReleasePool pool;
-    Q_D(QGLContext);
-    d->cx = 0;
-    d->vi = chooseMacVisual(0);
-    if (!d->vi)
-        return false;
-
-#ifndef QT_MAC_USE_COCOA
-    AGLPixelFormat fmt = (AGLPixelFormat)d->vi;
-    GLint res;
-    aglDescribePixelFormat(fmt, AGL_LEVEL, &res);
-    d->glFormat.setPlane(res);
-    if (deviceIsPixmap())
-        res = 0;
-    else
-        aglDescribePixelFormat(fmt, AGL_DOUBLEBUFFER, &res);
-    d->glFormat.setDoubleBuffer(res);
-    aglDescribePixelFormat(fmt, AGL_DEPTH_SIZE, &res);
-    d->glFormat.setDepth(res);
-    if (d->glFormat.depth())
-        d->glFormat.setDepthBufferSize(res);
-    aglDescribePixelFormat(fmt, AGL_RGBA, &res);
-    d->glFormat.setRgba(res);
-    aglDescribePixelFormat(fmt, AGL_RED_SIZE, &res);
-    d->glFormat.setRedBufferSize(res);
-    aglDescribePixelFormat(fmt, AGL_GREEN_SIZE, &res);
-    d->glFormat.setGreenBufferSize(res);
-    aglDescribePixelFormat(fmt, AGL_BLUE_SIZE, &res);
-    d->glFormat.setBlueBufferSize(res);
-    aglDescribePixelFormat(fmt, AGL_ALPHA_SIZE, &res);
-    d->glFormat.setAlpha(res);
-    if (d->glFormat.alpha())
-        d->glFormat.setAlphaBufferSize(res);
-    aglDescribePixelFormat(fmt, AGL_ACCUM_RED_SIZE, &res);
-    // Bug in Apple OpenGL (rdr://5015603), when we don't have an accumulation
-    // buffer, it still claims that we have a 16-bit one (which is pretty rare).
-    // So, we just assume we can never have a buffer that small.
-    d->glFormat.setAccum(res > 5);
-    if (d->glFormat.accum())
-        d->glFormat.setAccumBufferSize(res);
-    aglDescribePixelFormat(fmt, AGL_STENCIL_SIZE, &res);
-    d->glFormat.setStencil(res);
-    if (d->glFormat.stencil())
-        d->glFormat.setStencilBufferSize(res);
-    aglDescribePixelFormat(fmt, AGL_STEREO, &res);
-    d->glFormat.setStereo(res);
-    aglDescribePixelFormat(fmt, AGL_SAMPLE_BUFFERS_ARB, &res);
-    d->glFormat.setSampleBuffers(res);
-    if (d->glFormat.sampleBuffers()) {
-        aglDescribePixelFormat(fmt, AGL_SAMPLES_ARB, &res);
-        d->glFormat.setSamples(res);
-    }
-#else
-    NSOpenGLPixelFormat *fmt = static_cast<NSOpenGLPixelFormat *>(d->vi);
-
-    d->glFormat = QGLFormat();
-
-    // ### make sure to reset other options
-    d->glFormat.setDoubleBuffer(attribValue(fmt, NSOpenGLPFADoubleBuffer));
-
-    int depthSize = attribValue(fmt, NSOpenGLPFADepthSize);
-    d->glFormat.setDepth(depthSize > 0);
-    if (depthSize > 0)
-        d->glFormat.setDepthBufferSize(depthSize);
-
-    int alphaSize = attribValue(fmt, NSOpenGLPFAAlphaSize);
-    d->glFormat.setAlpha(alphaSize > 0);
-    if (alphaSize > 0)
-        d->glFormat.setAlphaBufferSize(alphaSize);
-
-    int accumSize = attribValue(fmt, NSOpenGLPFAAccumSize);
-    d->glFormat.setAccum(accumSize > 0);
-    if (accumSize > 0)
-        d->glFormat.setAccumBufferSize(accumSize);
-
-    int stencilSize = attribValue(fmt, NSOpenGLPFAStencilSize);
-    d->glFormat.setStencil(stencilSize > 0);
-    if (stencilSize > 0)
-        d->glFormat.setStencilBufferSize(stencilSize);
-
-    d->glFormat.setStereo(attribValue(fmt, NSOpenGLPFAStereo));
-
-    int sampleBuffers = attribValue(fmt, NSOpenGLPFASampleBuffers);
-    d->glFormat.setSampleBuffers(sampleBuffers);
-    if (sampleBuffers > 0)
-        d->glFormat.setSamples(attribValue(fmt, NSOpenGLPFASamples));
-#endif
-    if (shareContext && (!shareContext->isValid() || !shareContext->d_func()->cx)) {
-        qWarning("QGLContext::chooseContext: Cannot share with invalid context");
-        shareContext = 0;
-    }
-
-    // sharing between rgba and color-index will give wrong colors
-    if (shareContext && (format().rgba() != shareContext->format().rgba()))
-        shareContext = 0;
-
-#ifndef QT_MAC_USE_COCOA
-    AGLContext ctx = aglCreateContext(fmt, (AGLContext) (shareContext ? shareContext->d_func()->cx : 0));
-#else
-    NSOpenGLContext *ctx = [[NSOpenGLContext alloc] initWithFormat:fmt
-        shareContext:(shareContext ? static_cast<NSOpenGLContext *>(shareContext->d_func()->cx)
-                                   : 0)];
-#endif
-    if (!ctx) {
-#ifndef QT_MAC_USE_COCOA
-        GLenum err = aglGetError();
-        if (err == AGL_BAD_MATCH || err == AGL_BAD_CONTEXT) {
-            if (shareContext && shareContext->d_func()->cx) {
-                qWarning("QGLContext::chooseContext(): Context sharing mismatch!");
-                if (!(ctx = aglCreateContext(fmt, 0)))
-                    return false;
-                shareContext = 0;
-            }
-        }
-#else
-        if (shareContext) {
-            ctx = [[NSOpenGLContext alloc] initWithFormat:fmt shareContext:0];
-            if (ctx) {
-                qWarning("QGLContext::chooseContext: Context sharing mismatch");
-                shareContext = 0;
-            }
-        }
-#endif
-        if (!ctx) {
-            qWarning("QGLContext::chooseContext: Unable to create QGLContext");
-            return false;
-        }
-    }
-    d->cx = ctx;
-    if (shareContext && shareContext->d_func()->cx) {
-        QGLContext *share = const_cast<QGLContext *>(shareContext);
-        d->sharing = true;
-        share->d_func()->sharing = true;
-    }
-    if (deviceIsPixmap())
-        updatePaintDevice();
-
-    // vblank syncing
-    GLint interval = d->reqFormat.swapInterval();
-    if (interval != -1) {
-#ifndef QT_MAC_USE_COCOA
-        aglSetInteger((AGLContext)d->cx, AGL_SWAP_INTERVAL, &interval);
-        if (interval != 0)
-            aglEnable((AGLContext)d->cx, AGL_SWAP_INTERVAL);
-        else
-            aglDisable((AGLContext)d->cx, AGL_SWAP_INTERVAL);
-#else
-        [ctx setValues:&interval forParameter:NSOpenGLCPSwapInterval];
-#endif
-    }
-#ifndef QT_MAC_USE_COCOA
-    aglGetInteger((AGLContext)d->cx, AGL_SWAP_INTERVAL, &interval);
-#else
-    [ctx getValues:&interval forParameter:NSOpenGLCPSwapInterval];
-#endif
-    d->glFormat.setSwapInterval(interval);
-    return true;
-}
-
-void *QGLContextPrivate::tryFormat(const QGLFormat &format)
-{
-    static const int Max = 40;
-#ifndef QT_MAC_USE_COCOA
-    GLint attribs[Max], cnt = 0;
-    bool device_is_pixmap = (paintDevice->devType() == QInternal::Pixmap);
-
-    attribs[cnt++] = AGL_RGBA;
-    attribs[cnt++] = AGL_BUFFER_SIZE;
-    attribs[cnt++] = device_is_pixmap ? static_cast<QPixmap *>(paintDevice)->depth() : 32;
-    attribs[cnt++] = AGL_LEVEL;
-    attribs[cnt++] = format.plane();
-
-    if (format.redBufferSize() != -1) {
-        attribs[cnt++] = AGL_RED_SIZE;
-        attribs[cnt++] = format.redBufferSize();
-    }
-    if (format.greenBufferSize() != -1) {
-        attribs[cnt++] = AGL_GREEN_SIZE;
-        attribs[cnt++] = format.greenBufferSize();
-    }
-    if (format.blueBufferSize() != -1) {
-        attribs[cnt++] = AGL_BLUE_SIZE;
-        attribs[cnt++] = format.blueBufferSize();
-    }
-    if (device_is_pixmap) {
-        attribs[cnt++] = AGL_PIXEL_SIZE;
-        attribs[cnt++] = static_cast<QPixmap *>(paintDevice)->depth();
-        attribs[cnt++] = AGL_OFFSCREEN;
-        if (!format.alpha()) {
-            attribs[cnt++] = AGL_ALPHA_SIZE;
-            attribs[cnt++] = 8;
-        }
-    } else {
-        if (format.doubleBuffer())
-            attribs[cnt++] = AGL_DOUBLEBUFFER;
-    }
-
-    if (format.stereo())
-        attribs[cnt++] = AGL_STEREO;
-    if (format.alpha()) {
-        attribs[cnt++] = AGL_ALPHA_SIZE;
-        attribs[cnt++] = format.alphaBufferSize() == -1 ? 8 : format.alphaBufferSize();
-    }
-    if (format.stencil()) {
-        attribs[cnt++] = AGL_STENCIL_SIZE;
-        attribs[cnt++] = format.stencilBufferSize() == -1 ? 8 : format.stencilBufferSize();
-    }
-    if (format.depth()) {
-        attribs[cnt++] = AGL_DEPTH_SIZE;
-        attribs[cnt++] = format.depthBufferSize() == -1 ? 32 : format.depthBufferSize();
-    }
-    if (format.accum()) {
-        attribs[cnt++] = AGL_ACCUM_RED_SIZE;
-        attribs[cnt++] = format.accumBufferSize() == -1 ? 1 : format.accumBufferSize();
-        attribs[cnt++] = AGL_ACCUM_BLUE_SIZE;
-        attribs[cnt++] = format.accumBufferSize() == -1 ? 1 : format.accumBufferSize();
-        attribs[cnt++] = AGL_ACCUM_GREEN_SIZE;
-        attribs[cnt++] = format.accumBufferSize() == -1 ? 1 : format.accumBufferSize();
-        attribs[cnt++] = AGL_ACCUM_ALPHA_SIZE;
-        attribs[cnt++] = format.accumBufferSize() == -1 ? 1 : format.accumBufferSize();
-    }
-    if (format.sampleBuffers()) {
-        attribs[cnt++] = AGL_SAMPLE_BUFFERS_ARB;
-        attribs[cnt++] = 1;
-        attribs[cnt++] = AGL_SAMPLES_ARB;
-        attribs[cnt++] = format.samples() == -1 ? 4 : format.samples();
-    }
-
-    attribs[cnt] = AGL_NONE;
-    Q_ASSERT(cnt < Max);
-    return aglChoosePixelFormat(0, 0, attribs);
-#else
-    NSOpenGLPixelFormatAttribute attribs[Max];
-    int cnt = 0;
-    int devType = paintDevice->devType();
-    bool device_is_pixmap = (devType == QInternal::Pixmap);
-    int depth = device_is_pixmap ? static_cast<QPixmap *>(paintDevice)->depth() : 32;
-
-    attribs[cnt++] = NSOpenGLPFAColorSize;
-    attribs[cnt++] = depth;
-
-    if (device_is_pixmap) {
-        attribs[cnt++] = NSOpenGLPFAOffScreen;
-    } else {
-        if (format.doubleBuffer())
-            attribs[cnt++] = NSOpenGLPFADoubleBuffer;
-    }
-    if (glFormat.stereo())
-        attribs[cnt++] = NSOpenGLPFAStereo;
-    if (device_is_pixmap || format.alpha()) {
-        attribs[cnt++] = NSOpenGLPFAAlphaSize;
-        attribs[cnt++] = def(format.alphaBufferSize(), 8);
-    }
-    if (format.stencil()) {
-        attribs[cnt++] = NSOpenGLPFAStencilSize;
-        attribs[cnt++] = def(format.stencilBufferSize(), 8);
-    }
-    if (format.depth()) {
-        attribs[cnt++] = NSOpenGLPFADepthSize;
-        attribs[cnt++] = def(format.depthBufferSize(), 32);
-    }
-    if (format.accum()) {
-        attribs[cnt++] = NSOpenGLPFAAccumSize;
-        attribs[cnt++] = def(format.accumBufferSize(), 1);
-    }
-    if (format.sampleBuffers()) {
-        attribs[cnt++] = NSOpenGLPFASampleBuffers;
-        attribs[cnt++] = 1;
-        attribs[cnt++] = NSOpenGLPFASamples;
-        attribs[cnt++] = def(format.samples(), 4);
-    }
-
-    if (devType == QInternal::Pbuffer)
-        attribs[cnt++] = NSOpenGLPFAPixelBuffer;
-
-    attribs[cnt] = 0;
-    Q_ASSERT(cnt < Max);
-    return [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs];
-#endif
-}
-
-void QGLContextPrivate::clearDrawable()
-{
-    [static_cast<NSOpenGLContext *>(cx) clearDrawable];
-}
-
-/*!
-    \bold{Mac OS X only:} This virtual function tries to find a visual that
-    matches the format, reducing the demands if the original request
-    cannot be met.
-
-    The algorithm for reducing the demands of the format is quite
-    simple-minded, so override this method in your subclass if your
-    application has spcific requirements on visual selection.
-
-    The \a handle argument is always zero and is not used
-
-    \sa chooseContext()
-*/
-
-void *QGLContext::chooseMacVisual(GDHandle /* handle */)
-{
-    Q_D(QGLContext);
-
-    void *fmt = d->tryFormat(d->glFormat);
-    if (!fmt && d->glFormat.stereo()) {
-        d->glFormat.setStereo(false);
-        fmt = d->tryFormat(d->glFormat);
-    }
-    if (!fmt && d->glFormat.sampleBuffers()) {
-        d->glFormat.setSampleBuffers(false);
-        fmt = d->tryFormat(d->glFormat);
-    }
-    if (!fmt)
-        qWarning("QGLContext::chooseMacVisual: Unable to choose a pixel format");
-    return fmt;
-}
-
-void QGLContext::reset()
-{
-    Q_D(QGLContext);
-    if (!d->valid)
-        return;
-    d->cleanup();
-    doneCurrent();
-#ifndef QT_MAC_USE_COCOA
-    if (d->cx)
-        aglDestroyContext((AGLContext)d->cx);
-#else
-    QMacCocoaAutoReleasePool pool;
-    [static_cast<NSOpenGLContext *>(d->cx) release];
-#endif
-    d->cx = 0;
-#ifndef QT_MAC_USE_COCOA
-    if (d->vi)
-        aglDestroyPixelFormat((AGLPixelFormat)d->vi);
-#else
-    [static_cast<NSOpenGLPixelFormat *>(d->vi) release];
-#endif
-    d->vi = 0;
-    d->crWin = false;
-    d->sharing = false;
-    d->valid = false;
-    d->transpColor = QColor();
-    d->initDone = false;
-    QGLContextGroup::removeShare(this);
-}
-
-void QGLContext::makeCurrent()
-{
-    Q_D(QGLContext);
-
-    if (!d->valid) {
-        qWarning("QGLContext::makeCurrent: Cannot make invalid context current");
-        return;
-    }
-#ifndef QT_MAC_USE_COCOA
-    aglSetCurrentContext((AGLContext)d->cx);
-    if (d->update)
-        updatePaintDevice();
-#else
-    [static_cast<NSOpenGLContext *>(d->cx) makeCurrentContext];
-#endif
-    QGLContextPrivate::setCurrentContext(this);
-}
-
-#ifndef QT_MAC_USE_COCOA
-/*
-    Returns the effective scale factor for a widget. For this value to be
-    different than 1, the following must be true:
-    - The system scale factor must be greater than 1.
-    - The widget window must have WA_MacFrameworkScaled set.
-*/
-float qt_mac_get_scale_factor(QWidget *widget)
-{
-    if (!widget | !widget->window())
-        return 1;
-
-    if (widget->window()->testAttribute(Qt::WA_MacFrameworkScaled) == false)
-        return 1;
-
-    float systemScale = QSysInfo::MacintoshVersion >= QSysInfo::MV_10_4 ? HIGetScaleFactor() : 1;
-    if (systemScale == float(1))
-        return 1;
-
-    return systemScale;
-}
-#endif
-
-/*! \internal
-*/
-void QGLContext::updatePaintDevice()
-{
-    Q_D(QGLContext);
-#ifndef QT_MAC_USE_COCOA
-    d->update = false;
-    if (d->paintDevice->devType() == QInternal::Widget) {
-        //get control information
-        QWidget *w = (QWidget *)d->paintDevice;
-        HIViewRef hiview = (HIViewRef)w->winId();
-        WindowRef window = HIViewGetWindow(hiview);
-#ifdef DEBUG_OPENGL_REGION_UPDATE
-        static int serial_no_gl = 0;
-        qDebug("[%d] %p setting on %s::%s %p/%p [%s]", ++serial_no_gl, w,
-                w->metaObject()->className(), w->objectName().toLatin1().constData(),
-                hiview, window, w->handle() ? "Inside" : "Outside");
-#endif
-
-        //update drawable
-        if (0 && w->isWindow() && w->isFullScreen()) {
-            aglSetDrawable((AGLContext)d->cx, 0);
-            aglSetFullScreen((AGLContext)d->cx, w->width(), w->height(), 0, QApplication::desktop()->screenNumber(w));
-            w->hide();
-        } else {
-            AGLDrawable old_draw = aglGetDrawable((AGLContext)d->cx), new_draw = GetWindowPort(window);
-            if (old_draw != new_draw)
-                aglSetDrawable((AGLContext)d->cx, new_draw);
-        }
-
-        float scale  = qt_mac_get_scale_factor(w);
-
-        if (!w->isWindow()) {
-            QRegion clp = qt_mac_get_widget_rgn(w); //get drawable area
-
-#ifdef DEBUG_OPENGL_REGION_UPDATE
-            if (clp.isEmpty()) {
-                qDebug("  Empty area!");
-            } else {
-                QVector<QRect> rs = clp.rects();
-                for(int i = 0; i < rs.count(); i++)
-                    qDebug("  %d %d %d %d", rs[i].x(), rs[i].y(), rs[i].width(), rs[i].height());
-            }
-#endif
-            //update the clip
-            if (!aglIsEnabled((AGLContext)d->cx, AGL_BUFFER_RECT))
-                aglEnable((AGLContext)d->cx, AGL_BUFFER_RECT);
-            if (clp.isEmpty()) {
-                GLint offs[4] = { 0, 0, 0, 0 };
-                aglSetInteger((AGLContext)d->cx, AGL_BUFFER_RECT, offs);
-                if (aglIsEnabled((AGLContext)d->cx, AGL_CLIP_REGION))
-                    aglDisable((AGLContext)d->cx, AGL_CLIP_REGION);
-            } else {
-                HIPoint origin = { 0., 0. };
-                HIViewConvertPoint(&origin, HIViewRef(w->winId()), 0);
-                const GLint offs[4] = { qRound(origin.x),
-                    w->window()->frameGeometry().height() * scale
-                        - (qRound(origin.y) + w->height() * scale),
-                    w->width() * scale, w->height() * scale};
-
-                RgnHandle region = clp.handle(true);
-
-                if (scale != float(1)) {
-                    // Sacle the clip region by the scale factor
-                    Rect regionBounds;
-                    GetRegionBounds(region, &regionBounds);
-                    Rect regionBoundsDest = regionBounds;
-                    regionBoundsDest.bottom *= scale;
-                    regionBoundsDest.right *= scale;
-                    MapRgn(region, &regionBounds, &regionBoundsDest);
-                }
-
-                aglSetInteger((AGLContext)d->cx, AGL_BUFFER_RECT, offs);
-                aglSetInteger((AGLContext)d->cx, AGL_CLIP_REGION, (const GLint *)region);
-                if (!aglIsEnabled((AGLContext)d->cx, AGL_CLIP_REGION))
-                    aglEnable((AGLContext)d->cx, AGL_CLIP_REGION);
-            }
-        } else {
-            // Set the buffer rect for top-level gl contexts when scaled.
-            if (scale != float(1)) {
-                aglEnable((AGLContext)d->cx, AGL_BUFFER_RECT);
-                const GLint offs[4] = { 0, 0,  w->width() * scale , w->height() * scale};
-                aglSetInteger((AGLContext)d->cx, AGL_BUFFER_RECT, offs);
-            }
-        }
-    } else if (d->paintDevice->devType() == QInternal::Pixmap) {
-        QPixmap *pm = reinterpret_cast<QPixmap *>(d->paintDevice);
-
-        unsigned long qdformat = k32ARGBPixelFormat;
-        if (QSysInfo::ByteOrder == QSysInfo::LittleEndian)
-            qdformat = k32BGRAPixelFormat;
-        Rect rect;
-        SetRect(&rect, 0, 0, pm->width(), pm->height());
-
-        GWorldPtr gworld;
-        NewGWorldFromPtr(&gworld, qdformat, &rect, 0, 0, 0,
-                         reinterpret_cast<char *>(qt_mac_pixmap_get_base(pm)), 
-                         qt_mac_pixmap_get_bytes_per_line(pm));
-
-        PixMapHandle pixmapHandle = GetGWorldPixMap(gworld);
-        aglSetOffScreen(reinterpret_cast<AGLContext>(d->cx), pm->width(), pm->height(),
-                        GetPixRowBytes(pixmapHandle), GetPixBaseAddr(pixmapHandle));
-    } else {
-        qWarning("QGLContext::updatePaintDevice(): Not sure how to render OpenGL on this device!");
-    }
-    aglUpdateContext((AGLContext)d->cx);
-
-#else
-    QMacCocoaAutoReleasePool pool;
-
-    if (d->paintDevice->devType() == QInternal::Widget) {
-        //get control information
-        QWidget *w = (QWidget *)d->paintDevice;
-        NSView *view = qt_mac_nativeview_for(w);
-
-        // Trying to attach the GL context to the NSView will fail with
-        // "invalid drawable" if done too soon, but we have to make sure
-        // the connection is made before the first paint event. Using
-        // the NSView do to this check fails as the NSView is visible
-        // before it's safe to connect, and using the NSWindow fails as
-        // the NSWindow will become visible after the first paint event.
-        // This leaves us with the QWidget, who's visible state seems
-        // to match the point in time when it's safe to connect.
-        if (!w || !w->isVisible())
-            return; // Not safe to attach GL context to view yet
-
-        if ([static_cast<NSOpenGLContext *>(d->cx) view] != view && ![view isHidden])
-            [static_cast<NSOpenGLContext *>(d->cx) setView:view];
-    } else if (d->paintDevice->devType() == QInternal::Pixmap) {
-        const QPixmap *pm = static_cast<const QPixmap *>(d->paintDevice);
-        [static_cast<NSOpenGLContext *>(d->cx) setOffScreen:qt_mac_pixmap_get_base(pm)
-                                                      width:pm->width()
-                                                     height:pm->height()
-                                                   rowbytes:qt_mac_pixmap_get_bytes_per_line(pm)];
-    } else {
-        qWarning("QGLContext::updatePaintDevice: Not sure how to render OpenGL on this device");
-    }
-    [static_cast<NSOpenGLContext *>(d->cx) update];
-#endif
-}
-
-void QGLContext::doneCurrent()
-{
-
-    if (
-#ifndef QT_MAC_USE_COCOA
-        aglGetCurrentContext() != (AGLContext) d_func()->cx
-#else
-        [NSOpenGLContext currentContext] != d_func()->cx
-#endif
-       )
-        return;
-
-    QGLContextPrivate::setCurrentContext(0);
-#ifndef QT_MAC_USE_COCOA
-    aglSetCurrentContext(0);
-#else
-    [NSOpenGLContext clearCurrentContext];
-#endif
-}
-
-void QGLContext::swapBuffers() const
-{
-    Q_D(const QGLContext);
-    if (!d->valid)
-        return;
-#ifndef QT_MAC_USE_COCOA
-    aglSwapBuffers((AGLContext)d->cx);
-#else
-    [static_cast<NSOpenGLContext *>(d->cx) flushBuffer];
-#endif
-}
-
-QColor QGLContext::overlayTransparentColor() const
-{
-    return QColor(0, 0, 0);                // Invalid color
-}
-
-#ifndef QT_MAC_USE_COCOA
-static QColor cmap[256];
-static bool cmap_init = false;
-#endif
-uint QGLContext::colorIndex(const QColor &c) const
-{
-#ifndef QT_MAC_USE_COCOA
-    int ret = -1;
-    if(!cmap_init) {
-        cmap_init = true;
-        for(int i = 0; i < 256; i++)
-            cmap[i] = QColor();
-    } else {
-        for(int i = 0; i < 256; i++) {
-            if(cmap[i].isValid() && cmap[i] == c) {
-                ret = i;
-                break;
-            }
-        }
-    }
-    if(ret == -1) {
-        for(ret = 0; ret < 256; ret++)
-            if(!cmap[ret].isValid())
-                break;
-        if(ret == 256) {
-            ret = -1;
-            qWarning("QGLContext::colorIndex(): Internal error!");
-        } else {
-            cmap[ret] = c;
-
-            GLint vals[4];
-            vals[0] = ret;
-            vals[1] = c.red();
-            vals[2] = c.green();
-            vals[3] = c.blue();
-            aglSetInteger((AGLContext)d_func()->cx, AGL_COLORMAP_ENTRY, vals);
-        }
-    }
-    return (uint)(ret == -1 ? 0 : ret);
-#else
-    Q_UNUSED(c);
-    return 0;
-#endif
-}
-
-void QGLContext::generateFontDisplayLists(const QFont & /* fnt */, int /* listBase */)
-{
-}
-
-static CFBundleRef qt_getOpenGLBundle()
-{
-    CFBundleRef bundle = 0;
-    CFStringRef urlString = QCFString::toCFStringRef(QLatin1String("/System/Library/Frameworks/OpenGL.framework"));
-    QCFType<CFURLRef> url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
-                 urlString, kCFURLPOSIXPathStyle, false);
-    if (url)
-        bundle = CFBundleCreate(kCFAllocatorDefault, url);
-    CFRelease(urlString);
-    return bundle;
-}
-
-void *QGLContext::getProcAddress(const QString &proc) const
-{
-    CFStringRef procName = QCFString(proc).toCFStringRef(proc);
-    void *result = CFBundleGetFunctionPointerForName(QCFType<CFBundleRef>(qt_getOpenGLBundle()),
-                                             procName);
-    CFRelease(procName);
-    return result;
-}
-#ifndef QT_MAC_USE_COCOA
-/*****************************************************************************
-  QGLWidget AGL-specific code
- *****************************************************************************/
-
-/****************************************************************************
-  Hacks to glue AGL to an HIView
- ***************************************************************************/
-QRegion qt_mac_get_widget_rgn(const QWidget *widget)
-{
-    if(!widget->isVisible() || widget->isMinimized())
-        return QRegion();
-    const QRect wrect = QRect(qt_mac_posInWindow(widget), widget->size());
-    if(!wrect.isValid())
-        return QRegion();
-
-    RgnHandle macr = qt_mac_get_rgn();
-    GetControlRegion((HIViewRef)widget->winId(), kControlStructureMetaPart, macr);
-    OffsetRgn(macr, wrect.x(), wrect.y());
-    QRegion ret = qt_mac_convert_mac_region(macr);
-
-    QPoint clip_pos = wrect.topLeft();
-    for(const QWidget *last_clip = 0, *clip = widget; clip; last_clip = clip, clip = clip->parentWidget()) {
-        if(clip != widget) {
-            GetControlRegion((HIViewRef)clip->winId(), kControlStructureMetaPart, macr);
-            OffsetRgn(macr, clip_pos.x(), clip_pos.y());
-            ret &= qt_mac_convert_mac_region(macr);
-        }
-        const QObjectList &children = clip->children();
-        for(int i = children.size()-1; i >= 0; --i) {
-            if(QWidget *child = qobject_cast<QWidget*>(children.at(i))) {
-                if(child == last_clip)
-                    break;
-
-                // This check may seem weird, but when we are using a unified toolbar
-                // The widget is actually being owned by that toolbar and not by Qt.
-                // This means that the geometry it reports will be wrong
-                // and will accidentally cause problems when calculating the region
-                // So, it is better to skip these widgets since they aren't the hierarchy
-                // anyway.
-                if (HIViewGetSuperview(HIViewRef(child->winId())) != HIViewRef(clip->winId()))
-                    continue;
-
-                if(child->isVisible() && !child->isMinimized() && !child->isTopLevel()) {
-                    const QRect childRect = QRect(clip_pos+child->pos(), child->size());
-                    if(childRect.isValid() && wrect.intersects(childRect)) {
-                        GetControlRegion((HIViewRef)child->winId(), kControlStructureMetaPart, macr);
-                        OffsetRgn(macr, childRect.x(), childRect.y());
-                        ret -= qt_mac_convert_mac_region(macr);
-                    }
-                }
-            }
-        }
-        if(clip->isWindow())
-            break;
-        clip_pos -= clip->pos();
-    }
-    qt_mac_dispose_rgn(macr);
-    return ret;
-}
-
-#endif
-
-void QGLWidget::setMouseTracking(bool enable)
-{
-    QWidget::setMouseTracking(enable);
-}
-
-void QGLWidget::resizeEvent(QResizeEvent *)
-{
-    Q_D(QGLWidget);
-    if (!isValid())
-        return;
-#ifndef QT_MAC_USE_COCOA
-    if (!isWindow())
-        d->glcx->d_func()->update = true;
-#endif
-    makeCurrent();
-    if (!d->glcx->initialized())
-        glInit();
-#ifdef QT_MAC_USE_COCOA
-    d->glcx->updatePaintDevice();
-#endif
-#ifndef QT_MAC_USE_COCOA
-    float scale  = qt_mac_get_scale_factor(this);
-    resizeGL(width() * scale, height() * scale);
-#else
-    resizeGL(width(), height());
-#endif
-}
-
-const QGLContext* QGLWidget::overlayContext() const
-{
-    return 0;
-}
-
-void QGLWidget::makeOverlayCurrent()
-{
-}
-
-void QGLWidget::updateOverlayGL()
-{
-}
-
-void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, bool deleteOldContext)
-{
-    Q_D(QGLWidget);
-    if (context == 0) {
-        qWarning("QGLWidget::setContext: Cannot set null context");
-        return;
-    }
-
-    if (d->glcx)
-        d->glcx->doneCurrent();
-    QGLContext* oldcx = d->glcx;
-    d->glcx = context;
-    if (!d->glcx->isValid())
-        d->glcx->create(shareContext ? shareContext : oldcx);
-    if (deleteOldContext && oldcx)
-        delete oldcx;
-}
-
-void QGLWidgetPrivate::init(QGLContext *context, const QGLWidget *shareWidget)
-{
-    Q_Q(QGLWidget);
-
-    initContext(context, shareWidget);
-
-    QWidget *current = q;
-    while (current) {
-        qt_widget_private(current)->glWidgets.append(QWidgetPrivate::GlWidgetInfo(q));
-        if (current->isWindow())
-            break;
-        current = current->parentWidget();
-    }
-}
-
-bool QGLWidgetPrivate::renderCxPm(QPixmap*)
-{
-    return false;
-}
-
-void QGLWidgetPrivate::cleanupColormaps()
-{
-}
-
-const QGLColormap & QGLWidget::colormap() const
-{
-    return d_func()->cmap;
-}
-
-void QGLWidget::setColormap(const QGLColormap &)
-{
-}
-
-void QGLWidgetPrivate::updatePaintDevice()
-{
-    Q_Q(QGLWidget);
-    glcx->updatePaintDevice();
-    q->update();
-}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qgl_win.cpp b/src/opengl/qgl_win.cpp
deleted file mode 100644 (file)
index c74b88e..0000000
+++ /dev/null
@@ -1,1601 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <qgl.h>
-#include <qlist.h>
-#include <qmap.h>
-#include <qpixmap.h>
-#include <qevent.h>
-#include <qgl_p.h>
-#include <qcolormap.h>
-#include <qvarlengtharray.h>
-#include <qdebug.h>
-#include <qcolor.h>
-
-#include <qt_windows.h>
-
-typedef bool (APIENTRY *PFNWGLGETPIXELFORMATATTRIBIVARB)(HDC hdc,
-                                                         int iPixelFormat,
-                                                         int iLayerPlane,
-                                                         uint nAttributes,
-                                                         const int *piAttributes,
-                                                         int *piValues);
-typedef bool (APIENTRY *PFNWGLCHOOSEPIXELFORMATARB)(HDC hdc,
-                                                    const int *piAttribList,
-                                                    const float *pfAttribFList,
-                                                    uint nMaxFormats,
-                                                    int *piFormats,
-                                                    UINT *nNumFormats);
-#ifndef WGL_ARB_multisample
-#define WGL_SAMPLE_BUFFERS_ARB               0x2041
-#define WGL_SAMPLES_ARB                      0x2042
-#endif
-
-#ifndef WGL_ARB_pixel_format
-#define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
-#define WGL_DRAW_TO_WINDOW_ARB         0x2001
-#define WGL_DRAW_TO_BITMAP_ARB         0x2002
-#define WGL_ACCELERATION_ARB           0x2003
-#define WGL_NEED_PALETTE_ARB           0x2004
-#define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
-#define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
-#define WGL_SWAP_METHOD_ARB            0x2007
-#define WGL_NUMBER_OVERLAYS_ARB        0x2008
-#define WGL_NUMBER_UNDERLAYS_ARB       0x2009
-#define WGL_TRANSPARENT_ARB            0x200A
-#define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
-#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
-#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
-#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
-#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
-#define WGL_SHARE_DEPTH_ARB            0x200C
-#define WGL_SHARE_STENCIL_ARB          0x200D
-#define WGL_SHARE_ACCUM_ARB            0x200E
-#define WGL_SUPPORT_GDI_ARB            0x200F
-#define WGL_SUPPORT_OPENGL_ARB         0x2010
-#define WGL_DOUBLE_BUFFER_ARB          0x2011
-#define WGL_STEREO_ARB                 0x2012
-#define WGL_PIXEL_TYPE_ARB             0x2013
-#define WGL_COLOR_BITS_ARB             0x2014
-#define WGL_RED_BITS_ARB               0x2015
-#define WGL_RED_SHIFT_ARB              0x2016
-#define WGL_GREEN_BITS_ARB             0x2017
-#define WGL_GREEN_SHIFT_ARB            0x2018
-#define WGL_BLUE_BITS_ARB              0x2019
-#define WGL_BLUE_SHIFT_ARB             0x201A
-#define WGL_ALPHA_BITS_ARB             0x201B
-#define WGL_ALPHA_SHIFT_ARB            0x201C
-#define WGL_ACCUM_BITS_ARB             0x201D
-#define WGL_ACCUM_RED_BITS_ARB         0x201E
-#define WGL_ACCUM_GREEN_BITS_ARB       0x201F
-#define WGL_ACCUM_BLUE_BITS_ARB        0x2020
-#define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
-#define WGL_DEPTH_BITS_ARB             0x2022
-#define WGL_STENCIL_BITS_ARB           0x2023
-#define WGL_AUX_BUFFERS_ARB            0x2024
-#define WGL_NO_ACCELERATION_ARB        0x2025
-#define WGL_GENERIC_ACCELERATION_ARB   0x2026
-#define WGL_FULL_ACCELERATION_ARB      0x2027
-#define WGL_SWAP_EXCHANGE_ARB          0x2028
-#define WGL_SWAP_COPY_ARB              0x2029
-#define WGL_SWAP_UNDEFINED_ARB         0x202A
-#define WGL_TYPE_RGBA_ARB              0x202B
-#define WGL_TYPE_COLORINDEX_ARB        0x202C
-#endif
-
-#ifndef WGL_ARB_create_context
-#define WGL_CONTEXT_MAJOR_VERSION_ARB               0x2091
-#define WGL_CONTEXT_MINOR_VERSION_ARB               0x2092
-#define WGL_CONTEXT_LAYER_PLANE_ARB                 0x2093
-#define WGL_CONTEXT_FLAGS_ARB                       0x2094
-#define WGL_CONTEXT_PROFILE_MASK_ARB                0x9126
-#define WGL_CONTEXT_DEBUG_BIT_ARB                   0x0001
-#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB      0x0002
-#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB            0x0001
-#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB   0x0002
-// Error codes returned by GetLastError().
-#define ERROR_INVALID_VERSION_ARB                   0x2095
-#define ERROR_INVALID_PROFILE_ARB                   0x2096
-#endif
-
-#ifndef GL_VERSION_3_2
-#define GL_CONTEXT_PROFILE_MASK                     0x9126
-#define GL_MAJOR_VERSION                            0x821B
-#define GL_MINOR_VERSION                            0x821C
-#define GL_NUM_EXTENSIONS                           0x821D
-#define GL_CONTEXT_FLAGS                            0x821E
-#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT      0x0001
-#endif
-
-QT_BEGIN_NAMESPACE
-
-class QGLCmapPrivate
-{
-public:
-    QGLCmapPrivate() : count(1) { }
-    void ref()                { ++count; }
-    bool deref()        { return !--count; }
-    uint count;
-
-    enum AllocState{ UnAllocated = 0, Allocated = 0x01, Reserved = 0x02 };
-
-    int maxSize;
-    QVector<uint> colorArray;
-    QVector<quint8> allocArray;
-    QVector<quint8> contextArray;
-    QMap<uint,int> colorMap;
-};
-
-/*****************************************************************************
-  QColorMap class - temporarily here, until it is ready for prime time
- *****************************************************************************/
-
-/****************************************************************************
-**
-** Definition of QColorMap class
-**
-****************************************************************************/
-
-class QGLCmapPrivate;
-
-class /*Q_EXPORT*/ QGLCmap
-{
-public:
-    enum Flags { Reserved = 0x01 };
-
-    QGLCmap(int maxSize = 256);
-    QGLCmap(const QGLCmap& map);
-    ~QGLCmap();
-
-    QGLCmap& operator=(const QGLCmap& map);
-
-    // isEmpty and/or isNull ?
-    int size() const;
-    int maxSize() const;
-
-    void resize(int newSize);
-
-    int find(QRgb color) const;
-    int findNearest(QRgb color) const;
-    int allocate(QRgb color, uint flags = 0, quint8 context = 0);
-
-    void setEntry(int idx, QRgb color, uint flags = 0, quint8 context = 0);
-
-    const QRgb* colors() const;
-
-private:
-    void detach();
-    QGLCmapPrivate* d;
-};
-
-
-QGLCmap::QGLCmap(int maxSize) // add a bool prealloc?
-{
-    d = new QGLCmapPrivate;
-    d->maxSize = maxSize;
-}
-
-
-QGLCmap::QGLCmap(const QGLCmap& map)
-{
-    d = map.d;
-    d->ref();
-}
-
-
-QGLCmap::~QGLCmap()
-{
-    if (d && d->deref())
-        delete d;
-    d = 0;
-}
-
-
-QGLCmap& QGLCmap::operator=(const QGLCmap& map)
-{
-    map.d->ref();
-    if (d->deref())
-        delete d;
-    d = map.d;
-    return *this;
-}
-
-
-int QGLCmap::size() const
-{
-    return d->colorArray.size();
-}
-
-
-int QGLCmap::maxSize() const
-{
-    return d->maxSize;
-}
-
-
-void QGLCmap::detach()
-{
-    if (d->count != 1) {
-        d->deref();
-        QGLCmapPrivate* newd = new QGLCmapPrivate;
-        newd->maxSize = d->maxSize;
-        newd->colorArray = d->colorArray;
-        newd->allocArray = d->allocArray;
-        newd->contextArray = d->contextArray;
-        newd->colorArray.detach();
-        newd->allocArray.detach();
-        newd->contextArray.detach();
-        newd->colorMap = d->colorMap;
-        d = newd;
-    }
-}
-
-
-void QGLCmap::resize(int newSize)
-{
-    if (newSize < 0 || newSize > d->maxSize) {
-        qWarning("QGLCmap::resize(): size out of range");
-        return;
-    }
-    int oldSize = size();
-    detach();
-    //if shrinking; remove the lost elems from colorMap
-    d->colorArray.resize(newSize);
-    d->allocArray.resize(newSize);
-    d->contextArray.resize(newSize);
-    if (newSize > oldSize) {
-        memset(d->allocArray.data() + oldSize, 0, newSize - oldSize);
-        memset(d->contextArray.data() + oldSize, 0, newSize - oldSize);
-    }
-}
-
-
-int QGLCmap::find(QRgb color) const
-{
-    QMap<uint,int>::ConstIterator it = d->colorMap.find(color);
-    if (it != d->colorMap.end())
-        return *it;
-    return -1;
-}
-
-
-int QGLCmap::findNearest(QRgb color) const
-{
-    int idx = find(color);
-    if (idx >= 0)
-        return idx;
-    int mapSize = size();
-    int mindist = 200000;
-    int r = qRed(color);
-    int g = qGreen(color);
-    int b = qBlue(color);
-    int rx, gx, bx, dist;
-    for (int i=0; i < mapSize; i++) {
-        if (!(d->allocArray[i] & QGLCmapPrivate::Allocated))
-            continue;
-        QRgb ci = d->colorArray[i];
-        rx = r - qRed(ci);
-        gx = g - qGreen(ci);
-        bx = b - qBlue(ci);
-        dist = rx*rx + gx*gx + bx*bx;                // calculate distance
-        if (dist < mindist) {                        // minimal?
-            mindist = dist;
-            idx = i;
-        }
-    }
-    return idx;
-}
-
-
-
-
-// Does not always allocate; returns existing c idx if found
-
-int QGLCmap::allocate(QRgb color, uint flags, quint8 context)
-{
-    int idx = find(color);
-    if (idx >= 0)
-        return idx;
-
-    int mapSize = d->colorArray.size();
-    int newIdx = d->allocArray.indexOf(QGLCmapPrivate::UnAllocated);
-
-    if (newIdx < 0) {                        // Must allocate more room
-        if (mapSize < d->maxSize) {
-            newIdx = mapSize;
-            mapSize++;
-            resize(mapSize);
-        }
-        else {
-            //# add a bool param that says what to do in case no more room -
-            // fail (-1) or return nearest?
-            return -1;
-        }
-    }
-
-    d->colorArray[newIdx] = color;
-    if (flags & QGLCmap::Reserved) {
-        d->allocArray[newIdx] = QGLCmapPrivate::Reserved;
-    }
-    else {
-        d->allocArray[newIdx] = QGLCmapPrivate::Allocated;
-        d->colorMap.insert(color, newIdx);
-    }
-    d->contextArray[newIdx] = context;
-    return newIdx;
-}
-
-
-void QGLCmap::setEntry(int idx, QRgb color, uint flags, quint8 context)
-{
-    if (idx < 0 || idx >= d->maxSize) {
-        qWarning("QGLCmap::set(): Index out of range");
-        return;
-    }
-    detach();
-    int mapSize = size();
-    if (idx >= mapSize) {
-        mapSize = idx + 1;
-        resize(mapSize);
-    }
-    d->colorArray[idx] = color;
-    if (flags & QGLCmap::Reserved) {
-        d->allocArray[idx] = QGLCmapPrivate::Reserved;
-    }
-    else {
-        d->allocArray[idx] = QGLCmapPrivate::Allocated;
-        d->colorMap.insert(color, idx);
-    }
-    d->contextArray[idx] = context;
-}
-
-
-const QRgb* QGLCmap::colors() const
-{
-    return d->colorArray.data();
-}
-
-
-
-/*****************************************************************************
-  QGLFormat Win32/WGL-specific code
- *****************************************************************************/
-
-
-void qwglError(const char* method, const char* func)
-{
-#ifndef QT_NO_DEBUG
-    char* lpMsgBuf;
-    FormatMessageA(
-                  FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
-                  0, GetLastError(),
-                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                  (char*) &lpMsgBuf, 0, 0);
-    qWarning("%s : %s failed: %s", method, func, lpMsgBuf);
-    LocalFree(lpMsgBuf);
-#else
-    Q_UNUSED(method);
-    Q_UNUSED(func);
-#endif
-}
-
-
-
-bool QGLFormat::hasOpenGL()
-{
-    return true;
-}
-
-static bool opengl32dll = false;
-
-bool QGLFormat::hasOpenGLOverlays()
-{
-    // workaround for matrox driver:
-    // make a cheap call to opengl to force loading of DLL
-    if (!opengl32dll) {
-        GLint params;
-        glGetIntegerv(GL_DEPTH_BITS, &params);
-        opengl32dll = true;
-    }
-
-    static bool checkDone = false;
-    static bool hasOl = false;
-
-    if (!checkDone) {
-        checkDone = true;
-        HDC display_dc = GetDC(0);
-        int pfiMax = DescribePixelFormat(display_dc, 0, 0, NULL);
-        PIXELFORMATDESCRIPTOR pfd;
-        for (int pfi = 1; pfi <= pfiMax; pfi++) {
-            DescribePixelFormat(display_dc, pfi, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
-            if ((pfd.bReserved & 0x0f) && (pfd.dwFlags & PFD_SUPPORT_OPENGL)) {
-                // This format has overlays/underlays
-                LAYERPLANEDESCRIPTOR lpd;
-                wglDescribeLayerPlane(display_dc, pfi, 1,
-                                       sizeof(LAYERPLANEDESCRIPTOR), &lpd);
-                if (lpd.dwFlags & LPD_SUPPORT_OPENGL) {
-                    hasOl = true;
-                    break;
-                }
-            }
-        }
-        ReleaseDC(0, display_dc);
-    }
-    return hasOl;
-}
-
-
-/*****************************************************************************
-  QGLContext Win32/WGL-specific code
- *****************************************************************************/
-
-static uchar qgl_rgb_palette_comp(int idx, uint nbits, uint shift)
-{
-    const uchar map_3_to_8[8] = {
-        0, 0111>>1, 0222>>1, 0333>>1, 0444>>1, 0555>>1, 0666>>1, 0377
-    };
-    const uchar map_2_to_8[4] = {
-        0, 0x55, 0xaa, 0xff
-    };
-    const uchar map_1_to_8[2] = {
-        0, 255
-    };
-
-    uchar val = (uchar) (idx >> shift);
-    uchar res = 0;
-    switch (nbits) {
-    case 1:
-        val &= 0x1;
-        res =  map_1_to_8[val];
-        break;
-    case 2:
-        val &= 0x3;
-        res = map_2_to_8[val];
-        break;
-    case 3:
-        val &= 0x7;
-        res = map_3_to_8[val];
-        break;
-    default:
-        res = 0;
-    }
-    return res;
-}
-
-
-static QRgb* qgl_create_rgb_palette(const PIXELFORMATDESCRIPTOR* pfd)
-{
-    if ((pfd->iPixelType != PFD_TYPE_RGBA) ||
-         !(pfd->dwFlags & PFD_NEED_PALETTE) ||
-         (pfd->cColorBits != 8))
-        return 0;
-    int numEntries = 1 << pfd->cColorBits;
-    QRgb* pal = new QRgb[numEntries];
-    for (int i = 0; i < numEntries; i++) {
-        int r = qgl_rgb_palette_comp(i, pfd->cRedBits, pfd->cRedShift);
-        int g = qgl_rgb_palette_comp(i, pfd->cGreenBits, pfd->cGreenShift);
-        int b = qgl_rgb_palette_comp(i, pfd->cBlueBits, pfd->cBlueShift);
-        pal[i] = qRgb(r, g, b);
-    }
-
-    const int syscol_indices[12] = {
-        3, 24, 27, 64, 67, 88, 173, 181, 236, 247, 164, 91
-    };
-
-    const uint syscols[20] = {
-        0x000000, 0x800000, 0x008000, 0x808000, 0x000080, 0x800080,
-        0x008080, 0xc0c0c0, 0xc0dcc0, 0xa6caf0, 0xfffbf0, 0xa0a0a4,
-        0x808080, 0xff0000, 0x00ff00, 0xffff00, 0x0000ff, 0xff00ff,
-        0x00ffff, 0xffffff
-    };        // colors #1 - #12 are not present in pal; gets added below
-
-    if ((pfd->cColorBits == 8)                                &&
-         (pfd->cRedBits   == 3) && (pfd->cRedShift   == 0)        &&
-         (pfd->cGreenBits == 3) && (pfd->cGreenShift == 3)        &&
-         (pfd->cBlueBits  == 2) && (pfd->cBlueShift  == 6)) {
-        for (int j = 0 ; j < 12 ; j++)
-            pal[syscol_indices[j]] = QRgb(syscols[j+1]);
-    }
-
-    return pal;
-}
-
-static QGLFormat pfdToQGLFormat(const PIXELFORMATDESCRIPTOR* pfd)
-{
-    QGLFormat fmt;
-    fmt.setDoubleBuffer(pfd->dwFlags & PFD_DOUBLEBUFFER);
-    fmt.setDepth(pfd->cDepthBits);
-    if (fmt.depth())
-        fmt.setDepthBufferSize(pfd->cDepthBits);
-    fmt.setRgba(pfd->iPixelType == PFD_TYPE_RGBA);
-    fmt.setRedBufferSize(pfd->cRedBits);
-    fmt.setGreenBufferSize(pfd->cGreenBits);
-    fmt.setBlueBufferSize(pfd->cBlueBits);
-    fmt.setAlpha(pfd->cAlphaBits);
-    if (fmt.alpha())
-        fmt.setAlphaBufferSize(pfd->cAlphaBits);
-    fmt.setAccum(pfd->cAccumBits);
-    if (fmt.accum())
-        fmt.setAccumBufferSize(pfd->cAccumRedBits);
-    fmt.setStencil(pfd->cStencilBits);
-    if (fmt.stencil())
-        fmt.setStencilBufferSize(pfd->cStencilBits);
-    fmt.setStereo(pfd->dwFlags & PFD_STEREO);
-    fmt.setDirectRendering((pfd->dwFlags & PFD_GENERIC_ACCELERATED) ||
-                            !(pfd->dwFlags & PFD_GENERIC_FORMAT));
-    fmt.setOverlay((pfd->bReserved & 0x0f) != 0);
-    return fmt;
-}
-
-/*
-   NB! requires a current GL context to work
-*/
-QGLFormat pfiToQGLFormat(HDC hdc, int pfi)
-{
-    QGLFormat fmt;
-    QVarLengthArray<int> iAttributes(40);
-    QVarLengthArray<int> iValues(40);
-    int i = 0;
-    bool has_sample_buffers = QGLExtensions::glExtensions() & QGLExtensions::SampleBuffers;
-
-    iAttributes[i++] = WGL_DOUBLE_BUFFER_ARB; // 0
-    iAttributes[i++] = WGL_DEPTH_BITS_ARB; // 1
-    iAttributes[i++] = WGL_PIXEL_TYPE_ARB; // 2
-    iAttributes[i++] = WGL_RED_BITS_ARB; // 3
-    iAttributes[i++] = WGL_GREEN_BITS_ARB; // 4
-    iAttributes[i++] = WGL_BLUE_BITS_ARB; // 5
-    iAttributes[i++] = WGL_ALPHA_BITS_ARB; // 6
-    iAttributes[i++] = WGL_ACCUM_BITS_ARB; // 7
-    iAttributes[i++] = WGL_STENCIL_BITS_ARB; // 8
-    iAttributes[i++] = WGL_STEREO_ARB; // 9
-    iAttributes[i++] = WGL_ACCELERATION_ARB; // 10
-    iAttributes[i++] = WGL_NUMBER_OVERLAYS_ARB; // 11
-    if (has_sample_buffers) {
-        iAttributes[i++] = WGL_SAMPLE_BUFFERS_ARB; // 12
-        iAttributes[i++] = WGL_SAMPLES_ARB; // 13
-    }
-    PFNWGLGETPIXELFORMATATTRIBIVARB wglGetPixelFormatAttribivARB =
-        (PFNWGLGETPIXELFORMATATTRIBIVARB) wglGetProcAddress("wglGetPixelFormatAttribivARB");
-
-    if (wglGetPixelFormatAttribivARB
-        && wglGetPixelFormatAttribivARB(hdc, pfi, 0, i,
-                                        iAttributes.constData(),
-                                        iValues.data()))
-    {
-        fmt.setDoubleBuffer(iValues[0]);
-        fmt.setDepth(iValues[1]);
-        if (fmt.depth())
-            fmt.setDepthBufferSize(iValues[1]);
-        fmt.setRgba(iValues[2] == WGL_TYPE_RGBA_ARB);
-        fmt.setRedBufferSize(iValues[3]);
-        fmt.setGreenBufferSize(iValues[4]);
-        fmt.setBlueBufferSize(iValues[5]);
-        fmt.setAlpha(iValues[6]);
-        if (fmt.alpha())
-            fmt.setAlphaBufferSize(iValues[6]);
-        fmt.setAccum(iValues[7]);
-        if (fmt.accum())
-            fmt.setAccumBufferSize(iValues[7]);
-        fmt.setStencil(iValues[8]);
-        if (fmt.stencil())
-            fmt.setStencilBufferSize(iValues[8]);
-        fmt.setStereo(iValues[9]);
-        if (iValues[10] == WGL_FULL_ACCELERATION_ARB)
-            fmt.setDirectRendering(true);
-        else
-            fmt.setDirectRendering(false);
-        fmt.setOverlay(iValues[11]);
-        if (has_sample_buffers) {
-            fmt.setSampleBuffers(iValues[12]);
-            if (fmt.sampleBuffers())
-                fmt.setSamples(iValues[13]);
-        }
-    }
-#if 0
-    qDebug() << "values for pfi:" << pfi;
-    qDebug() << "doublebuffer  0:" << fmt.doubleBuffer();
-    qDebug() << "depthbuffer   1:" << fmt.depthBufferSize();
-    qDebug() << "rgba          2:" << fmt.rgba();
-    qDebug() << "red size      3:" << fmt.redBufferSize();
-    qDebug() << "green size    4:" << fmt.greenBufferSize();
-    qDebug() << "blue size     5:" << fmt.blueBufferSize();
-    qDebug() << "alpha size    6:" << fmt.alphaBufferSize();
-    qDebug() << "accum size    7:" << fmt.accumBufferSize();
-    qDebug() << "stencil size  8:" << fmt.stencilBufferSize();
-    qDebug() << "stereo        9:" << fmt.stereo();
-    qDebug() << "direct       10:" << fmt.directRendering();
-    qDebug() << "has overlays 11:" << fmt.hasOverlay();
-    qDebug() << "sample buff  12:" << fmt.sampleBuffers();
-    qDebug() << "num samples  13:" << fmt.samples();
-#endif
-    return fmt;
-}
-
-
-/*
-    QGLTemporaryContext implementation
-*/
-
-Q_GUI_EXPORT const QString qt_getRegisteredWndClass();
-
-class QGLTemporaryContextPrivate
-{
-public:
-    HDC dmy_pdc;
-    HGLRC dmy_rc;
-    HDC old_dc;
-    HGLRC old_context;
-    WId dmy_id;
-};
-
-QGLTemporaryContext::QGLTemporaryContext(bool directRendering, QWidget *parent)
-    : d(new QGLTemporaryContextPrivate)
-{
-    QString windowClassName = qt_getRegisteredWndClass();
-    if (parent && !parent->internalWinId())
-        parent = parent->nativeParentWidget();
-
-    d->dmy_id = CreateWindow((const wchar_t *)windowClassName.utf16(),
-                             0, 0, 0, 0, 1, 1,
-                             parent ? parent->winId() : 0, 0, qWinAppInst(), 0);
-
-    d->dmy_pdc = GetDC(d->dmy_id);
-    PIXELFORMATDESCRIPTOR dmy_pfd;
-    memset(&dmy_pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
-    dmy_pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
-    dmy_pfd.nVersion = 1;
-    dmy_pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
-    dmy_pfd.iPixelType = PFD_TYPE_RGBA;
-    if (!directRendering)
-        dmy_pfd.dwFlags |= PFD_GENERIC_FORMAT;
-
-    int dmy_pf = ChoosePixelFormat(d->dmy_pdc, &dmy_pfd);
-    SetPixelFormat(d->dmy_pdc, dmy_pf, &dmy_pfd);
-    d->dmy_rc = wglCreateContext(d->dmy_pdc);
-    d->old_dc = wglGetCurrentDC();
-    d->old_context = wglGetCurrentContext();
-    wglMakeCurrent(d->dmy_pdc, d->dmy_rc);
-}
-
-QGLTemporaryContext::~QGLTemporaryContext()
-{
-    wglMakeCurrent(d->dmy_pdc, 0);
-    wglDeleteContext(d->dmy_rc);
-    ReleaseDC(d->dmy_id, d->dmy_pdc);
-    DestroyWindow(d->dmy_id);
-    if (d->old_dc && d->old_context)
-        wglMakeCurrent(d->old_dc, d->old_context);
-}
-
-static bool qgl_create_context(HDC hdc, QGLContextPrivate *d, QGLContextPrivate *shareContext)
-{
-    d->rc = 0;
-
-    typedef HGLRC (APIENTRYP PFNWGLCREATECONTEXTATTRIBSARB)(HDC, HGLRC, const int *);
-    PFNWGLCREATECONTEXTATTRIBSARB wglCreateContextAttribsARB =
-        (PFNWGLCREATECONTEXTATTRIBSARB) wglGetProcAddress("wglCreateContextAttribsARB");
-    if (wglCreateContextAttribsARB) {
-        int attributes[11];
-        int attribIndex = 0;
-        const int major = d->reqFormat.majorVersion();
-        const int minor = d->reqFormat.minorVersion();
-        attributes[attribIndex++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
-        attributes[attribIndex++] = major;
-        attributes[attribIndex++] = WGL_CONTEXT_MINOR_VERSION_ARB;
-        attributes[attribIndex++] = minor;
-
-        if (major >= 3 && !d->reqFormat.testOption(QGL::DeprecatedFunctions)) {
-            attributes[attribIndex++] = WGL_CONTEXT_FLAGS_ARB;
-            attributes[attribIndex++] = WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB;
-        }
-
-        if ((major == 3 && minor >= 2) || major > 3) {
-            switch (d->reqFormat.profile()) {
-            case QGLFormat::NoProfile:
-                break;
-            case QGLFormat::CoreProfile:
-                attributes[attribIndex++] = WGL_CONTEXT_PROFILE_MASK_ARB;
-                attributes[attribIndex++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
-                break;
-            case QGLFormat::CompatibilityProfile:
-                attributes[attribIndex++] = WGL_CONTEXT_PROFILE_MASK_ARB;
-                attributes[attribIndex++] = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
-                break;
-            default:
-                qWarning("QGLContext::chooseContext(): Context profile not supported.");
-                return false;
-            }
-        }
-
-        if (d->reqFormat.plane() != 0) {
-            attributes[attribIndex++] = WGL_CONTEXT_LAYER_PLANE_ARB;
-            attributes[attribIndex++] = d->reqFormat.plane();
-        }
-
-        attributes[attribIndex++] = 0; // Terminate list.
-        d->rc = wglCreateContextAttribsARB(hdc, shareContext && shareContext->valid
-                                           ? shareContext->rc : 0, attributes);
-        if (d->rc) {
-            if (shareContext)
-                shareContext->sharing = d->sharing = true;
-            return true;
-        }
-    }
-
-    d->rc = wglCreateLayerContext(hdc, d->reqFormat.plane());
-    if (d->rc && shareContext && shareContext->valid)
-        shareContext->sharing = d->sharing = wglShareLists(shareContext->rc, d->rc);
-    return d->rc != 0;
-}
-
-void QGLContextPrivate::updateFormatVersion()
-{
-    const GLubyte *s = glGetString(GL_VERSION);
-
-    if (!(s && s[0] >= '0' && s[0] <= '9' && s[1] == '.' && s[2] >= '0' && s[2] <= '9')) {
-        if (!s)
-            qWarning("QGLContext::chooseContext(): OpenGL version string is null.");
-        else
-            qWarning("QGLContext::chooseContext(): Unexpected OpenGL version string format.");
-        glFormat.setVersion(0, 0);
-        glFormat.setProfile(QGLFormat::NoProfile);
-        glFormat.setOption(QGL::DeprecatedFunctions);
-        return;
-    }
-
-    int major = s[0] - '0';
-    int minor = s[2] - '0';
-    glFormat.setVersion(major, minor);
-
-    if (major < 3) {
-        glFormat.setProfile(QGLFormat::NoProfile);
-        glFormat.setOption(QGL::DeprecatedFunctions);
-    } else {
-        GLint value = 0;
-        if (major > 3 || minor >= 2)
-            glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &value);
-
-        switch (value) {
-        case WGL_CONTEXT_CORE_PROFILE_BIT_ARB:
-            glFormat.setProfile(QGLFormat::CoreProfile);
-            break;
-        case WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB:
-            glFormat.setProfile(QGLFormat::CompatibilityProfile);
-            break;
-        default:
-            glFormat.setProfile(QGLFormat::NoProfile);
-            break;
-        }
-
-        glGetIntegerv(GL_CONTEXT_FLAGS, &value);
-        if (value & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT)
-            glFormat.setOption(QGL::NoDeprecatedFunctions);
-        else
-            glFormat.setOption(QGL::DeprecatedFunctions);
-    }
-}
-
-bool QGLContext::chooseContext(const QGLContext* shareContext)
-{
-    QGLContextPrivate *share = shareContext ? const_cast<QGLContext *>(shareContext)->d_func() : 0;
-
-    Q_D(QGLContext);
-    // workaround for matrox driver:
-    // make a cheap call to opengl to force loading of DLL
-    if (!opengl32dll) {
-        GLint params;
-        glGetIntegerv(GL_DEPTH_BITS, &params);
-        opengl32dll = true;
-    }
-
-    bool result = true;
-    HDC myDc;
-    QWidget *widget = 0;
-
-    if (deviceIsPixmap()) {
-        if (d->glFormat.plane())
-            return false;                // Pixmaps can't have overlay
-        d->win = 0;
-        HDC display_dc = GetDC(0);
-        myDc = d->hbitmap_hdc = CreateCompatibleDC(display_dc);
-        QPixmap *px = static_cast<QPixmap *>(d->paintDevice);
-
-        BITMAPINFO bmi;
-        memset(&bmi, 0, sizeof(bmi));
-        bmi.bmiHeader.biSize        = sizeof(BITMAPINFOHEADER);
-        bmi.bmiHeader.biWidth       = px->width();
-        bmi.bmiHeader.biHeight      = px->height();
-        bmi.bmiHeader.biPlanes      = 1;
-        bmi.bmiHeader.biBitCount    = 32;
-        bmi.bmiHeader.biCompression = BI_RGB;
-        d->hbitmap = CreateDIBSection(display_dc, &bmi, DIB_RGB_COLORS, 0, 0, 0);
-        SelectObject(myDc, d->hbitmap);
-        ReleaseDC(0, display_dc);
-    } else {
-        widget = static_cast<QWidget *>(d->paintDevice);
-        d->win = widget->winId();
-        myDc = GetDC(d->win);
-    }
-
-    // NB! the QGLTemporaryContext object is needed for the
-    // wglGetProcAddress() calls to succeed and are absolutely
-    // necessary - don't remove!
-    QGLTemporaryContext tmp_ctx(d->glFormat.directRendering(), widget);
-
-    if (!myDc) {
-        qWarning("QGLContext::chooseContext(): Paint device cannot be null");
-        result = false;
-        goto end;
-    }
-
-    if (d->glFormat.plane()) {
-        d->pixelFormatId = ((QGLWidget*)d->paintDevice)->context()->d_func()->pixelFormatId;
-        if (!d->pixelFormatId) {                // I.e. the glwidget is invalid
-            qWarning("QGLContext::chooseContext(): Cannot create overlay context for invalid widget");
-            result = false;
-            goto end;
-        }
-
-        if (!qgl_create_context(myDc, d, share)) {
-            qwglError("QGLContext::chooseContext()", "CreateLayerContext");
-            result = false;
-            goto end;
-        }
-
-        LAYERPLANEDESCRIPTOR lpfd;
-        wglDescribeLayerPlane(myDc, d->pixelFormatId, d->glFormat.plane(), sizeof(LAYERPLANEDESCRIPTOR), &lpfd);
-        d->glFormat.setDoubleBuffer(lpfd.dwFlags & LPD_DOUBLEBUFFER);
-        d->glFormat.setDepth(lpfd.cDepthBits);
-        d->glFormat.setRgba(lpfd.iPixelType == PFD_TYPE_RGBA);
-        if (d->glFormat.rgba()) {
-            if (d->glFormat.redBufferSize() != -1)
-                d->glFormat.setRedBufferSize(lpfd.cRedBits);
-            if (d->glFormat.greenBufferSize() != -1)
-                d->glFormat.setGreenBufferSize(lpfd.cGreenBits);
-            if (d->glFormat.blueBufferSize() != -1)
-                d->glFormat.setBlueBufferSize(lpfd.cBlueBits);
-        }
-        d->glFormat.setAlpha(lpfd.cAlphaBits);
-        d->glFormat.setAccum(lpfd.cAccumBits);
-        d->glFormat.setStencil(lpfd.cStencilBits);
-        d->glFormat.setStereo(lpfd.dwFlags & LPD_STEREO);
-        d->glFormat.setDirectRendering(false);
-        if (d->glFormat.depth())
-            d->glFormat.setDepthBufferSize(lpfd.cDepthBits);
-        if (d->glFormat.alpha())
-            d->glFormat.setAlphaBufferSize(lpfd.cAlphaBits);
-        if (d->glFormat.accum())
-            d->glFormat.setAccumBufferSize(lpfd.cAccumRedBits);
-        if (d->glFormat.stencil())
-            d->glFormat.setStencilBufferSize(lpfd.cStencilBits);
-
-        if (d->glFormat.rgba()) {
-            if (lpfd.dwFlags & LPD_TRANSPARENT)
-                d->transpColor = QColor(lpfd.crTransparent & 0xff,
-                                        (lpfd.crTransparent >> 8) & 0xff,
-                                        (lpfd.crTransparent >> 16) & 0xff);
-            else
-                d->transpColor = QColor(0, 0, 0);
-        }
-        else {
-            if (lpfd.dwFlags & LPD_TRANSPARENT)
-                d->transpColor = QColor(qRgb(1, 2, 3));//, lpfd.crTransparent);
-            else
-                d->transpColor = QColor(qRgb(1, 2, 3));//, 0);
-
-            d->cmap = new QGLCmap(1 << lpfd.cColorBits);
-            d->cmap->setEntry(lpfd.crTransparent, qRgb(1, 2, 3));//, QGLCmap::Reserved);
-        }
-    } else {
-        PIXELFORMATDESCRIPTOR pfd;
-        PIXELFORMATDESCRIPTOR realPfd;
-        d->pixelFormatId = choosePixelFormat(&pfd, myDc);
-        if (d->pixelFormatId == 0) {
-            qwglError("QGLContext::chooseContext()", "ChoosePixelFormat");
-            result = false;
-            goto end;
-        }
-
-        bool overlayRequested = d->glFormat.hasOverlay();
-        DescribePixelFormat(myDc, d->pixelFormatId, sizeof(PIXELFORMATDESCRIPTOR), &realPfd);
-
-        if (!deviceIsPixmap() && wglGetProcAddress("wglGetPixelFormatAttribivARB"))
-            d->glFormat = pfiToQGLFormat(myDc, d->pixelFormatId);
-        else
-            d->glFormat = pfdToQGLFormat(&realPfd);
-
-        d->glFormat.setOverlay(d->glFormat.hasOverlay() && overlayRequested);
-
-        if (deviceIsPixmap() && !(realPfd.dwFlags & PFD_DRAW_TO_BITMAP)) {
-            qWarning("QGLContext::chooseContext(): Failed to get pixmap rendering context.");
-            result = false;
-            goto end;
-        }
-
-        if (deviceIsPixmap() &&
-            (((QPixmap*)d->paintDevice)->depth() != realPfd.cColorBits)) {
-            qWarning("QGLContext::chooseContext(): Failed to get pixmap rendering context of suitable depth.");
-            result = false;
-            goto end;
-        }
-
-        if (!SetPixelFormat(myDc, d->pixelFormatId, &realPfd)) {
-            qwglError("QGLContext::chooseContext()", "SetPixelFormat");
-            result = false;
-            goto end;
-        }
-
-        if (!qgl_create_context(myDc, d, share)) {
-            qwglError("QGLContext::chooseContext()", "wglCreateContext");
-            result = false;
-            goto end;
-        }
-
-        if(!deviceIsPixmap()) {
-            QRgb* pal = qgl_create_rgb_palette(&realPfd);
-            if (pal) {
-                QGLColormap cmap;
-                cmap.setEntries(256, pal);
-                ((QGLWidget*)d->paintDevice)->setColormap(cmap);
-                delete[] pal;
-            }
-        }
-    }
-
-end:
-    // vblanking
-    wglMakeCurrent(myDc, d->rc);
-    if (d->rc)
-        d->updateFormatVersion();
-
-    typedef BOOL (APIENTRYP PFNWGLSWAPINTERVALEXT) (int interval);
-    typedef int (APIENTRYP PFNWGLGETSWAPINTERVALEXT) (void);
-    PFNWGLSWAPINTERVALEXT wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXT) wglGetProcAddress("wglSwapIntervalEXT");
-    PFNWGLGETSWAPINTERVALEXT wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXT) wglGetProcAddress("wglGetSwapIntervalEXT");
-    if (wglSwapIntervalEXT && wglGetSwapIntervalEXT) {
-        if (d->reqFormat.swapInterval() != -1)
-            wglSwapIntervalEXT(d->reqFormat.swapInterval());
-        d->glFormat.setSwapInterval(wglGetSwapIntervalEXT());
-    }
-
-    if (d->win)
-        ReleaseDC(d->win, myDc);
-    return result;
-}
-
-
-
-static bool qLogEq(bool a, bool b)
-{
-    return (((!a) && (!b)) || (a && b));
-}
-
-/*
-  See qgl.cpp for qdoc comment.
- */
-int QGLContext::choosePixelFormat(void* dummyPfd, HDC pdc)
-{
-    Q_D(QGLContext);
-    // workaround for matrox driver:
-    // make a cheap call to opengl to force loading of DLL
-    if (!opengl32dll) {
-        GLint params;
-        glGetIntegerv(GL_DEPTH_BITS, &params);
-        opengl32dll = true;
-    }
-
-    PFNWGLCHOOSEPIXELFORMATARB wglChoosePixelFormatARB =
-        (PFNWGLCHOOSEPIXELFORMATARB) wglGetProcAddress("wglChoosePixelFormatARB");
-    int chosenPfi = 0;
-    if (!deviceIsPixmap() && wglChoosePixelFormatARB) {
-        bool valid;
-        int pixelFormat = 0;
-        uint numFormats = 0;
-        QVarLengthArray<int> iAttributes(40);
-        int i = 0;
-        iAttributes[i++] = WGL_ACCELERATION_ARB;
-        if (d->glFormat.directRendering())
-            iAttributes[i++] = WGL_FULL_ACCELERATION_ARB;
-        else
-            iAttributes[i++] = WGL_NO_ACCELERATION_ARB;
-        iAttributes[i++] = WGL_SUPPORT_OPENGL_ARB;
-        iAttributes[i++] = TRUE;
-        iAttributes[i++] = WGL_DRAW_TO_WINDOW_ARB;
-        iAttributes[i++] = TRUE;
-        iAttributes[i++] = WGL_COLOR_BITS_ARB;
-        iAttributes[i++] = 24;
-        iAttributes[i++] = WGL_DOUBLE_BUFFER_ARB;
-        iAttributes[i++] = d->glFormat.doubleBuffer();
-        if (d->glFormat.stereo()) {
-            iAttributes[i++] = WGL_STEREO_ARB;
-            iAttributes[i++] = TRUE;
-        }
-        if (d->glFormat.depth()) {
-            iAttributes[i++] = WGL_DEPTH_BITS_ARB;
-            iAttributes[i++] = d->glFormat.depthBufferSize() == -1 ? 24 : d->glFormat.depthBufferSize();
-        }
-        iAttributes[i++] = WGL_PIXEL_TYPE_ARB;
-        if (d->glFormat.rgba()) {
-            iAttributes[i++] = WGL_TYPE_RGBA_ARB;
-            if (d->glFormat.redBufferSize() != -1) {
-                iAttributes[i++] = WGL_RED_BITS_ARB;
-                iAttributes[i++] = d->glFormat.redBufferSize();
-            }
-            if (d->glFormat.greenBufferSize() != -1) {
-                iAttributes[i++] = WGL_GREEN_BITS_ARB;
-                iAttributes[i++] = d->glFormat.greenBufferSize();
-            }
-            if (d->glFormat.blueBufferSize() != -1) {
-                iAttributes[i++] = WGL_BLUE_BITS_ARB;
-                iAttributes[i++] = d->glFormat.blueBufferSize();
-            }
-        } else {
-            iAttributes[i++] = WGL_TYPE_COLORINDEX_ARB;
-        }
-        if (d->glFormat.alpha()) {
-            iAttributes[i++] = WGL_ALPHA_BITS_ARB;
-            iAttributes[i++] = d->glFormat.alphaBufferSize() == -1 ? 8 : d->glFormat.alphaBufferSize();
-        }
-        if (d->glFormat.accum()) {
-            iAttributes[i++] = WGL_ACCUM_BITS_ARB;
-            iAttributes[i++] = d->glFormat.accumBufferSize() == -1 ? 16 : d->glFormat.accumBufferSize();
-        }
-        if (d->glFormat.stencil()) {
-            iAttributes[i++] = WGL_STENCIL_BITS_ARB;
-            iAttributes[i++] = d->glFormat.stencilBufferSize() == -1 ? 8 : d->glFormat.stencilBufferSize();
-        }
-        if (d->glFormat.hasOverlay()) {
-            iAttributes[i++] = WGL_NUMBER_OVERLAYS_ARB;
-            iAttributes[i++] = 1;
-        }
-        int si = 0;
-        bool trySampleBuffers = QGLExtensions::glExtensions() & QGLExtensions::SampleBuffers;
-        if (trySampleBuffers && d->glFormat.sampleBuffers()) {
-            iAttributes[i++] = WGL_SAMPLE_BUFFERS_ARB;
-            iAttributes[i++] = TRUE;
-            iAttributes[i++] = WGL_SAMPLES_ARB;
-            si = i;
-            iAttributes[i++] = d->glFormat.samples() == -1 ? 4 : d->glFormat.samples();
-        }
-        iAttributes[i] = 0;
-
-        do {
-            valid = wglChoosePixelFormatARB(pdc, iAttributes.constData(), 0, 1,
-                                            &pixelFormat, &numFormats);
-            if (trySampleBuffers  && (!valid || numFormats < 1) && d->glFormat.sampleBuffers())
-                iAttributes[si] /= 2; // try different no. samples - we aim for the best one
-            else
-                break;
-        } while ((!valid || numFormats < 1) && iAttributes[si] > 1);
-        chosenPfi = pixelFormat;
-    }
-
-    if (!chosenPfi) { // fallback if wglChoosePixelFormatARB() failed
-        int pmDepth = deviceIsPixmap() ? ((QPixmap*)d->paintDevice)->depth() : 0;
-        PIXELFORMATDESCRIPTOR* p = (PIXELFORMATDESCRIPTOR*)dummyPfd;
-        memset(p, 0, sizeof(PIXELFORMATDESCRIPTOR));
-        p->nSize = sizeof(PIXELFORMATDESCRIPTOR);
-        p->nVersion = 1;
-        p->dwFlags  = PFD_SUPPORT_OPENGL;
-        if (deviceIsPixmap())
-            p->dwFlags |= PFD_DRAW_TO_BITMAP;
-        else
-            p->dwFlags |= PFD_DRAW_TO_WINDOW;
-        if (!d->glFormat.directRendering())
-            p->dwFlags |= PFD_GENERIC_FORMAT;
-        if (d->glFormat.doubleBuffer() && !deviceIsPixmap())
-            p->dwFlags |= PFD_DOUBLEBUFFER;
-        if (d->glFormat.stereo())
-            p->dwFlags |= PFD_STEREO;
-        if (d->glFormat.depth())
-            p->cDepthBits = d->glFormat.depthBufferSize() == -1 ? 32 : d->glFormat.depthBufferSize();
-        else
-            p->dwFlags |= PFD_DEPTH_DONTCARE;
-        if (d->glFormat.rgba()) {
-            p->iPixelType = PFD_TYPE_RGBA;
-            if (d->glFormat.redBufferSize() != -1)
-                p->cRedBits = d->glFormat.redBufferSize();
-            if (d->glFormat.greenBufferSize() != -1)
-                p->cGreenBits = d->glFormat.greenBufferSize();
-            if (d->glFormat.blueBufferSize() != -1)
-                p->cBlueBits = d->glFormat.blueBufferSize();
-            if (deviceIsPixmap())
-                p->cColorBits = pmDepth;
-            else
-                p->cColorBits = 32;
-        } else {
-            p->iPixelType = PFD_TYPE_COLORINDEX;
-            p->cColorBits = 8;
-        }
-        if (d->glFormat.alpha())
-            p->cAlphaBits = d->glFormat.alphaBufferSize() == -1 ? 8 : d->glFormat.alphaBufferSize();
-        if (d->glFormat.accum()) {
-            p->cAccumRedBits = p->cAccumGreenBits = p->cAccumBlueBits = p->cAccumAlphaBits =
-                               d->glFormat.accumBufferSize() == -1 ? 16 : d->glFormat.accumBufferSize();
-        }
-        if (d->glFormat.stencil())
-            p->cStencilBits = d->glFormat.stencilBufferSize() == -1 ? 8 : d->glFormat.stencilBufferSize();
-        p->iLayerType = PFD_MAIN_PLANE;
-        chosenPfi = ChoosePixelFormat(pdc, p);
-
-        if (!chosenPfi)
-            qErrnoWarning("QGLContext: ChoosePixelFormat failed");
-
-        // Since the GDI function ChoosePixelFormat() does not handle
-        // overlay and direct-rendering requests, we must roll our own here
-
-        bool doSearch = chosenPfi <= 0;
-        PIXELFORMATDESCRIPTOR pfd;
-        QGLFormat fmt;
-        if (!doSearch) {
-            DescribePixelFormat(pdc, chosenPfi, sizeof(PIXELFORMATDESCRIPTOR),
-                                &pfd);
-            fmt = pfdToQGLFormat(&pfd);
-            if (d->glFormat.hasOverlay() && !fmt.hasOverlay())
-                doSearch = true;
-            else if (!qLogEq(d->glFormat.directRendering(), fmt.directRendering()))
-                doSearch = true;
-            else if (deviceIsPixmap() && (!(pfd.dwFlags & PFD_DRAW_TO_BITMAP) ||
-                                          pfd.cColorBits != pmDepth))
-                doSearch = true;
-            else if (!deviceIsPixmap() && !(pfd.dwFlags & PFD_DRAW_TO_WINDOW))
-                doSearch = true;
-            else if (!qLogEq(d->glFormat.rgba(), fmt.rgba()))
-                doSearch = true;
-        }
-
-        if (doSearch) {
-            int pfiMax = DescribePixelFormat(pdc, 0, 0, NULL);
-            int bestScore = -1;
-            int bestPfi = -1;
-            for (int pfi = 1; pfi <= pfiMax; pfi++) {
-                DescribePixelFormat(pdc, pfi, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
-                if (!(pfd.dwFlags & PFD_SUPPORT_OPENGL))
-                    continue;
-                if (deviceIsPixmap() && (!(pfd.dwFlags & PFD_DRAW_TO_BITMAP) ||
-                                         pfd.cColorBits != pmDepth))
-                    continue;
-                if (!deviceIsPixmap() && !(pfd.dwFlags & PFD_DRAW_TO_WINDOW))
-                    continue;
-
-                fmt = pfdToQGLFormat(&pfd);
-                if (d->glFormat.hasOverlay() && !fmt.hasOverlay())
-                    continue;
-
-                int score = pfd.cColorBits;
-                if (qLogEq(d->glFormat.depth(), fmt.depth()))
-                    score += pfd.cDepthBits;
-                if (qLogEq(d->glFormat.alpha(), fmt.alpha()))
-                    score += pfd.cAlphaBits;
-                if (qLogEq(d->glFormat.accum(), fmt.accum()))
-                    score += pfd.cAccumBits;
-                if (qLogEq(d->glFormat.stencil(), fmt.stencil()))
-                    score += pfd.cStencilBits;
-                if (qLogEq(d->glFormat.doubleBuffer(), fmt.doubleBuffer()))
-                    score += 1000;
-                if (qLogEq(d->glFormat.stereo(), fmt.stereo()))
-                    score += 2000;
-                if (qLogEq(d->glFormat.directRendering(), fmt.directRendering()))
-                    score += 4000;
-                if (qLogEq(d->glFormat.rgba(), fmt.rgba()))
-                    score += 8000;
-                if (score > bestScore) {
-                    bestScore = score;
-                    bestPfi = pfi;
-                }
-            }
-
-            if (bestPfi > 0)
-                chosenPfi = bestPfi;
-        }
-    }
-    return chosenPfi;
-}
-
-
-
-void QGLContext::reset()
-{
-    Q_D(QGLContext);
-    // workaround for matrox driver:
-    // make a cheap call to opengl to force loading of DLL
-    if (!opengl32dll) {
-        GLint params;
-        glGetIntegerv(GL_DEPTH_BITS, &params);
-        opengl32dll = true;
-    }
-
-    if (!d->valid)
-        return;
-    d->cleanup();
-    doneCurrent();
-    if (d->rc)
-        wglDeleteContext(d->rc);
-    d->rc  = 0;
-    if (d->win && d->dc)
-        ReleaseDC(d->win, d->dc);
-    if (deviceIsPixmap()) {
-        DeleteDC(d->hbitmap_hdc);
-        DeleteObject(d->hbitmap);
-        d->hbitmap_hdc = 0;
-        d->hbitmap = 0;
-    }
-    d->dc  = 0;
-    d->win = 0;
-    d->threadId = 0;
-    d->pixelFormatId = 0;
-    d->sharing = false;
-    d->valid = false;
-    d->transpColor = QColor();
-    delete d->cmap;
-    d->cmap = 0;
-    d->initDone = false;
-    QGLContextGroup::removeShare(this);
-}
-
-//
-// NOTE: In a multi-threaded environment, each thread has a current
-// context. If we want to make this code thread-safe, we probably
-// have to use TLS (thread local storage) for keeping current contexts.
-//
-
-void QGLContext::makeCurrent()
-{
-    Q_D(QGLContext);
-    if (d->rc == wglGetCurrentContext() || !d->valid)       // already current
-        return;
-
-    if (d->win && (!d->dc || d->threadId != QThread::currentThreadId())) {
-        d->dc = GetDC(d->win);
-        d->threadId = QThread::currentThreadId();
-        if (!d->dc) {
-            qwglError("QGLContext::makeCurrent()", "GetDC()");
-            return;
-        }
-    } else if (deviceIsPixmap()) {
-        d->dc = d->hbitmap_hdc;
-    }
-
-    HPALETTE hpal = QColormap::hPal();
-    if (hpal) {
-        SelectPalette(d->dc, hpal, FALSE);
-        RealizePalette(d->dc);
-    }
-    if (d->glFormat.plane()) {
-        wglRealizeLayerPalette(d->dc, d->glFormat.plane(), TRUE);
-    }
-
-    if (wglMakeCurrent(d->dc, d->rc)) {
-        QGLContextPrivate::setCurrentContext(this);
-    } else {
-        qwglError("QGLContext::makeCurrent()", "wglMakeCurrent");
-    }
-}
-
-
-void QGLContext::doneCurrent()
-{
-    Q_D(QGLContext);
-    wglMakeCurrent(0, 0);
-    QGLContextPrivate::setCurrentContext(0);
-    if (deviceIsPixmap() && d->hbitmap) {
-        QPixmap *pm = static_cast<QPixmap *>(d->paintDevice);
-        *pm = QPixmap::fromWinHBITMAP(d->hbitmap);
-    }
-    if (d->win && d->dc) {
-        ReleaseDC(d->win, d->dc);
-        d->dc = 0;
-        d->threadId = 0;
-    }
-}
-
-void QGLContext::swapBuffers() const
-{
-    Q_D(const QGLContext);
-    if (d->dc && d->glFormat.doubleBuffer() && !deviceIsPixmap()) {
-        if (d->glFormat.plane())
-            wglSwapLayerBuffers(d->dc, WGL_SWAP_OVERLAY1);
-        else {
-            if (d->glFormat.hasOverlay())
-                wglSwapLayerBuffers(d->dc, WGL_SWAP_MAIN_PLANE);
-            else
-                SwapBuffers(d->dc);
-        }
-    }
-}
-
-
-QColor QGLContext::overlayTransparentColor() const
-{
-    return d_func()->transpColor;
-}
-
-
-uint QGLContext::colorIndex(const QColor& c) const
-{
-    Q_D(const QGLContext);
-    if (!isValid())
-        return 0;
-    if (d->cmap) {
-        int idx = d->cmap->find(c.rgb());
-        if (idx >= 0)
-            return idx;
-        if (d->dc && d->glFormat.plane()) {
-            idx = d->cmap->allocate(c.rgb());
-            if (idx >= 0) {
-                COLORREF r = RGB(qRed(c.rgb()),qGreen(c.rgb()),qBlue(c.rgb()));
-                wglSetLayerPaletteEntries(d->dc, d->glFormat.plane(), idx, 1, &r);
-                wglRealizeLayerPalette(d->dc, d->glFormat.plane(), TRUE);
-                return idx;
-            }
-        }
-        return d->cmap->findNearest(c.rgb());
-    }
-    QColormap cmap = QColormap::instance();
-    return cmap.pixel(c) & 0x00ffffff; // Assumes standard palette
-}
-
-void QGLContext::generateFontDisplayLists(const QFont & fnt, int listBase)
-{
-    if (!isValid())
-        return;
-
-    HDC display_dc = GetDC(0);
-    HDC tmp_dc = CreateCompatibleDC(display_dc);
-    HGDIOBJ old_font = SelectObject(tmp_dc, fnt.handle());
-
-    ReleaseDC(0, display_dc);
-
-    if (!wglUseFontBitmaps(tmp_dc, 0, 256, listBase))
-        qWarning("QGLContext::generateFontDisplayLists: Could not generate display lists for font '%s'", fnt.family().toLatin1().data());
-
-    SelectObject(tmp_dc, old_font);
-    DeleteDC(tmp_dc);
-}
-
-void *QGLContext::getProcAddress(const QString &proc) const
-{
-    return (void *)wglGetProcAddress(proc.toLatin1());
-}
-
-/*****************************************************************************
-  QGLWidget Win32/WGL-specific code
- *****************************************************************************/
-
-void QGLWidgetPrivate::init(QGLContext *ctx, const QGLWidget* shareWidget)
-{
-    Q_Q(QGLWidget);
-    olcx = 0;
-    initContext(ctx, shareWidget);
-
-    if (q->isValid() && q->context()->format().hasOverlay()) {
-        olcx = new QGLContext(QGLFormat::defaultOverlayFormat(), q);
-        if (!olcx->create(shareWidget ? shareWidget->overlayContext() : 0)) {
-            delete olcx;
-            olcx = 0;
-            glcx->d_func()->glFormat.setOverlay(false);
-        }
-    } else {
-        olcx = 0;
-    }
-}
-
-/*\internal
-  Store color values in the given colormap.
-*/
-static void qStoreColors(HPALETTE cmap, const QGLColormap & cols)
-{
-    QRgb color;
-    PALETTEENTRY pe;
-
-    for (int i = 0; i < cols.size(); i++) {
-        color = cols.entryRgb(i);
-        pe.peRed   = qRed(color);
-        pe.peGreen = qGreen(color);
-        pe.peBlue  = qBlue(color);
-        pe.peFlags = 0;
-
-        SetPaletteEntries(cmap, i, 1, &pe);
-    }
-}
-
-void QGLWidgetPrivate::updateColormap()
-{
-    Q_Q(QGLWidget);
-    if (!cmap.handle())
-        return;
-    HDC hdc = GetDC(q->winId());
-    SelectPalette(hdc, (HPALETTE) cmap.handle(), TRUE);
-    qStoreColors((HPALETTE) cmap.handle(), cmap);
-    RealizePalette(hdc);
-    ReleaseDC(q->winId(), hdc);
-}
-
-void QGLWidget::setMouseTracking(bool enable)
-{
-    QWidget::setMouseTracking(enable);
-}
-
-
-void QGLWidget::resizeEvent(QResizeEvent *)
-{
-    Q_D(QGLWidget);
-    if (!isValid())
-        return;
-    makeCurrent();
-    if (!d->glcx->initialized())
-        glInit();
-    resizeGL(width(), height());
-    if (d->olcx) {
-        makeOverlayCurrent();
-        resizeOverlayGL(width(), height());
-    }
-}
-
-
-const QGLContext* QGLWidget::overlayContext() const
-{
-    return d_func()->olcx;
-}
-
-
-void QGLWidget::makeOverlayCurrent()
-{
-    Q_D(QGLWidget);
-    if (d->olcx) {
-        d->olcx->makeCurrent();
-        if (!d->olcx->initialized()) {
-            initializeOverlayGL();
-            d->olcx->setInitialized(true);
-        }
-    }
-}
-
-
-void QGLWidget::updateOverlayGL()
-{
-    Q_D(QGLWidget);
-    if (d->olcx) {
-        makeOverlayCurrent();
-        paintOverlayGL();
-        if (d->olcx->format().doubleBuffer()) {
-            if (d->autoSwap)
-                d->olcx->swapBuffers();
-        }
-        else {
-            glFlush();
-        }
-    }
-}
-
-
-void QGLWidget::setContext(QGLContext *context,
-                            const QGLContext* shareContext,
-                            bool deleteOldContext)
-{
-    Q_D(QGLWidget);
-    if (context == 0) {
-        qWarning("QGLWidget::setContext: Cannot set null context");
-        return;
-    }
-    if (!context->deviceIsPixmap() && context->device() != this) {
-        qWarning("QGLWidget::setContext: Context must refer to this widget");
-        return;
-    }
-
-    if (d->glcx)
-        d->glcx->doneCurrent();
-    QGLContext* oldcx = d->glcx;
-    d->glcx = context;
-
-    bool doShow = false;
-    if (oldcx && oldcx->d_func()->win == winId() && !d->glcx->deviceIsPixmap()) {
-        // We already have a context and must therefore create a new
-        // window since Windows does not permit setting a new OpenGL
-        // context for a window that already has one set.
-        doShow = isVisible();
-        QWidget *pW = static_cast<QWidget *>(parent());
-        QPoint pos = geometry().topLeft();
-        setParent(pW, windowFlags());
-        move(pos);
-    }
-
-    if (!d->glcx->isValid()) {
-        bool wasSharing = shareContext || (oldcx && oldcx->isSharing());
-        d->glcx->create(shareContext ? shareContext : oldcx);
-        // the above is a trick to keep disp lists etc when a
-        // QGLWidget has been reparented, so remove the sharing
-        // flag if we don't actually have a sharing context.
-        if (!wasSharing)
-            d->glcx->d_ptr->sharing = false;
-    }
-
-    if (deleteOldContext)
-        delete oldcx;
-
-    if (doShow)
-        show();
-}
-
-
-bool QGLWidgetPrivate::renderCxPm(QPixmap*)
-{
-    return false;
-}
-
-void QGLWidgetPrivate::cleanupColormaps()
-{
-    Q_Q(QGLWidget);
-    if (cmap.handle()) {
-        HDC hdc = GetDC(q->winId());
-        SelectPalette(hdc, (HPALETTE) GetStockObject(DEFAULT_PALETTE), FALSE);
-        DeleteObject((HPALETTE) cmap.handle());
-        ReleaseDC(q->winId(), hdc);
-        cmap.setHandle(0);
-    }
-    return;
-}
-
-const QGLColormap & QGLWidget::colormap() const
-{
-    return d_func()->cmap;
-}
-
-void QGLWidget::setColormap(const QGLColormap & c)
-{
-    Q_D(QGLWidget);
-    d->cmap = c;
-
-    if (d->cmap.handle()) { // already have an allocated cmap
-        d->updateColormap();
-    } else {
-        LOGPALETTE *lpal = (LOGPALETTE *) malloc(sizeof(LOGPALETTE)
-                                                 +c.size()*sizeof(PALETTEENTRY));
-        lpal->palVersion    = 0x300;
-        lpal->palNumEntries = c.size();
-        d->cmap.setHandle(CreatePalette(lpal));
-        free(lpal);
-        d->updateColormap();
-    }
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qgl_wince.cpp b/src/opengl/qgl_wince.cpp
deleted file mode 100644 (file)
index 10360d5..0000000
+++ /dev/null
@@ -1,635 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <qgl.h>
-#include <qlist.h>
-#include <qmap.h>
-#include <qpixmap.h>
-#include <qevent.h>
-#include <qgl_p.h>
-#include <qcolormap.h>
-#include <qdebug.h>
-#include <qapplication.h>
-#include <qdesktopwidget>
-
-#include <windows.h>
-
-#include <qeglproperties_p.h>
-#include <qeglcontext_p.h>
-#include <qgl_egl_p.h>
-
-
-QT_BEGIN_NAMESPACE
-
-
-
-class QGLCmapPrivate
-{
-public:
-    QGLCmapPrivate() : count(1) { }
-    void ref()                { ++count; }
-    bool deref()        { return !--count; }
-    uint count;
-
-    enum AllocState{ UnAllocated = 0, Allocated = 0x01, Reserved = 0x02 };
-
-    int maxSize;
-    QVector<uint> colorArray;
-    QVector<quint8> allocArray;
-    QVector<quint8> contextArray;
-    QMap<uint,int> colorMap;
-};
-
-/*****************************************************************************
-  QColorMap class - temporarily here, until it is ready for prime time
- *****************************************************************************/
-
-/****************************************************************************
-**
-** Definition of QColorMap class
-**
-****************************************************************************/
-
-#ifndef QGLCMAP_H
-#define QGLCMAP_H
-
-#include <qcolor.h>
-
-/*
-    QGLTemporaryContext implementation
-*/
-
-class QGLTemporaryContextPrivate
-{
-public:
-    QGLWidget *widget;
-};
-
-QGLTemporaryContext::QGLTemporaryContext(bool, QWidget *)
-    : d(new QGLTemporaryContextPrivate)
-{
-    d->widget = new QGLWidget;
-    d->widget->makeCurrent();
-}
-
-QGLTemporaryContext::~QGLTemporaryContext()
-{
-    delete d->widget;
-}
-
-/*****************************************************************************
-  QGLFormat Win32/WGL-specific code
- *****************************************************************************/
-
-static bool opengl32dll = false;
-
-bool QGLFormat::hasOpenGLOverlays()
-{
-    return false; // ###
-}
-
-
-bool QGLContext::chooseContext(const QGLContext* shareContext)
-{
-        Q_D(QGLContext);
-
-    // Validate the device.
-    if (!device())
-        return false;
-    int devType = device()->devType();
-    if (devType != QInternal::Pixmap && devType != QInternal::Image && devType != QInternal::Widget) {
-        qWarning("QGLContext::chooseContext(): Cannot create QGLContext's for paint device type %d", devType);
-        return false;
-    }
-
-    // Get the display and initialize it.
-    d->eglContext = new QEglContext();
-    d->ownsEglContext = true;
-    d->eglContext->setApi(QEgl::OpenGL);
-
-    // Construct the configuration we need for this surface.
-    QEglProperties configProps;
-    qt_eglproperties_set_glformat(configProps, d->glFormat);
-    configProps.setDeviceType(devType);
-    configProps.setPaintDeviceFormat(device());
-    configProps.setRenderableType(QEgl::OpenGL);
-
-    // Search for a matching configuration, reducing the complexity
-    // each time until we get something that matches.
-    if (!d->eglContext->chooseConfig(configProps)) {
-        delete d->eglContext;
-        d->eglContext = 0;
-        return false;
-    }
-
-    // Inform the higher layers about the actual format properties.
-    qt_glformat_from_eglconfig(d->glFormat, d->eglContext->config());
-
-    // Create a new context for the configuration.
-    if (!d->eglContext->createContext
-            (shareContext ? shareContext->d_func()->eglContext : 0)) {
-        delete d->eglContext;
-        d->eglContext = 0;
-        return false;
-    }
-    d->sharing = d->eglContext->isSharing();
-    if (d->sharing && shareContext)
-        const_cast<QGLContext *>(shareContext)->d_func()->sharing = true;
-
-#if defined(EGL_VERSION_1_1)
-    if (d->glFormat.swapInterval() != -1 && devType == QInternal::Widget)
-        eglSwapInterval(d->eglContext->display(), d->glFormat.swapInterval());
-#endif
-
-    // Create the EGL surface to draw into.
-    d->eglSurface = d->eglContext->createSurface(device());
-    if (d->eglSurface == EGL_NO_SURFACE) {
-        delete d->eglContext;
-        d->eglContext = 0;
-        return false;
-    }
-
-    return true;
-
-}
-
-
-
-static bool qLogEq(bool a, bool b)
-{
-    return (((!a) && (!b)) || (a && b));
-}
-
-int QGLContext::choosePixelFormat(void* , HDC )
-{
-
-    return 0;
-}
-
-class QGLCmapPrivate;
-
-class /*Q_EXPORT*/ QGLCmap
-{
-public:
-    enum Flags { Reserved = 0x01 };
-
-    QGLCmap(int maxSize = 256);
-    QGLCmap(const QGLCmap& map);
-    ~QGLCmap();
-
-    QGLCmap& operator=(const QGLCmap& map);
-
-    // isEmpty and/or isNull ?
-    int size() const;
-    int maxSize() const;
-
-    void resize(int newSize);
-
-    int find(QRgb color) const;
-    int findNearest(QRgb color) const;
-    int allocate(QRgb color, uint flags = 0, quint8 context = 0);
-
-    void setEntry(int idx, QRgb color, uint flags = 0, quint8 context = 0);
-
-    const QRgb* colors() const;
-
-private:
-    void detach();
-    QGLCmapPrivate* d;
-};
-
-#endif
-
-
-QGLCmap::QGLCmap(int maxSize) // add a bool prealloc?
-{
-    d = new QGLCmapPrivate;
-    d->maxSize = maxSize;
-}
-
-QGLCmap::QGLCmap(const QGLCmap& map)
-{
-    d = map.d;
-    d->ref();
-}
-
-QGLCmap::~QGLCmap()
-{
-    if (d && d->deref())
-        delete d;
-    d = 0;
-}
-
-QGLCmap& QGLCmap::operator=(const QGLCmap& map)
-{
-    map.d->ref();
-    if (d->deref())
-        delete d;
-    d = map.d;
-    return *this;
-}
-
-int QGLCmap::size() const
-{
-    return d->colorArray.size();
-}
-
-int QGLCmap::maxSize() const
-{
-    return d->maxSize;
-}
-
-void QGLCmap::detach()
-{
-    if (d->count != 1) {
-        d->deref();
-        QGLCmapPrivate* newd = new QGLCmapPrivate;
-        newd->maxSize = d->maxSize;
-        newd->colorArray = d->colorArray;
-        newd->allocArray = d->allocArray;
-        newd->contextArray = d->contextArray;
-        newd->colorArray.detach();
-        newd->allocArray.detach();
-        newd->contextArray.detach();
-        newd->colorMap = d->colorMap;
-        d = newd;
-    }
-}
-
-
-void QGLCmap::resize(int newSize)
-{
-    if (newSize < 0 || newSize > d->maxSize) {
-        qWarning("QGLCmap::resize(): size out of range");
-        return;
-    }
-    int oldSize = size();
-    detach();
-    //if shrinking; remove the lost elems from colorMap
-    d->colorArray.resize(newSize);
-    d->allocArray.resize(newSize);
-    d->contextArray.resize(newSize);
-    if (newSize > oldSize) {
-        memset(d->allocArray.data() + oldSize, 0, newSize - oldSize);
-        memset(d->contextArray.data() + oldSize, 0, newSize - oldSize);
-    }
-}
-
-
-int QGLCmap::find(QRgb color) const
-{
-    QMap<uint,int>::ConstIterator it = d->colorMap.find(color);
-    if (it != d->colorMap.end())
-        return *it;
-    return -1;
-}
-
-
-int QGLCmap::findNearest(QRgb color) const
-{
-    int idx = find(color);
-    if (idx >= 0)
-        return idx;
-    int mapSize = size();
-    int mindist = 200000;
-    int r = qRed(color);
-    int g = qGreen(color);
-    int b = qBlue(color);
-    int rx, gx, bx, dist;
-    for (int i=0; i < mapSize; i++) {
-        if (!(d->allocArray[i] & QGLCmapPrivate::Allocated))
-            continue;
-        QRgb ci = d->colorArray[i];
-        rx = r - qRed(ci);
-        gx = g - qGreen(ci);
-        bx = b - qBlue(ci);
-        dist = rx*rx + gx*gx + bx*bx;                // calculate distance
-        if (dist < mindist) {                        // minimal?
-            mindist = dist;
-            idx = i;
-        }
-    }
-    return idx;
-}
-
-
-// Does not always allocate; returns existing c idx if found
-
-int QGLCmap::allocate(QRgb color, uint flags, quint8 context)
-{
-    int idx = find(color);
-    if (idx >= 0)
-        return idx;
-
-    int mapSize = d->colorArray.size();
-    int newIdx = d->allocArray.indexOf(QGLCmapPrivate::UnAllocated);
-
-    if (newIdx < 0) {                        // Must allocate more room
-        if (mapSize < d->maxSize) {
-            newIdx = mapSize;
-            mapSize++;
-            resize(mapSize);
-        }
-        else {
-            //# add a bool param that says what to do in case no more room -
-            // fail (-1) or return nearest?
-            return -1;
-        }
-    }
-
-    d->colorArray[newIdx] = color;
-    if (flags & QGLCmap::Reserved) {
-        d->allocArray[newIdx] = QGLCmapPrivate::Reserved;
-    }
-    else {
-        d->allocArray[newIdx] = QGLCmapPrivate::Allocated;
-        d->colorMap.insert(color, newIdx);
-    }
-    d->contextArray[newIdx] = context;
-    return newIdx;
-}
-
-
-void QGLCmap::setEntry(int idx, QRgb color, uint flags, quint8 context)
-{
-    if (idx < 0 || idx >= d->maxSize) {
-        qWarning("QGLCmap::set(): Index out of range");
-        return;
-    }
-    detach();
-    int mapSize = size();
-    if (idx >= mapSize) {
-        mapSize = idx + 1;
-        resize(mapSize);
-    }
-    d->colorArray[idx] = color;
-    if (flags & QGLCmap::Reserved) {
-        d->allocArray[idx] = QGLCmapPrivate::Reserved;
-    }
-    else {
-        d->allocArray[idx] = QGLCmapPrivate::Allocated;
-        d->colorMap.insert(color, idx);
-    }
-    d->contextArray[idx] = context;
-}
-
-
-const QRgb* QGLCmap::colors() const
-{
-    return d->colorArray.data();
-}
-
-
-/*****************************************************************************
-  QGLWidget Win32/WGL-specific code
- *****************************************************************************/
-
-void QGLWidgetPrivate::init(QGLContext *ctx, const QGLWidget* shareWidget)
-{
-    Q_Q(QGLWidget);
-    olcx = 0;
-    initContext(ctx, shareWidget);
-
-    if (q->isValid() && q->context()->format().hasOverlay()) {
-        olcx = new QGLContext(QGLFormat::defaultOverlayFormat(), q);
-        if (!olcx->create(shareWidget ? shareWidget->overlayContext() : 0)) {
-            delete olcx;
-            olcx = 0;
-            glcx->d_func()->glFormat.setOverlay(false);
-        }
-    } else {
-        olcx = 0;
-    }
-}
-
-/*\internal
-  Store color values in the given colormap.
-*/
-static void qStoreColors(HPALETTE cmap, const QGLColormap & cols)
-{
-    QRgb color;
-    PALETTEENTRY pe;
-
-    for (int i = 0; i < cols.size(); i++) {
-        color = cols.entryRgb(i);
-        pe.peRed   = qRed(color);
-        pe.peGreen = qGreen(color);
-        pe.peBlue  = qBlue(color);
-        pe.peFlags = 0;
-
-        SetPaletteEntries(cmap, i, 1, &pe);
-    }
-}
-
-void QGLWidgetPrivate::updateColormap()
-{
-    Q_Q(QGLWidget);
-    if (!cmap.handle())
-        return;
-    HDC hdc = GetDC(q->winId());
-    SelectPalette(hdc, (HPALETTE) cmap.handle(), TRUE);
-    qStoreColors((HPALETTE) cmap.handle(), cmap);
-    RealizePalette(hdc);
-    ReleaseDC(q->winId(), hdc);
-}
-
-bool QGLWidget::event(QEvent *e)
-{
-    Q_D(QGLWidget);
-    if (e->type() == QEvent::ParentChange) {
-        setContext(new QGLContext(d->glcx->requestedFormat(), this));
-        // the overlay needs to be recreated as well
-        delete d->olcx;
-        if (isValid() && context()->format().hasOverlay()) {
-            d->olcx = new QGLContext(QGLFormat::defaultOverlayFormat(), this);
-            if (!d->olcx->create(isSharing() ? d->glcx : 0)) {
-                delete d->olcx;
-                d->olcx = 0;
-                d->glcx->d_func()->glFormat.setOverlay(false);
-            }
-        } else {
-            d->olcx = 0;
-        }
-    } else if (e->type() == QEvent::Show && !format().rgba()) {
-        d->updateColormap();
-    }
-
-    return QWidget::event(e);
-}
-
-
-void QGLWidget::resizeEvent(QResizeEvent *)
-{
-    Q_D(QGLWidget);
-    if (!isValid())
-        return;
-    makeCurrent();
-    if (!d->glcx->initialized())
-        glInit();
-    resizeGL(width(), height());
-    if (d->olcx) {
-        makeOverlayCurrent();
-        resizeOverlayGL(width(), height());
-    }
-}
-
-
-const QGLContext* QGLWidget::overlayContext() const
-{
-    return d_func()->olcx;
-}
-
-
-void QGLWidget::makeOverlayCurrent()
-{
-    Q_D(QGLWidget);
-    if (d->olcx) {
-        d->olcx->makeCurrent();
-        if (!d->olcx->initialized()) {
-            initializeOverlayGL();
-            d->olcx->setInitialized(true);
-        }
-    }
-}
-
-
-void QGLWidget::updateOverlayGL()
-{
-    Q_D(QGLWidget);
-    if (d->olcx) {
-        makeOverlayCurrent();
-        paintOverlayGL();
-        if (d->olcx->format().doubleBuffer()) {
-            if (d->autoSwap)
-                d->olcx->swapBuffers();
-        }
-        else {
-            glFlush();
-        }
-    }
-}
-
-void QGLWidget::setContext(QGLContext *context,
-                            const QGLContext* shareContext,
-                            bool deleteOldContext)
-{
-    Q_D(QGLWidget);
-    if (context == 0) {
-        qWarning("QGLWidget::setContext: Cannot set null context");
-        return;
-    }
-    if (!context->deviceIsPixmap() && context->device() != this) {
-        qWarning("QGLWidget::setContext: Context must refer to this widget");
-        return;
-    }
-
-    if (d->glcx)
-        d->glcx->doneCurrent();
-    QGLContext* oldcx = d->glcx;
-    d->glcx = context;
-
-    bool doShow = false;
-    if (oldcx && oldcx->d_func()->win == winId() && !d->glcx->deviceIsPixmap()) {
-        // We already have a context and must therefore create a new
-        // window since Windows does not permit setting a new OpenGL
-        // context for a window that already has one set.
-        doShow = isVisible();
-        QWidget *pW = static_cast<QWidget *>(parent());
-        QPoint pos = geometry().topLeft();
-        setParent(pW, windowFlags());
-        move(pos);
-    }
-
-    if (!d->glcx->isValid()) {
-        d->glcx->create(shareContext ? shareContext : oldcx);
-        // the above is a trick to keep disp lists etc when a
-        // QGLWidget has been reparented, so remove the sharing
-        // flag if we don't actually have a sharing context.
-        if (!shareContext)
-            d->glcx->d_ptr->sharing = false;
-    }
-
-    if (deleteOldContext)
-        delete oldcx;
-
-    if (doShow)
-        show();
-}
-
-
-void QGLWidgetPrivate::cleanupColormaps()
-{
-    Q_Q(QGLWidget);
-    if (cmap.handle()) {
-        HDC hdc = GetDC(q->winId());
-        SelectPalette(hdc, (HPALETTE) GetStockObject(DEFAULT_PALETTE), FALSE);
-        DeleteObject((HPALETTE) cmap.handle());
-        ReleaseDC(q->winId(), hdc);
-        cmap.setHandle(0);
-    }
-    return;
-}
-
-const QGLColormap & QGLWidget::colormap() const
-{
-    return d_func()->cmap;
-}
-
-void QGLWidget::setColormap(const QGLColormap & c)
-{
-    Q_D(QGLWidget);
-    d->cmap = c;
-
-    if (d->cmap.handle()) { // already have an allocated cmap
-        d->updateColormap();
-    } else {
-        LOGPALETTE *lpal = (LOGPALETTE *) malloc(sizeof(LOGPALETTE)
-                                                 +c.size()*sizeof(PALETTEENTRY));
-        lpal->palVersion    = 0x300;
-        lpal->palNumEntries = c.size();
-        d->cmap.setHandle(CreatePalette(lpal));
-        free(lpal);
-        d->updateColormap();
-    }
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglpixelbuffer_mac.mm b/src/opengl/qglpixelbuffer_mac.mm
deleted file mode 100644 (file)
index 37bc00f..0000000
+++ /dev/null
@@ -1,331 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qglpixelbuffer.h"
-#include "qglpixelbuffer_p.h"
-
-#ifndef QT_MAC_USE_COCOA
-#include <AGL/agl.h>
-#endif
-
-#include <qimage.h>
-#include <qgl_p.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef GL_TEXTURE_RECTANGLE_EXT
-#define GL_TEXTURE_RECTANGLE_EXT 0x84F5
-#endif
-
-static int nearest_gl_texture_size(int v)
-{
-    int n = 0, last = 0;
-    for (int s = 0; s < 32; ++s) {
-        if (((v>>s) & 1) == 1) {
-            ++n;
-            last = s;
-        }
-    }
-    if (n > 1)
-        return 1 << (last+1);
-    return 1 << last;
-}
-
-bool QGLPixelBufferPrivate::init(const QSize &size, const QGLFormat &f, QGLWidget *shareWidget)
-{
-#ifdef QT_MAC_USE_COCOA
-    Q_Q(QGLPixelBuffer);
-    // create a dummy context
-    QGLContext context(f, q);
-    context.create(shareWidget ? shareWidget->context() : 0);
-
-    if (context.isSharing())
-        share_ctx = shareWidget->context()->d_func()->cx;
-
-    // steal the NSOpenGLContext and update the format
-    ctx = context.d_func()->cx;
-    context.d_func()->cx = 0;
-    // d->cx will be set to ctx later in
-    // QGLPixelBufferPrivate::common_init, so we need to retain it:
-    [static_cast<NSOpenGLContext *>(ctx) retain];
-
-    format = context.format();
-
-    GLenum target = GL_TEXTURE_2D;
-
-    if ((QGLExtensions::glExtensions() & QGLExtensions::TextureRectangle)
-        && (size.width() != nearest_gl_texture_size(size.width())
-            || size.height() != nearest_gl_texture_size(size.height())))
-    {
-        target = GL_TEXTURE_RECTANGLE_EXT;
-    }
-
-    pbuf = [[NSOpenGLPixelBuffer alloc] initWithTextureTarget:target
-                                        textureInternalFormat:GL_RGBA
-                                        textureMaxMipMapLevel:0
-                                                  pixelsWide:size.width()
-                                                  pixelsHigh:size.height()];
-    if (!pbuf) {
-        qWarning("QGLPixelBuffer: Cannot create a pbuffer");
-        return false;
-    }
-
-    [static_cast<NSOpenGLContext *>(ctx) setPixelBuffer:static_cast<NSOpenGLPixelBuffer *>(pbuf)
-                                            cubeMapFace:0
-                                            mipMapLevel:0
-                                   currentVirtualScreen:0];
-    return true;
-#else
-    GLint attribs[40], i=0;
-    attribs[i++] = AGL_RGBA;
-    attribs[i++] = AGL_BUFFER_SIZE;
-    attribs[i++] = 32;
-    attribs[i++] = AGL_LEVEL;
-    attribs[i++] = f.plane();
-    if (f.redBufferSize() != -1) {
-        attribs[i++] = AGL_RED_SIZE;
-        attribs[i++] = f.redBufferSize();
-    }
-    if (f.greenBufferSize() != -1) {
-        attribs[i++] = AGL_GREEN_SIZE;
-        attribs[i++] = f.greenBufferSize();
-    }
-    if (f.blueBufferSize() != -1) {
-        attribs[i++] = AGL_BLUE_SIZE;
-        attribs[i++] = f.blueBufferSize();
-    }
-    if (f.stereo())
-        attribs[i++] = AGL_STEREO;
-    if (f.alpha()) {
-        attribs[i++] = AGL_ALPHA_SIZE;
-        attribs[i++] = f.alphaBufferSize() == -1 ? 8 : f.alphaBufferSize();
-    }
-    if (f.stencil()) {
-        attribs[i++] = AGL_STENCIL_SIZE;
-        attribs[i++] = f.stencilBufferSize() == -1 ? 8 : f.stencilBufferSize();
-    }
-    if (f.depth()) {
-        attribs[i++] = AGL_DEPTH_SIZE;
-        attribs[i++] = f.depthBufferSize() == -1 ? 32 : f.depthBufferSize();
-    }
-    if (f.accum()) {
-        attribs[i++] = AGL_ACCUM_RED_SIZE;
-        attribs[i++] = f.accumBufferSize() == -1 ? 16 : f.accumBufferSize();
-        attribs[i++] = AGL_ACCUM_BLUE_SIZE;
-        attribs[i++] = f.accumBufferSize() == -1 ? 16 : f.accumBufferSize();
-        attribs[i++] = AGL_ACCUM_GREEN_SIZE;
-        attribs[i++] = f.accumBufferSize() == -1 ? 16 : f.accumBufferSize();
-        attribs[i++] = AGL_ACCUM_ALPHA_SIZE;
-        attribs[i++] = f.accumBufferSize() == -1 ? 16 : f.accumBufferSize();
-    }
-
-    if (f.sampleBuffers()) {
-        attribs[i++] = AGL_SAMPLE_BUFFERS_ARB;
-        attribs[i++] = 1;
-        attribs[i++] = AGL_SAMPLES_ARB;
-        attribs[i++] = f.samples() == -1 ? 4 : f.samples();
-    }
-    attribs[i] = AGL_NONE;
-
-    AGLPixelFormat format = aglChoosePixelFormat(0, 0, attribs);
-    if (!format) {
-       qWarning("QGLPixelBuffer: Unable to find a pixel format (AGL error %d).",
-                (int) aglGetError());
-        return false;
-    }
-
-    GLint res;
-    aglDescribePixelFormat(format, AGL_LEVEL, &res);
-    this->format.setPlane(res);
-    aglDescribePixelFormat(format, AGL_DOUBLEBUFFER, &res);
-    this->format.setDoubleBuffer(res);
-    aglDescribePixelFormat(format, AGL_DEPTH_SIZE, &res);
-    this->format.setDepth(res);
-    if (this->format.depth())
-       this->format.setDepthBufferSize(res);
-    aglDescribePixelFormat(format, AGL_RGBA, &res);
-    this->format.setRgba(res);
-    aglDescribePixelFormat(format, AGL_RED_SIZE, &res);
-    this->format.setRedBufferSize(res);
-    aglDescribePixelFormat(format, AGL_GREEN_SIZE, &res);
-    this->format.setGreenBufferSize(res);
-    aglDescribePixelFormat(format, AGL_BLUE_SIZE, &res);
-    this->format.setBlueBufferSize(res);
-    aglDescribePixelFormat(format, AGL_ALPHA_SIZE, &res);
-    this->format.setAlpha(res);
-    if (this->format.alpha())
-       this->format.setAlphaBufferSize(res);
-    aglDescribePixelFormat(format, AGL_ACCUM_RED_SIZE, &res);
-    this->format.setAccum(res);
-    if (this->format.accum())
-       this->format.setAccumBufferSize(res);
-    aglDescribePixelFormat(format, AGL_STENCIL_SIZE, &res);
-    this->format.setStencil(res);
-    if (this->format.stencil())
-       this->format.setStencilBufferSize(res);
-    aglDescribePixelFormat(format, AGL_STEREO, &res);
-    this->format.setStereo(res);
-    aglDescribePixelFormat(format, AGL_SAMPLE_BUFFERS_ARB, &res);
-    this->format.setSampleBuffers(res);
-    if (this->format.sampleBuffers()) {
-        aglDescribePixelFormat(format, AGL_SAMPLES_ARB, &res);
-        this->format.setSamples(res);
-    }
-
-    AGLContext share = 0;
-    if (shareWidget)
-       share = share_ctx = static_cast<AGLContext>(shareWidget->d_func()->glcx->d_func()->cx);
-    ctx = aglCreateContext(format, share);
-    if (!ctx) {
-       qWarning("QGLPixelBuffer: Unable to create a context (AGL error %d).",
-                (int) aglGetError());
-       return false;
-    }
-
-    GLenum target = GL_TEXTURE_2D;
-
-    if ((QGLExtensions::glExtensions() & QGLExtensions::TextureRectangle)
-        && (size.width() != nearest_gl_texture_size(size.width())
-            || size.height() != nearest_gl_texture_size(size.height())))
-    {
-        target = GL_TEXTURE_RECTANGLE_EXT;
-    }
-
-    if (!aglCreatePBuffer(size.width(), size.height(), target, GL_RGBA, 0, &pbuf)) {
-       qWarning("QGLPixelBuffer: Unable to create a pbuffer (AGL error %d).",
-                (int) aglGetError());
-       return false;
-    }
-
-    if (!aglSetPBuffer(ctx, pbuf, 0, 0, 0)) {
-       qWarning("QGLPixelBuffer: Unable to set pbuffer (AGL error %d).",
-                (int) aglGetError());
-       return false;
-    }
-
-    aglDestroyPixelFormat(format);
-    return true;
-
-#endif
-}
-
-bool QGLPixelBufferPrivate::cleanup()
-{
-#ifdef QT_MAC_USE_COCOA
-    [static_cast<NSOpenGLPixelBuffer *>(pbuf) release];
-    pbuf = 0;
-    [static_cast<NSOpenGLContext *>(ctx) release];
-    ctx = 0;
-#else
-    aglDestroyPBuffer(pbuf);
-#endif
-    return true;
-}
-
-bool QGLPixelBuffer::bindToDynamicTexture(GLuint texture_id)
-{
-    Q_D(QGLPixelBuffer);
-    if (d->invalid || !d->share_ctx)
-        return false;
-
-#ifdef QT_MAC_USE_COCOA
-    NSOpenGLContext *oldContext = [NSOpenGLContext currentContext];
-    if (d->share_ctx != oldContext)
-        [static_cast<NSOpenGLContext *>(d->share_ctx) makeCurrentContext];
-    glBindTexture(GL_TEXTURE_2D, texture_id);
-    [static_cast<NSOpenGLContext *>(d->share_ctx)
-            setTextureImageToPixelBuffer:static_cast<NSOpenGLPixelBuffer *>(d->pbuf)
-            colorBuffer:GL_FRONT];
-    if (oldContext && oldContext != d->share_ctx)
-        [oldContext makeCurrentContext];
-    return true;
-#else
-    aglSetCurrentContext(d->share_ctx);
-    glBindTexture(GL_TEXTURE_2D, texture_id);
-    aglTexImagePBuffer(d->share_ctx, d->pbuf, GL_FRONT);
-    return true;
-#endif
-}
-
-#ifdef Q_MAC_COMPAT_GL_FUNCTIONS
-bool QGLPixelBuffer::bindToDynamicTexture(QMacCompatGLuint texture_id)
-{
-    return bindToDynamicTexture(GLuint(texture_id));
-}
-#endif
-
-void QGLPixelBuffer::releaseFromDynamicTexture()
-{
-}
-
-GLuint QGLPixelBuffer::generateDynamicTexture() const
-{
-#ifdef QT_MAC_USE_COCOA
-    Q_D(const QGLPixelBuffer);
-    NSOpenGLContext *oldContext = [NSOpenGLContext currentContext];
-    if (d->share_ctx != oldContext)
-        [static_cast<NSOpenGLContext *>(d->share_ctx) makeCurrentContext];
-    GLuint texture;
-    glGenTextures(1, &texture);
-    glBindTexture(GL_TEXTURE_2D, texture);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-
-    if (oldContext && oldContext != d->share_ctx)
-        [oldContext makeCurrentContext];
-    return texture;
-#else
-    GLuint texture;
-    glGenTextures(1, &texture);
-    glBindTexture(GL_TEXTURE_2D, texture);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-    return texture;
-#endif
-}
-
-bool QGLPixelBuffer::hasOpenGLPbuffers()
-{
-    return true;
-}
-
-QT_END_NAMESPACE
diff --git a/src/opengl/qglpixelbuffer_win.cpp b/src/opengl/qglpixelbuffer_win.cpp
deleted file mode 100644 (file)
index be0d5f4..0000000
+++ /dev/null
@@ -1,404 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the QtOpenGL 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <qglpixelbuffer.h>
-#include <qgl.h>
-#include <qgl_p.h>
-
-#include <qglpixelbuffer_p.h>
-
-#include <qimage.h>
-#include <qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-/* WGL_WGLEXT_PROTOTYPES */
-typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
-typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
-typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer);
-typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC);
-typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer);
-typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
-typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
-typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
-typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
-typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
-typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
-typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int * piAttribList);
-
-#ifndef WGL_ARB_pbuffer
-#define WGL_DRAW_TO_PBUFFER_ARB        0x202D
-#define WGL_MAX_PBUFFER_PIXELS_ARB     0x202E
-#define WGL_MAX_PBUFFER_WIDTH_ARB      0x202F
-#define WGL_MAX_PBUFFER_HEIGHT_ARB     0x2030
-#define WGL_PBUFFER_LARGEST_ARB        0x2033
-#define WGL_PBUFFER_WIDTH_ARB          0x2034
-#define WGL_PBUFFER_HEIGHT_ARB         0x2035
-#define WGL_PBUFFER_LOST_ARB           0x2036
-#endif
-
-#ifndef WGL_ARB_pixel_format
-#define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
-#define WGL_DRAW_TO_WINDOW_ARB         0x2001
-#define WGL_DRAW_TO_BITMAP_ARB         0x2002
-#define WGL_ACCELERATION_ARB           0x2003
-#define WGL_NEED_PALETTE_ARB           0x2004
-#define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
-#define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
-#define WGL_SWAP_METHOD_ARB            0x2007
-#define WGL_NUMBER_OVERLAYS_ARB        0x2008
-#define WGL_NUMBER_UNDERLAYS_ARB       0x2009
-#define WGL_TRANSPARENT_ARB            0x200A
-#define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
-#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
-#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
-#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
-#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
-#define WGL_SHARE_DEPTH_ARB            0x200C
-#define WGL_SHARE_STENCIL_ARB          0x200D
-#define WGL_SHARE_ACCUM_ARB            0x200E
-#define WGL_SUPPORT_GDI_ARB            0x200F
-#define WGL_SUPPORT_OPENGL_ARB         0x2010
-#define WGL_DOUBLE_BUFFER_ARB          0x2011
-#define WGL_STEREO_ARB                 0x2012
-#define WGL_PIXEL_TYPE_ARB             0x2013
-#define WGL_COLOR_BITS_ARB             0x2014
-#define WGL_RED_BITS_ARB               0x2015
-#define WGL_RED_SHIFT_ARB              0x2016
-#define WGL_GREEN_BITS_ARB             0x2017
-#define WGL_GREEN_SHIFT_ARB            0x2018
-#define WGL_BLUE_BITS_ARB              0x2019
-#define WGL_BLUE_SHIFT_ARB             0x201A
-#define WGL_ALPHA_BITS_ARB             0x201B
-#define WGL_ALPHA_SHIFT_ARB            0x201C
-#define WGL_ACCUM_BITS_ARB             0x201D
-#define WGL_ACCUM_RED_BITS_ARB         0x201E
-#define WGL_ACCUM_GREEN_BITS_ARB       0x201F
-#define WGL_ACCUM_BLUE_BITS_ARB        0x2020
-#define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
-#define WGL_DEPTH_BITS_ARB             0x2022
-#define WGL_STENCIL_BITS_ARB           0x2023
-#define WGL_AUX_BUFFERS_ARB            0x2024
-#define WGL_NO_ACCELERATION_ARB        0x2025
-#define WGL_GENERIC_ACCELERATION_ARB   0x2026
-#define WGL_FULL_ACCELERATION_ARB      0x2027
-#define WGL_SWAP_EXCHANGE_ARB          0x2028
-#define WGL_SWAP_COPY_ARB              0x2029
-#define WGL_SWAP_UNDEFINED_ARB         0x202A
-#define WGL_TYPE_RGBA_ARB              0x202B
-#define WGL_TYPE_COLORINDEX_ARB        0x202C
-#endif
-
-#ifndef WGL_ARB_render_texture
-#define WGL_BIND_TO_TEXTURE_RGB_ARB        0x2070
-#define WGL_BIND_TO_TEXTURE_RGBA_ARB       0x2071
-#define WGL_TEXTURE_FORMAT_ARB             0x2072
-#define WGL_TEXTURE_TARGET_ARB             0x2073
-#define WGL_MIPMAP_TEXTURE_ARB             0x2074
-#define WGL_TEXTURE_RGB_ARB                0x2075
-#define WGL_TEXTURE_RGBA_ARB               0x2076
-#define WGL_NO_TEXTURE_ARB                 0x2077
-#define WGL_TEXTURE_CUBE_MAP_ARB           0x2078
-#define WGL_TEXTURE_1D_ARB                 0x2079
-#define WGL_TEXTURE_2D_ARB                 0x207A
-#define WGL_MIPMAP_LEVEL_ARB               0x207B
-#define WGL_CUBE_MAP_FACE_ARB              0x207C
-#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D
-#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E
-#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F
-#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080
-#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081
-#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082
-#define WGL_FRONT_LEFT_ARB                 0x2083
-#define WGL_FRONT_RIGHT_ARB                0x2084
-#define WGL_BACK_LEFT_ARB                  0x2085
-#define WGL_BACK_RIGHT_ARB                 0x2086
-#define WGL_AUX0_ARB                       0x2087
-#define WGL_AUX1_ARB                       0x2088
-#define WGL_AUX2_ARB                       0x2089
-#define WGL_AUX3_ARB                       0x208A
-#define WGL_AUX4_ARB                       0x208B
-#define WGL_AUX5_ARB                       0x208C
-#define WGL_AUX6_ARB                       0x208D
-#define WGL_AUX7_ARB                       0x208E
-#define WGL_AUX8_ARB                       0x208F
-#define WGL_AUX9_ARB                       0x2090
-#endif
-
-#ifndef WGL_FLOAT_COMPONENTS_NV
-#define WGL_FLOAT_COMPONENTS_NV        0x20B0
-#endif
-
-#ifndef WGL_ARB_multisample
-#define WGL_SAMPLE_BUFFERS_ARB         0x2041
-#define WGL_SAMPLES_ARB                0x2042
-#endif
-
-#ifndef GL_SAMPLES_ARB
-#define GL_SAMPLES_ARB 0x80A9
-#endif
-
-QGLFormat pfiToQGLFormat(HDC hdc, int pfi);
-
-static void qt_format_to_attrib_list(bool has_render_texture, const QGLFormat &f, int attribs[])
-{
-    int i = 0;
-    attribs[i++] = WGL_SUPPORT_OPENGL_ARB;
-    attribs[i++] = TRUE;
-    attribs[i++] = WGL_DRAW_TO_PBUFFER_ARB;
-    attribs[i++] = TRUE;
-
-    if (has_render_texture) {
-        attribs[i++] = WGL_BIND_TO_TEXTURE_RGBA_ARB;
-        attribs[i++] = TRUE;
-    }
-
-    attribs[i++] = WGL_COLOR_BITS_ARB;
-    attribs[i++] = 32;
-    attribs[i++] = WGL_DOUBLE_BUFFER_ARB;
-    attribs[i++] = FALSE;
-
-    if (f.stereo()) {
-        attribs[i++] = WGL_STEREO_ARB;
-        attribs[i++] = TRUE;
-    }
-    if (f.depth()) {
-        attribs[i++] = WGL_DEPTH_BITS_ARB;
-        attribs[i++] = f.depthBufferSize() == -1 ? 24 : f.depthBufferSize();
-    }
-    if (f.redBufferSize() != -1) {
-        attribs[i++] = WGL_RED_BITS_ARB;
-        attribs[i++] = f.redBufferSize();
-    }
-    if (f.greenBufferSize() != -1) {
-        attribs[i++] = WGL_GREEN_BITS_ARB;
-        attribs[i++] = f.greenBufferSize();
-    }
-    if (f.blueBufferSize() != -1) {
-        attribs[i++] = WGL_BLUE_BITS_ARB;
-        attribs[i++] = f.blueBufferSize();
-    }
-    if (f.alpha()) {
-        attribs[i++] = WGL_ALPHA_BITS_ARB;
-        attribs[i++] = f.alphaBufferSize() == -1 ? 8 : f.alphaBufferSize();
-    }
-    if (f.accum()) {
-        attribs[i++] = WGL_ACCUM_BITS_ARB;
-        attribs[i++] = f.accumBufferSize() == -1 ? 16 : f.accumBufferSize();
-    }
-    if (f.stencil()) {
-        attribs[i++] = WGL_STENCIL_BITS_ARB;
-        attribs[i++] = f.stencilBufferSize() == -1 ? 8 : f.stencilBufferSize();
-    }
-    if ((f.redBufferSize() > 8 || f.greenBufferSize() > 8
-         || f.blueBufferSize() > 8 || f.alphaBufferSize() > 8)
-        && (QGLExtensions::glExtensions() & QGLExtensions::NVFloatBuffer))
-    {
-        attribs[i++] = WGL_FLOAT_COMPONENTS_NV;
-        attribs[i++] = TRUE;
-    }
-    if (f.sampleBuffers()) {
-        attribs[i++] = WGL_SAMPLE_BUFFERS_ARB;
-        attribs[i++] = 1;
-        attribs[i++] = WGL_SAMPLES_ARB;
-        attribs[i++] = f.samples() == -1 ? 16 : f.samples();
-    }
-    attribs[i] = 0;
-}
-
-bool QGLPixelBufferPrivate::init(const QSize &size, const QGLFormat &f, QGLWidget *shareWidget)
-{
-    QGLTemporaryContext tempContext;
-
-    PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB =
-        (PFNWGLCREATEPBUFFERARBPROC) wglGetProcAddress("wglCreatePbufferARB");
-    PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB =
-        (PFNWGLGETPBUFFERDCARBPROC) wglGetProcAddress("wglGetPbufferDCARB");
-    PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB =
-        (PFNWGLQUERYPBUFFERARBPROC) wglGetProcAddress("wglQueryPbufferARB");
-    PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB =
-        (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB");
-
-    if (!wglCreatePbufferARB) // assumes that if one can be resolved, all of them can
-        return false;
-
-    dc = wglGetCurrentDC();
-    Q_ASSERT(dc);
-    has_render_texture = false;
-
-    // sample buffers doesn't work in conjunction with the render_texture extension
-    if (!f.sampleBuffers()) {
-        PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB =
-                (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");
-
-        if (wglGetExtensionsStringARB) {
-            QString extensions(QLatin1String(wglGetExtensionsStringARB(dc)));
-            has_render_texture = extensions.contains(QLatin1String("WGL_ARB_render_texture"));
-        }
-    }
-
-    int attribs[40];
-    qt_format_to_attrib_list(has_render_texture, f, attribs);
-
-    // Find pbuffer capable pixel format.
-    unsigned int num_formats = 0;
-    int pixel_format;
-    wglChoosePixelFormatARB(dc, attribs, 0, 1, &pixel_format, &num_formats);
-
-    // some GL implementations don't support pbuffers with accum
-    // buffers, so try that before we give up
-    if (num_formats == 0 && f.accum()) {
-        QGLFormat tmp = f;
-        tmp.setAccum(false);
-        qt_format_to_attrib_list(has_render_texture, tmp, attribs);
-        wglChoosePixelFormatARB(dc, attribs, 0, 1, &pixel_format, &num_formats);
-    }
-
-    if (num_formats == 0) {
-        qWarning("QGLPixelBuffer: Unable to find a pixel format with pbuffer  - giving up.");
-        return false;
-    }
-    format = pfiToQGLFormat(dc, pixel_format);
-
-    // NB! The below ONLY works if the width/height are powers of 2.
-    // Set some pBuffer attributes so that we can use this pBuffer as
-    // a 2D RGBA texture target.
-    int pb_attribs[] = {WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB,
-                        WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, 0};
-    int pb_attribs_null[] = {0};
-
-    pbuf = wglCreatePbufferARB(dc, pixel_format, size.width(), size.height(),
-                               has_render_texture ? pb_attribs : pb_attribs_null);
-    if (!pbuf) {
-        // try again without the render_texture extension
-        pbuf = wglCreatePbufferARB(dc, pixel_format, size.width(), size.height(), pb_attribs_null);
-        has_render_texture = false;
-        if (!pbuf) {
-            qWarning("QGLPixelBuffer: Unable to create pbuffer [w=%d, h=%d] - giving up.", size.width(), size.height());
-            return false;
-        }
-    }
-
-    dc = wglGetPbufferDCARB(pbuf);
-    ctx = wglCreateContext(dc);
-    if (!dc || !ctx) {
-        qWarning("QGLPixelBuffer: Unable to create pbuffer context - giving up.");
-        return false;
-    }
-
-    // Explicitly disable the render_texture extension if we have a 
-    // multi-sampled pbuffer context. This seems to be a problem only with 
-    // ATI cards if multi-sampling is forced globally in the driver.
-    wglMakeCurrent(dc, ctx);
-    GLint samples = 0;
-    glGetIntegerv(GL_SAMPLES_ARB, &samples);
-    if (has_render_texture && samples != 0)
-        has_render_texture = false;
-
-    HGLRC share_ctx = shareWidget ? shareWidget->d_func()->glcx->d_func()->rc : 0;
-    if (share_ctx && !wglShareLists(share_ctx, ctx))
-        qWarning("QGLPixelBuffer: Unable to share display lists - with share widget.");
-
-    int width, height;
-    wglQueryPbufferARB(pbuf, WGL_PBUFFER_WIDTH_ARB, &width);
-    wglQueryPbufferARB(pbuf, WGL_PBUFFER_HEIGHT_ARB, &height);
-    return true;
-}
-
-bool QGLPixelBufferPrivate::cleanup()
-{
-    PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB =
-        (PFNWGLRELEASEPBUFFERDCARBPROC) wglGetProcAddress("wglReleasePbufferDCARB");
-    PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB =
-        (PFNWGLDESTROYPBUFFERARBPROC) wglGetProcAddress("wglDestroyPbufferARB");
-    if (!invalid && wglReleasePbufferDCARB && wglDestroyPbufferARB) {
-        wglReleasePbufferDCARB(pbuf, dc);
-        wglDestroyPbufferARB(pbuf);
-    }
-    return true;
-}
-
-bool QGLPixelBuffer::bindToDynamicTexture(GLuint texture_id)
-{
-    Q_D(QGLPixelBuffer);
-    if (d->invalid || !d->has_render_texture)
-        return false;
-    PFNWGLBINDTEXIMAGEARBPROC wglBindTexImageARB =
-        (PFNWGLBINDTEXIMAGEARBPROC) wglGetProcAddress("wglBindTexImageARB");
-    if (wglBindTexImageARB) {
-        glBindTexture(GL_TEXTURE_2D, texture_id);
-        return wglBindTexImageARB(d->pbuf, WGL_FRONT_LEFT_ARB);
-    }
-    return false;
-}
-
-void QGLPixelBuffer::releaseFromDynamicTexture()
-{
-    Q_D(QGLPixelBuffer);
-    if (d->invalid || !d->has_render_texture)
-        return;
-    PFNWGLRELEASETEXIMAGEARBPROC wglReleaseTexImageARB =
-        (PFNWGLRELEASETEXIMAGEARBPROC) wglGetProcAddress("wglReleaseTexImageARB");
-    if (wglReleaseTexImageARB)
-        wglReleaseTexImageARB(d->pbuf, WGL_FRONT_LEFT_ARB);
-}
-
-bool QGLPixelBuffer::hasOpenGLPbuffers()
-{
-    bool ret = false;
-    QGLTemporaryContext *tmpContext = 0;
-    if (!QGLContext::currentContext())
-        tmpContext = new QGLTemporaryContext;
-    PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB =
-        (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB");
-    if (wglGetExtensionsStringARB) {
-        QString extensions(QLatin1String(wglGetExtensionsStringARB(wglGetCurrentDC())));
-        if (extensions.contains(QLatin1String("WGL_ARB_pbuffer"))
-            && extensions.contains(QLatin1String("WGL_ARB_pixel_format"))) {
-            ret = true;
-        }
-    }
-    if (tmpContext)
-        delete tmpContext;
-    return ret;
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/bearer/blackberry/bbmain.cpp b/src/plugins/bearer/blackberry/bbmain.cpp
deleted file mode 100644 (file)
index f9be19b..0000000
+++ /dev/null
@@ -1,86 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Research In Motion
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qbbengine.h"
-
-#include <QtNetwork/qbearerplugin_p.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-class QBBEnginePlugin : public QBearerEnginePlugin
-{
-public:
-    QBBEnginePlugin();
-    ~QBBEnginePlugin();
-
-    QStringList keys() const;
-    QBearerEngine *create(const QString &key) const;
-};
-
-QBBEnginePlugin::QBBEnginePlugin()
-{
-}
-
-QBBEnginePlugin::~QBBEnginePlugin()
-{
-}
-
-QStringList QBBEnginePlugin::keys() const
-{
-    return QStringList() << QLatin1String("blackberry");
-}
-
-QBearerEngine *QBBEnginePlugin::create(const QString &key) const
-{
-    if (key == QLatin1String("blackberry"))
-        return new QBBEngine;
-
-    return 0;
-}
-
-Q_EXPORT_STATIC_PLUGIN(QBBEnginePlugin)
-Q_EXPORT_PLUGIN2(qbbbearer, QBBEnginePlugin)
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/blackberry/qbbengine.cpp b/src/plugins/bearer/blackberry/qbbengine.cpp
deleted file mode 100644 (file)
index ca13e4b..0000000
+++ /dev/null
@@ -1,438 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Research In Motion
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qbbengine.h"
-#include "../qnetworksession_impl.h"
-
-#include <QDebug>
-#include <QThreadStorage>
-#include <QStringList>
-#include <QTimer>
-
-#include <bps/netstatus.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-#ifdef QBBENGINE_DEBUG
-#define qBearerDebug qDebug
-#else
-#define qBearerDebug QT_NO_QDEBUG_MACRO
-#endif
-
-struct NetstatusInterfaceListCleanupHelper
-{
-    static inline void cleanup(netstatus_interface_list_t *list)
-    {
-        netstatus_free_interfaces(list);
-    }
-};
-
-struct NetstatusInterfaceCleanupHelper
-{
-    static inline void cleanup(char *interface)
-    {
-        bps_free(interface);
-    }
-};
-
-struct EngineInstanceHolder
-{
-    EngineInstanceHolder(QBBEngine *engine) :
-        instance(engine) {}
-
-    QBBEngine *instance;
-};
-
-Q_GLOBAL_STATIC(QThreadStorage<EngineInstanceHolder *>, instanceStorage);
-
-static QNetworkConfiguration::BearerType
-interfaceType(netstatus_interface_type_t type)
-{
-    switch (type) {
-    case NETSTATUS_INTERFACE_TYPE_USB:
-    case NETSTATUS_INTERFACE_TYPE_WIRED:
-        return QNetworkConfiguration::BearerEthernet;
-
-    case NETSTATUS_INTERFACE_TYPE_WIFI:
-        return QNetworkConfiguration::BearerWLAN;
-
-    case NETSTATUS_INTERFACE_TYPE_BLUETOOTH_DUN:
-        return QNetworkConfiguration::BearerBluetooth;
-
-    case NETSTATUS_INTERFACE_TYPE_CELLULAR:
-        //### TODO  not sure which BearerType would be the best
-        //to return here. We need to be able to get more
-        //information on the bearer type in order to return
-        //the exact match.
-        return QNetworkConfiguration::Bearer2G;
-
-    case NETSTATUS_INTERFACE_TYPE_VPN:
-    case NETSTATUS_INTERFACE_TYPE_BB:
-    case NETSTATUS_INTERFACE_TYPE_UNKNOWN:
-        break;
-    }
-
-    return QNetworkConfiguration::BearerUnknown;
-}
-
-static QString idForName(const QString &name)
-{
-    return QLatin1String("bps:") + name;
-}
-
-QT_BEGIN_NAMESPACE
-
-
-QBBEngine::QBBEngine(QObject *parent) :
-    QBearerEngineImpl(parent),
-    previousEventFilter(0),
-    pollingRequired(false),
-    initialized(false)
-{
-}
-
-QBBEngine::~QBBEngine()
-{
-    QAbstractEventDispatcher::instance()->setEventFilter(previousEventFilter);
-}
-
-
-QString QBBEngine::getInterfaceFromId(const QString &id)
-{
-    const QMutexLocker locker(&mutex);
-
-    return configurationInterface.value(id);
-}
-
-bool QBBEngine::hasIdentifier(const QString &id)
-{
-    const QMutexLocker locker(&mutex);
-
-    return configurationInterface.contains(id);
-}
-
-void QBBEngine::connectToId(const QString &id)
-{
-    Q_EMIT connectionError(id, OperationNotSupported);
-}
-
-void QBBEngine::disconnectFromId(const QString &id)
-{
-    Q_EMIT connectionError(id, OperationNotSupported);
-}
-
-void QBBEngine::initialize()
-{
-    if (initialized) {
-        qWarning() << Q_FUNC_INFO << "called, but instance already initialized.";
-        return;
-    }
-
-    instanceStorage()->setLocalData(new EngineInstanceHolder(this));
-
-    if (netstatus_request_events(0) != BPS_SUCCESS) {
-        qWarning() << Q_FUNC_INFO << "cannot register for network events. Polling enabled.";
-
-        const QMutexLocker locker(&pollingMutex);
-        pollingRequired = true;
-    } else {
-        previousEventFilter =
-            QAbstractEventDispatcher::instance()->setEventFilter(filterEvent);
-    }
-
-    doRequestUpdate();
-}
-
-void QBBEngine::requestUpdate()
-{
-    doRequestUpdate();
-}
-
-void QBBEngine::doRequestUpdate()
-{
-    qBearerDebug() << Q_FUNC_INFO << "entered method";
-
-    netstatus_interface_list_t interfaceList;
-
-    if ((netstatus_get_interfaces(&interfaceList)) != BPS_SUCCESS) {
-        qBearerDebug() << Q_FUNC_INFO << "cannot retrieve interface list";
-        return;
-    }
-
-    const QScopedPointer<netstatus_interface_list_t,
-          NetstatusInterfaceListCleanupHelper> holder(&interfaceList);
-
-    QSet<QString> currentConfigurations;
-
-    for (int i = 0; i < interfaceList.num_interfaces; i++) {
-        const char *interface = interfaceList.interfaces[i];
-
-        qBearerDebug() << Q_FUNC_INFO << "discovered interface" << interface;
-
-        updateConfiguration(interface);
-
-        currentConfigurations << idForName(QString::fromLatin1(interface));
-    }
-
-    QMutexLocker locker(&mutex);
-
-    const QStringList keys = accessPointConfigurations.uniqueKeys();
-
-    locker.unlock();
-
-    Q_FOREACH (const QString &id, keys) {
-        if (!currentConfigurations.contains(id))
-            removeConfiguration(id);
-    }
-
-    Q_EMIT updateCompleted();
-}
-
-QNetworkSession::State QBBEngine::sessionStateForId(const QString &id)
-{
-    const QMutexLocker locker(&mutex);
-
-    QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-    if (!ptr || !ptr->isValid)
-        return QNetworkSession::Invalid;
-
-    if ((ptr->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active)
-        return QNetworkSession::Connected;
-    else if ((ptr->state & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered)
-        return QNetworkSession::Disconnected;
-    else if ((ptr->state & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined)
-        return QNetworkSession::NotAvailable;
-    else if ((ptr->state & QNetworkConfiguration::Undefined) == QNetworkConfiguration::Undefined)
-        return QNetworkSession::NotAvailable;
-
-    return QNetworkSession::Invalid;
-}
-
-QNetworkConfigurationManager::Capabilities QBBEngine::capabilities() const
-{
-    return QNetworkConfigurationManager::ForcedRoaming;
-}
-
-QNetworkSessionPrivate *QBBEngine::createSessionBackend()
-{
-    return new QNetworkSessionPrivateImpl;
-}
-
-QNetworkConfigurationPrivatePointer QBBEngine::defaultConfiguration()
-{
-    char *interface = 0;
-
-    if (netstatus_get_default_interface(&interface) != BPS_SUCCESS)
-        return QNetworkConfigurationPrivatePointer();
-
-    if (!interface)
-        return QNetworkConfigurationPrivatePointer();
-
-    const QScopedPointer<char, NetstatusInterfaceCleanupHelper> holder(interface);
-
-    const QString id = idForName(QString::fromLatin1(interface));
-
-    const QMutexLocker locker(&mutex);
-
-    if (accessPointConfigurations.contains(id)) {
-        qBearerDebug() << Q_FUNC_INFO << "found default interface:" << id;
-
-        return accessPointConfigurations.value(id);
-    }
-
-    return QNetworkConfigurationPrivatePointer();
-}
-
-bool QBBEngine::requiresPolling() const
-{
-    const QMutexLocker locker(&pollingMutex);
-
-    return pollingRequired;
-}
-
-bool QBBEngine::filterEvent(void *message)
-{
-    bps_event_t * const event = static_cast<bps_event_t *>(message);
-
-    Q_ASSERT(event);
-
-    QBBEngine *self = instanceStorage()->localData()->instance;
-
-    Q_ASSERT(self);
-
-    if (bps_event_get_domain(event) == netstatus_get_domain())
-        self->filterEvent(event);
-
-    if (self->previousEventFilter)
-        return self->previousEventFilter(message);
-
-    return false;
-}
-
-void QBBEngine::filterEvent(bps_event_t *event)
-{
-    Q_UNUSED(event);
-
-    qBearerDebug() << Q_FUNC_INFO << "got update request.";
-
-    doRequestUpdate();
-}
-
-void QBBEngine::updateConfiguration(const char *interface)
-{
-    netstatus_interface_details_t *details = 0;
-
-    if (netstatus_get_interface_details(interface, &details) != BPS_SUCCESS) {
-        qBearerDebug() << Q_FUNC_INFO << "cannot retrieve details for interface" << interface;
-
-        return;
-    }
-
-    const QString name = QString::fromLatin1(netstatus_interface_get_name(details));
-    const QString id = idForName(name);
-
-
-    const netstatus_interface_type_t type = netstatus_interface_get_type(details);
-    const netstatus_ip_status_t ipStatus = netstatus_interface_get_ip_status(details);
-
-    netstatus_free_interface_details(&details);
-
-    QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Defined;
-
-    if (ipStatus == NETSTATUS_IP_STATUS_OK)
-        state |= QNetworkConfiguration::Active;
-
-    QMutexLocker locker(&mutex);
-
-    if (accessPointConfigurations.contains(id)) {
-        QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-        bool changed = false;
-
-        QMutexLocker ptrLocker(&ptr->mutex);
-
-        if (!ptr->isValid) {
-            ptr->isValid = true;
-            changed = true;
-        }
-
-        if (ptr->name != name) {
-            ptr->name = name;
-            changed = true;
-        }
-
-        if (ptr->id != id) {
-            ptr->id = id;
-            changed = true;
-        }
-
-        if (ptr->state != state) {
-            ptr->state = state;
-            changed = true;
-        }
-
-        const netstatus_ip_status_t oldIpStatus = ptr->oldIpStatus;
-        ptr->oldIpStatus = ipStatus;
-
-        ptrLocker.unlock();
-
-        locker.unlock();
-
-        if (changed) {
-            qBearerDebug() << Q_FUNC_INFO << "configuration changed:" << interface;
-
-            Q_EMIT configurationChanged(ptr);
-        } else {
-            // maybe Wifi has changed but gateway not yet ready etc.
-            qBearerDebug() << Q_FUNC_INFO << "configuration has not changed.";
-            if (oldIpStatus != ipStatus) { // if IP status changed
-                if (ipStatus != NETSTATUS_IP_STATUS_OK
-                        && ipStatus != NETSTATUS_IP_STATUS_ERROR_NOT_UP
-                        && ipStatus != NETSTATUS_IP_STATUS_ERROR_NOT_CONFIGURED) {
-                    // work around race condition in netstatus API by just checking
-                    // again in 300 ms
-                    QTimer::singleShot(300, this, SLOT(doRequestUpdate()));
-                }
-            }
-        }
-
-        return;
-    }
-
-    QNetworkConfigurationPrivatePointer ptr(new QNetworkConfigurationPrivate);
-
-    ptr->name = name;
-    ptr->isValid = true;
-    ptr->id = id;
-    ptr->state = state;
-    ptr->type = QNetworkConfiguration::InternetAccessPoint;
-    ptr->bearerType = interfaceType(type);
-
-    accessPointConfigurations.insert(id, ptr);
-    configurationInterface.insert(id, name);
-
-    locker.unlock();
-
-    qBearerDebug() << Q_FUNC_INFO << "configuration added:" << interface;
-
-    Q_EMIT configurationAdded(ptr);
-}
-
-void QBBEngine::removeConfiguration(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    QNetworkConfigurationPrivatePointer ptr =
-        accessPointConfigurations.take(id);
-
-    configurationInterface.remove(ptr->id);
-
-    locker.unlock();
-
-    Q_EMIT configurationRemoved(ptr);
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
-
-#include "moc_qbbengine.h"
diff --git a/src/plugins/bearer/blackberry/qbbengine.h b/src/plugins/bearer/blackberry/qbbengine.h
deleted file mode 100644 (file)
index 2302367..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Research In Motion
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QBBENGINE_H
-#define QBBENGINE_H
-
-#include "../qbearerengine_impl.h"
-
-#include <QAbstractEventDispatcher>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-struct bps_event_t;
-
-QT_BEGIN_NAMESPACE
-
-class QNetworkConfigurationPrivate;
-class QNetworkSessionPrivate;
-
-class QBBEngine : public QBearerEngineImpl
-{
-    Q_OBJECT
-
-public:
-    explicit QBBEngine(QObject *parent = 0);
-    ~QBBEngine();
-
-    QString getInterfaceFromId(const QString &id);
-    bool hasIdentifier(const QString &id);
-
-    void connectToId(const QString &id);
-    void disconnectFromId(const QString &id);
-
-    Q_INVOKABLE void initialize();
-    Q_INVOKABLE void requestUpdate();
-
-    QNetworkSession::State sessionStateForId(const QString &id);
-
-    QNetworkConfigurationManager::Capabilities capabilities() const;
-
-    QNetworkSessionPrivate *createSessionBackend();
-
-    QNetworkConfigurationPrivatePointer defaultConfiguration();
-
-    bool requiresPolling() const;
-
-protected:
-    void updateConfiguration(const char *interface);
-    void removeConfiguration(const QString &id);
-
-private Q_SLOTS:
-    void doRequestUpdate();
-
-private:
-    static bool filterEvent(void *message);
-
-    void filterEvent(bps_event_t *event);
-
-    QHash<QString, QString> configurationInterface;
-
-    QAbstractEventDispatcher::EventFilter previousEventFilter;
-
-    mutable QMutex pollingMutex;
-
-    bool pollingRequired;
-    bool initialized;
-};
-
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
-
-#endif // QBBENGINE_H
diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.h b/src/plugins/bearer/corewlan/qcorewlanengine.h
deleted file mode 100644 (file)
index e3e72d3..0000000
+++ /dev/null
@@ -1,147 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QCOREWLANENGINE_H
-#define QCOREWLANENGINE_H
-
-#include "../qbearerengine_impl.h"
-
-#include <QMap>
-#include <QTimer>
-#include <SystemConfiguration/SystemConfiguration.h>
-#include <QThread>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-class QNetworkConfigurationPrivate;
-class QScanThread;
-
-class QCoreWlanEngine : public QBearerEngineImpl
-{
-     friend class QScanThread;
-    Q_OBJECT
-
-public:
-    QCoreWlanEngine(QObject *parent = 0);
-    ~QCoreWlanEngine();
-
-    QString getInterfaceFromId(const QString &id);
-    bool hasIdentifier(const QString &id);
-
-    void connectToId(const QString &id);
-    void disconnectFromId(const QString &id);
-
-    Q_INVOKABLE void initialize();
-    Q_INVOKABLE void requestUpdate();
-
-    QNetworkSession::State sessionStateForId(const QString &id);
-
-    quint64 bytesWritten(const QString &id);
-    quint64 bytesReceived(const QString &id);
-    quint64 startTime(const QString &id);
-
-    QNetworkConfigurationManager::Capabilities capabilities() const;
-
-    QNetworkSessionPrivate *createSessionBackend();
-
-    QNetworkConfigurationPrivatePointer defaultConfiguration();
-
-    bool requiresPolling() const;
-
-private Q_SLOTS:
-    void doRequestUpdate();
-    void networksChanged();
-
-private:
-    bool isWifiReady(const QString &dev);
-    QList<QNetworkConfigurationPrivate *> foundConfigurations;
-
-    SCDynamicStoreRef storeSession;
-    CFRunLoopSourceRef runloopSource;
-    bool hasWifi;
-    bool scanning;
-    QScanThread *scanThread;
-
-    quint64 getBytes(const QString &interfaceName,bool b);
-
-protected:
-    void startNetworkChangeLoop();
-
-};
-
-class QScanThread : public QThread
-{
-    Q_OBJECT
-
-public:
-    QScanThread(QObject *parent = 0);
-    ~QScanThread();
-
-    void quit();
-    QList<QNetworkConfigurationPrivate *> getConfigurations();
-    QString interfaceName;
-    QMap<QString, QString> configurationInterface;
-    void getUserConfigurations();
-    QString getNetworkNameFromSsid(const QString &ssid);
-    QString getSsidFromNetworkName(const QString &name);
-    bool isKnownSsid(const QString &ssid);
-    QMap<QString, QMap<QString,QString> > userProfiles;
-
-signals:
-    void networksChanged();
-
-protected:
-    void run();
-
-private:
-    QList<QNetworkConfigurationPrivate *> fetchedConfigurations;
-    QMutex mutex;
-    QStringList foundNetwork(const QString &id, const QString &ssid, const QNetworkConfiguration::StateFlags state, const QString &interfaceName, const QNetworkConfiguration::Purpose purpose);
-
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
-
-#endif
diff --git a/src/plugins/bearer/corewlan/qcorewlanengine.mm b/src/plugins/bearer/corewlan/qcorewlanengine.mm
deleted file mode 100644 (file)
index 6400f7f..0000000
+++ /dev/null
@@ -1,865 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qcorewlanengine.h"
-#include "../qnetworksession_impl.h"
-
-#include <QtNetwork/qnetworkconfiguration_p.h>
-
-#include <QtCore/qthread.h>
-#include <QtCore/qmutex.h>
-#include <QtCore/qcoreapplication.h>
-#include <QtCore/qstringlist.h>
-
-#include <QtCore/qdebug.h>
-
-#include <QDir>
-
-extern "C" { // Otherwise it won't find CWKeychain* symbols at link time
-#import <CoreWLAN/CoreWLAN.h>
-}
-
-#include "qcore_mac_p.h"
-
-#include <net/if.h>
-#include <ifaddrs.h>
-
-#if __MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7
-
-@interface QT_MANGLE_NAMESPACE(QNSListener) : NSObject
-{
-    NSNotificationCenter *notificationCenter;
-    CWInterface *currentInterface;
-    QCoreWlanEngine *engine;
-    NSLock *locker;
-}
-- (void)notificationHandler:(NSNotification *)notification;
-- (void)remove;
-- (void)setEngine:(QCoreWlanEngine *)coreEngine;
-- (QCoreWlanEngine *)engine;
-- (void)dealloc;
-
-@property (assign) QCoreWlanEngine* engine;
-
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSListener)
-
-- (id) init
-{
-    [locker lock];
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    notificationCenter = [NSNotificationCenter defaultCenter];
-    currentInterface = [CWInterface interfaceWithName:nil];
-    [notificationCenter addObserver:self selector:@selector(notificationHandler:) name:CWPowerDidChangeNotification object:nil];
-    [locker unlock];
-    [autoreleasepool release];
-    return self;
-}
-
--(void)dealloc
-{
-    [super dealloc];
-}
-
--(void)setEngine:(QCoreWlanEngine *)coreEngine
-{
-    [locker lock];
-    if(!engine)
-        engine = coreEngine;
-    [locker unlock];
-}
-
--(QCoreWlanEngine *)engine
-{
-    return engine;
-}
-
--(void)remove
-{
-    [locker lock];
-    [notificationCenter removeObserver:self];
-    [locker unlock];
-}
-
-- (void)notificationHandler:(NSNotification *)notification
-{
-    Q_UNUSED(notification);
-    engine->requestUpdate();
-}
-@end
-
-static QT_MANGLE_NAMESPACE(QNSListener) *listener = 0;
-
-QT_BEGIN_NAMESPACE
-
-void networkChangeCallback(SCDynamicStoreRef/* store*/, CFArrayRef changedKeys, void *info)
-{
-    for ( long i = 0; i < CFArrayGetCount(changedKeys); i++) {
-
-        QString changed =  QCFString::toQString((CFStringRef)CFArrayGetValueAtIndex(changedKeys, i));
-        if( changed.contains("/Network/Global/IPv4")) {
-            QCoreWlanEngine* wlanEngine = static_cast<QCoreWlanEngine*>(info);
-            wlanEngine->requestUpdate();
-        }
-    }
-    return;
-}
-
-
-QScanThread::QScanThread(QObject *parent)
-    :QThread(parent)
-{
-}
-
-QScanThread::~QScanThread()
-{
-}
-
-void QScanThread::quit()
-{
-    wait();
-}
-
-void QScanThread::run()
-{
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    QStringList found;
-    mutex.lock();
-    CWInterface *currentInterface = [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceName)];
-    mutex.unlock();
-
-    if (currentInterface.powerOn) {
-        NSError *err = nil;
-
-        NSSet* apSet = [currentInterface scanForNetworksWithName:nil error:&err];
-
-        if (!err) {
-            for (CWNetwork *apNetwork in apSet) {
-                const QString networkSsid = QCFString::toQString(CFStringRef([apNetwork ssid]));
-                const QString id = QString::number(qHash(QLatin1String("corewlan:") + networkSsid));
-                found.append(id);
-
-                QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined;
-                bool known = isKnownSsid(networkSsid);
-                if (currentInterface.serviceActive) {
-                    if( networkSsid == QCFString::toQString(CFStringRef([currentInterface ssid]))) {
-                        state = QNetworkConfiguration::Active;
-                    }
-                }
-                if (state == QNetworkConfiguration::Undefined) {
-                    if(known) {
-                        state = QNetworkConfiguration::Discovered;
-                    } else {
-                        state = QNetworkConfiguration::Undefined;
-                    }
-                }
-                QNetworkConfiguration::Purpose purpose = QNetworkConfiguration::UnknownPurpose;
-                if ([apNetwork supportsSecurity:kCWSecurityNone]) {
-                    purpose = QNetworkConfiguration::PublicPurpose;
-                } else {
-                    purpose = QNetworkConfiguration::PrivatePurpose;
-                }
-
-                found.append(foundNetwork(id, networkSsid, state, interfaceName, purpose));
-
-            }
-        }
-    }
-    // add known configurations that are not around.
-    QMapIterator<QString, QMap<QString,QString> > i(userProfiles);
-    while (i.hasNext()) {
-        i.next();
-
-        QString networkName = i.key();
-        const QString id = QString::number(qHash(QLatin1String("corewlan:") + networkName));
-
-        if(!found.contains(id)) {
-            QString networkSsid = getSsidFromNetworkName(networkName);
-            const QString ssidId = QString::number(qHash(QLatin1String("corewlan:") + networkSsid));
-            QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined;
-            QString interfaceName;
-            QMapIterator<QString, QString> ij(i.value());
-            while (ij.hasNext()) {
-                ij.next();
-                interfaceName = ij.value();
-            }
-
-            if (currentInterface.serviceActive) {
-                if( networkSsid == QCFString::toQString(CFStringRef([currentInterface ssid]))) {
-                    state = QNetworkConfiguration::Active;
-                }
-            }
-            if(state == QNetworkConfiguration::Undefined) {
-                if( userProfiles.contains(networkName)
-                    && found.contains(ssidId)) {
-                    state = QNetworkConfiguration::Discovered;
-                }
-            }
-
-            if(state == QNetworkConfiguration::Undefined) {
-                state = QNetworkConfiguration::Defined;
-            }
-
-            found.append(foundNetwork(id, networkName, state, interfaceName, QNetworkConfiguration::UnknownPurpose));
-        }
-    }
-    emit networksChanged();
-    [autoreleasepool release];
-}
-
-QStringList QScanThread::foundNetwork(const QString &id, const QString &name, const QNetworkConfiguration::StateFlags state, const QString &interfaceName, const QNetworkConfiguration::Purpose purpose)
-{
-    QStringList found;
-    QMutexLocker locker(&mutex);
-        QNetworkConfigurationPrivate *ptr = new QNetworkConfigurationPrivate;
-
-        ptr->name = name;
-        ptr->isValid = true;
-        ptr->id = id;
-        ptr->state = state;
-        ptr->type = QNetworkConfiguration::InternetAccessPoint;
-        ptr->bearerType = QNetworkConfiguration::BearerWLAN;
-        ptr->purpose = purpose;
-
-        fetchedConfigurations.append( ptr);
-        configurationInterface.insert(ptr->id, interfaceName);
-
-        locker.unlock();
-        locker.relock();
-       found.append(id);
-    return found;
-}
-
-QList<QNetworkConfigurationPrivate *> QScanThread::getConfigurations()
-{
-    QMutexLocker locker(&mutex);
-
-    QList<QNetworkConfigurationPrivate *> foundConfigurations = fetchedConfigurations;
-    fetchedConfigurations.clear();
-
-    return foundConfigurations;
-}
-
-void QScanThread::getUserConfigurations()
-{
-    QMutexLocker locker(&mutex);
-
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    userProfiles.clear();
-
-    NSSet *wifiInterfaces = [CWInterface interfaceNames];
-    for (NSString *ifName in wifiInterfaces) {
-
-        CWInterface *wifiInterface = [CWInterface interfaceWithName: ifName];
-        if (!wifiInterface.powerOn)
-            continue;
-
-        NSString *nsInterfaceName = wifiInterface.ssid;
-// add user configured system networks
-        SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (CFStringRef)@"Qt corewlan", nil, nil);
-        NSDictionary * airportPlist = (NSDictionary *)SCDynamicStoreCopyValue(dynRef, (CFStringRef)[NSString stringWithFormat:@"Setup:/Network/Interface/%@/AirPort", nsInterfaceName]);
-        CFRelease(dynRef);
-        if(airportPlist != nil) {
-            NSDictionary *prefNetDict = [airportPlist objectForKey:@"PreferredNetworks"];
-
-            NSArray *thisSsidarray = [prefNetDict valueForKey:@"SSID_STR"];
-            for (NSString *ssidkey in thisSsidarray) {
-                QString thisSsid = QCFString::toQString(CFStringRef(ssidkey));
-                if(!userProfiles.contains(thisSsid)) {
-                    QMap <QString,QString> map;
-                    map.insert(thisSsid, QCFString::toQString(CFStringRef(nsInterfaceName)));
-                    userProfiles.insert(thisSsid, map);
-                }
-            }
-            CFRelease(airportPlist);
-        }
-
-        // 802.1X user profiles
-        QString userProfilePath = QDir::homePath() + "/Library/Preferences/com.apple.eap.profiles.plist";
-        NSDictionary* eapDict = [[[NSDictionary alloc] initWithContentsOfFile: (NSString *)QCFString::toCFStringRef(userProfilePath)] autorelease];
-        if(eapDict != nil) {
-            NSString *profileStr= @"Profiles";
-            NSString *nameStr = @"UserDefinedName";
-            NSString *networkSsidStr = @"Wireless Network";
-            for (id profileKey in eapDict) {
-                if ([profileStr isEqualToString:profileKey]) {
-                    NSDictionary *itemDict = [eapDict objectForKey:profileKey];
-                    for (id itemKey in itemDict) {
-
-                        NSInteger dictSize = [itemKey count];
-                        id objects[dictSize];
-                        id keys[dictSize];
-
-                        [itemKey getObjects:objects andKeys:keys];
-                        QString networkName;
-                        QString ssid;
-                        for(int i = 0; i < dictSize; i++) {
-                            if([nameStr isEqualToString:keys[i]]) {
-                                networkName = QCFString::toQString(CFStringRef(objects[i]));
-                            }
-                            if([networkSsidStr isEqualToString:keys[i]]) {
-                                ssid = QCFString::toQString(CFStringRef(objects[i]));
-                            }
-                            if(!userProfiles.contains(networkName)
-                                && !ssid.isEmpty()) {
-                                QMap<QString,QString> map;
-                                map.insert(ssid, QCFString::toQString(CFStringRef(nsInterfaceName)));
-                                userProfiles.insert(networkName, map);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-    [autoreleasepool release];
-}
-
-QString QScanThread::getSsidFromNetworkName(const QString &name)
-{
-    QMutexLocker locker(&mutex);
-
-    QMapIterator<QString, QMap<QString,QString> > i(userProfiles);
-    while (i.hasNext()) {
-        i.next();
-        QMap<QString,QString> map = i.value();
-        QMapIterator<QString, QString> ij(i.value());
-         while (ij.hasNext()) {
-             ij.next();
-             const QString networkNameHash = QString::number(qHash(QLatin1String("corewlan:") +i.key()));
-             if(name == i.key() || name == networkNameHash) {
-                 return ij.key();
-             }
-        }
-    }
-    return QString();
-}
-
-QString QScanThread::getNetworkNameFromSsid(const QString &ssid)
-{
-    QMutexLocker locker(&mutex);
-
-    QMapIterator<QString, QMap<QString,QString> > i(userProfiles);
-    while (i.hasNext()) {
-        i.next();
-        QMap<QString,QString> map = i.value();
-        QMapIterator<QString, QString> ij(i.value());
-         while (ij.hasNext()) {
-             ij.next();
-             if(ij.key() == ssid) {
-                 return i.key();
-             }
-         }
-    }
-    return QString();
-}
-
-bool QScanThread::isKnownSsid(const QString &ssid)
-{
-    QMutexLocker locker(&mutex);
-
-    QMapIterator<QString, QMap<QString,QString> > i(userProfiles);
-    while (i.hasNext()) {
-        i.next();
-        QMap<QString,QString> map = i.value();
-        if(map.keys().contains(ssid)) {
-            return true;
-        }
-    }
-    return false;
-}
-
-
-QCoreWlanEngine::QCoreWlanEngine(QObject *parent)
-:   QBearerEngineImpl(parent), scanThread(0)
-{
-    scanThread = new QScanThread(this);
-    connect(scanThread, SIGNAL(networksChanged()),
-            this, SLOT(networksChanged()));
-}
-
-QCoreWlanEngine::~QCoreWlanEngine()
-{
-    while (!foundConfigurations.isEmpty())
-        delete foundConfigurations.takeFirst();
-    [listener remove];
-    [listener release];
-}
-
-void QCoreWlanEngine::initialize()
-{
-    QMutexLocker locker(&mutex);
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-
-    if ([[CWInterface interfaceNames] count] > 0 && !listener) {
-        listener = [[QT_MANGLE_NAMESPACE(QNSListener) alloc] init];
-        listener.engine = this;
-        hasWifi = true;
-    } else {
-        hasWifi = false;
-    }
-    storeSession = NULL;
-
-    startNetworkChangeLoop();
-    [autoreleasepool release];
-}
-
-
-QString QCoreWlanEngine::getInterfaceFromId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    return scanThread->configurationInterface.value(id);
-}
-
-bool QCoreWlanEngine::hasIdentifier(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    return scanThread->configurationInterface.contains(id);
-}
-
-void QCoreWlanEngine::connectToId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    QString interfaceString = getInterfaceFromId(id);
-
-    CWInterface *wifiInterface =
-        [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceString)];
-
-    if (wifiInterface.powerOn) {
-        NSError *err = nil;
-        QString wantedSsid;
-        QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-        const QString idHash = QString::number(qHash(QLatin1String("corewlan:") + ptr->name));
-        const QString idHash2 = QString::number(qHash(QLatin1String("corewlan:") + scanThread->getNetworkNameFromSsid(ptr->name)));
-
-        QString wantedNetwork;
-        QMapIterator<QString, QMap<QString, QString> > i(scanThread->userProfiles);
-        while (i.hasNext()) {
-            i.next();
-            wantedNetwork = i.key();
-            const QString networkNameHash = QString::number(qHash(QLatin1String("corewlan:") + wantedNetwork));
-            if (id == networkNameHash) {
-                wantedSsid = scanThread->getSsidFromNetworkName(wantedNetwork);
-                break;
-            }
-        }
-
-        NSSet *scanSet = [wifiInterface scanForNetworksWithName:(NSString *)QCFString::toCFStringRef(wantedSsid) error:&err];
-
-        if(!err) {
-            for (CWNetwork *apNetwork in scanSet) {
-                CFDataRef ssidData = (CFDataRef)[apNetwork ssidData];
-                bool result = false;
-
-                SecIdentityRef identity = 0;
-                // Check first whether we require IEEE 802.1X authentication for the wanted SSID
-                if (CWKeychainCopyEAPIdentity(ssidData, &identity) == errSecSuccess) {
-                    CFStringRef username = 0;
-                    CFStringRef password = 0;
-                    if (CWKeychainCopyEAPUsernameAndPassword(ssidData, &username, &password) == errSecSuccess) {
-                        result = [wifiInterface associateToEnterpriseNetwork:apNetwork
-                                    identity:identity username:(NSString *)username password:(NSString *)password
-                                    error:&err];
-                        CFRelease(username);
-                        CFRelease(password);
-                    }
-                    CFRelease(identity);
-                } else {
-                    CFStringRef password = 0;
-                    if (CWKeychainCopyPassword(ssidData, &password) == errSecSuccess) {
-                        result = [wifiInterface associateToNetwork:apNetwork password:(NSString *)password error:&err];
-                        CFRelease(password);
-                    }
-                }
-
-                if (!err) {
-                    if (!result) {
-                        emit connectionError(id, ConnectError);
-                    } else {
-                        return;
-                    }
-                } else {
-                    qDebug() <<"associate ERROR"<<  QCFString::toQString(CFStringRef([err localizedDescription ]));
-                }
-            } //end scan network
-        } else {
-            qDebug() <<"scan ERROR"<<  QCFString::toQString(CFStringRef([err localizedDescription ]));
-        }
-        emit connectionError(id, InterfaceLookupError);
-    }
-
-    locker.unlock();
-    emit connectionError(id, InterfaceLookupError);
-    [autoreleasepool release];
-}
-
-void QCoreWlanEngine::disconnectFromId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    QString interfaceString = getInterfaceFromId(id);
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-
-    CWInterface *wifiInterface =
-        [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceString)];
-
-    [wifiInterface disassociate];
-    if (wifiInterface.serviceActive) {
-        locker.unlock();
-        emit connectionError(id, DisconnectionError);
-        locker.relock();
-    }
-    [autoreleasepool release];
-}
-
-void QCoreWlanEngine::requestUpdate()
-{
-    scanThread->getUserConfigurations();
-    doRequestUpdate();
-}
-
-void QCoreWlanEngine::doRequestUpdate()
-{
-    QMutexLocker locker(&mutex);
-
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-
-    NSSet *wifiInterfaces = [CWInterface interfaceNames];
-    for (NSString *ifName in wifiInterfaces) {
-            scanThread->interfaceName = QCFString::toQString(CFStringRef(ifName));
-            scanThread->start();
-    }
-    locker.unlock();
-    if ([wifiInterfaces count] == 0)
-        networksChanged();
-    [autoreleasepool release];
-}
-
-bool QCoreWlanEngine::isWifiReady(const QString &wifiDeviceName)
-{
-    QMutexLocker locker(&mutex);
-    bool haswifi = false;
-    if(hasWifi) {
-        NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-        CWInterface *defaultInterface = [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(wifiDeviceName)];
-        if (defaultInterface.powerOn) {
-            haswifi = true;
-        }
-        [autoreleasepool release];
-    }
-    return haswifi;
-}
-
-
-QNetworkSession::State QCoreWlanEngine::sessionStateForId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-    QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-    if (!ptr)
-        return QNetworkSession::Invalid;
-
-    if (!ptr->isValid) {
-        return QNetworkSession::Invalid;
-    } else if ((ptr->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
-        return QNetworkSession::Connected;
-    } else if ((ptr->state & QNetworkConfiguration::Discovered) ==
-                QNetworkConfiguration::Discovered) {
-        return QNetworkSession::Disconnected;
-    } else if ((ptr->state & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) {
-        return QNetworkSession::NotAvailable;
-    } else if ((ptr->state & QNetworkConfiguration::Undefined) ==
-                QNetworkConfiguration::Undefined) {
-        return QNetworkSession::NotAvailable;
-    }
-
-    return QNetworkSession::Invalid;
-}
-
-QNetworkConfigurationManager::Capabilities QCoreWlanEngine::capabilities() const
-{
-    return QNetworkConfigurationManager::ForcedRoaming;
-}
-
-void QCoreWlanEngine::startNetworkChangeLoop()
-{
-
-    SCDynamicStoreContext dynStoreContext = { 0, this/*(void *)storeSession*/, NULL, NULL, NULL };
-    storeSession = SCDynamicStoreCreate(NULL,
-                                 CFSTR("networkChangeCallback"),
-                                 networkChangeCallback,
-                                 &dynStoreContext);
-    if (!storeSession ) {
-        qWarning() << "could not open dynamic store: error:" << SCErrorString(SCError());
-        return;
-    }
-
-    CFMutableArrayRef notificationKeys;
-    notificationKeys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
-    CFMutableArrayRef patternsArray;
-    patternsArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
-
-    CFStringRef storeKey;
-    storeKey = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
-                                                     kSCDynamicStoreDomainState,
-                                                     kSCEntNetIPv4);
-    CFArrayAppendValue(notificationKeys, storeKey);
-    CFRelease(storeKey);
-
-    storeKey = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
-                                                      kSCDynamicStoreDomainState,
-                                                      kSCCompAnyRegex,
-                                                      kSCEntNetIPv4);
-    CFArrayAppendValue(patternsArray, storeKey);
-    CFRelease(storeKey);
-
-    if (!SCDynamicStoreSetNotificationKeys(storeSession , notificationKeys, patternsArray)) {
-        qWarning() << "register notification error:"<< SCErrorString(SCError());
-        CFRelease(storeSession );
-        CFRelease(notificationKeys);
-        CFRelease(patternsArray);
-        return;
-    }
-    CFRelease(notificationKeys);
-    CFRelease(patternsArray);
-
-    runloopSource = SCDynamicStoreCreateRunLoopSource(NULL, storeSession , 0);
-    if (!runloopSource) {
-        qWarning() << "runloop source error:"<< SCErrorString(SCError());
-        CFRelease(storeSession );
-        return;
-    }
-
-    CFRunLoopAddSource(CFRunLoopGetCurrent(), runloopSource, kCFRunLoopDefaultMode);
-    return;
-}
-
-QNetworkSessionPrivate *QCoreWlanEngine::createSessionBackend()
-{
-    return new QNetworkSessionPrivateImpl;
-}
-
-QNetworkConfigurationPrivatePointer QCoreWlanEngine::defaultConfiguration()
-{
-    return QNetworkConfigurationPrivatePointer();
-}
-
-bool QCoreWlanEngine::requiresPolling() const
-{
-    return true;
-}
-
-void QCoreWlanEngine::networksChanged()
-{
-    QMutexLocker locker(&mutex);
-
-    QStringList previous = accessPointConfigurations.keys();
-
-    QList<QNetworkConfigurationPrivate *> foundConfigurations = scanThread->getConfigurations();
-    while (!foundConfigurations.isEmpty()) {
-        QNetworkConfigurationPrivate *cpPriv = foundConfigurations.takeFirst();
-
-        previous.removeAll(cpPriv->id);
-
-        if (accessPointConfigurations.contains(cpPriv->id)) {
-            QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(cpPriv->id);
-
-            bool changed = false;
-
-            ptr->mutex.lock();
-
-            if (ptr->isValid != cpPriv->isValid) {
-                ptr->isValid = cpPriv->isValid;
-                changed = true;
-            }
-
-            if (ptr->name != cpPriv->name) {
-                ptr->name = cpPriv->name;
-                changed = true;
-            }
-
-            if (ptr->bearerType != cpPriv->bearerType) {
-                ptr->bearerType = cpPriv->bearerType;
-                changed = true;
-            }
-
-            if (ptr->state != cpPriv->state) {
-                ptr->state = cpPriv->state;
-                changed = true;
-            }
-
-            ptr->mutex.unlock();
-
-            if (changed) {
-                locker.unlock();
-                emit configurationChanged(ptr);
-                locker.relock();
-            }
-
-            delete cpPriv;
-        } else {
-            QNetworkConfigurationPrivatePointer ptr(cpPriv);
-
-            accessPointConfigurations.insert(ptr->id, ptr);
-
-            locker.unlock();
-            emit configurationAdded(ptr);
-            locker.relock();
-        }
-    }
-
-    while (!previous.isEmpty()) {
-        QNetworkConfigurationPrivatePointer ptr =
-            accessPointConfigurations.take(previous.takeFirst());
-
-        locker.unlock();
-        emit configurationRemoved(ptr);
-        locker.relock();
-    }
-
-    locker.unlock();
-    emit updateCompleted();
-
-}
-
-quint64 QCoreWlanEngine::bytesWritten(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-    const QString interfaceStr = getInterfaceFromId(id);
-    return getBytes(interfaceStr,false);
-}
-
-quint64 QCoreWlanEngine::bytesReceived(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-    const QString interfaceStr = getInterfaceFromId(id);
-    return getBytes(interfaceStr,true);
-}
-
-quint64 QCoreWlanEngine::startTime(const QString &identifier)
-{
-    QMutexLocker locker(&mutex);
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    quint64 timestamp = 0;
-
-    NSString *filePath = @"/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist";
-    NSDictionary* plistDict = [[[NSDictionary alloc] initWithContentsOfFile:filePath] autorelease];
-    if(plistDict == nil)
-        return timestamp;
-    NSString *input = @"KnownNetworks";
-    NSString *timeStampStr = @"_timeStamp";
-
-    NSString *ssidStr = @"SSID_STR";
-
-    for (id key in plistDict) {
-        if ([input isEqualToString:key]) {
-
-            NSDictionary *knownNetworksDict = [plistDict objectForKey:key];
-            if(knownNetworksDict == nil)
-                return timestamp;
-            for (id networkKey in knownNetworksDict) {
-                bool isFound = false;
-                NSDictionary *itemDict = [knownNetworksDict objectForKey:networkKey];
-                if(itemDict == nil)
-                    return timestamp;
-                NSInteger dictSize = [itemDict count];
-                id objects[dictSize];
-                id keys[dictSize];
-
-                [itemDict getObjects:objects andKeys:keys];
-                bool ok = false;
-                for(int i = 0; i < dictSize; i++) {
-                    if([ssidStr isEqualToString:keys[i]]) {
-                        const QString ident = QString::number(qHash(QLatin1String("corewlan:") + QCFString::toQString(CFStringRef(objects[i]))));
-                        if(ident == identifier) {
-                            ok = true;
-                        }
-                    }
-                    if(ok && [timeStampStr isEqualToString:keys[i]]) {
-                        timestamp = (quint64)[objects[i] timeIntervalSince1970];
-                        isFound = true;
-                        break;
-                    }
-                }
-                if(isFound)
-                    break;
-            }
-        }
-    }
-    [autoreleasepool release];
-    return timestamp;
-}
-
-quint64 QCoreWlanEngine::getBytes(const QString &interfaceName, bool b)
-{
-    struct ifaddrs *ifAddressList, *ifAddress;
-    struct if_data *if_data;
-
-    quint64 bytes = 0;
-    ifAddressList = nil;
-    if(getifaddrs(&ifAddressList) == 0) {
-        for(ifAddress = ifAddressList; ifAddress; ifAddress = ifAddress->ifa_next) {
-            if(interfaceName == ifAddress->ifa_name) {
-                if_data = (struct if_data*)ifAddress->ifa_data;
-                if(b) {
-                    bytes = if_data->ifi_ibytes;
-                    break;
-                } else {
-                    bytes = if_data->ifi_obytes;
-                    break;
-                }
-            }
-        }
-        freeifaddrs(ifAddressList);
-    }
-    return bytes;
-}
-
-QT_END_NAMESPACE
-
-#else // QT_MAC_PLATFORM_SDK_EQUAL_OR_ABOVE
-#include "qcorewlanengine_10_6.mm"
-#endif
diff --git a/src/plugins/bearer/corewlan/qcorewlanengine_10_6.mm b/src/plugins/bearer/corewlan/qcorewlanengine_10_6.mm
deleted file mode 100644 (file)
index 4f41f1e..0000000
+++ /dev/null
@@ -1,919 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <SystemConfiguration/SCNetworkConfiguration.h>
-
-@interface QT_MANGLE_NAMESPACE(QNSListener) : NSObject
-{
-    NSNotificationCenter *notificationCenter;
-    CWInterface *currentInterface;
-    QCoreWlanEngine *engine;
-    NSLock *locker;
-}
-- (void)notificationHandler:(NSNotification *)notification;
-- (void)remove;
-- (void)setEngine:(QCoreWlanEngine *)coreEngine;
-- (QCoreWlanEngine *)engine;
-- (void)dealloc;
-
-@property (assign) QCoreWlanEngine* engine;
-
-@end
-
-@implementation QT_MANGLE_NAMESPACE(QNSListener)
-
-- (id) init
-{
-    [locker lock];
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    notificationCenter = [NSNotificationCenter defaultCenter];
-    currentInterface = [CWInterface interfaceWithName:nil];
-    [notificationCenter addObserver:self selector:@selector(notificationHandler:) name:kCWPowerDidChangeNotification object:nil];
-    [locker unlock];
-    [autoreleasepool release];
-    return self;
-}
-
--(void)dealloc
-{
-    [super dealloc];
-}
-
--(void)setEngine:(QCoreWlanEngine *)coreEngine
-{
-    [locker lock];
-    if(!engine)
-        engine = coreEngine;
-    [locker unlock];
-}
-
--(QCoreWlanEngine *)engine
-{
-    return engine;
-}
-
--(void)remove
-{
-    [locker lock];
-    [notificationCenter removeObserver:self];
-    [locker unlock];
-}
-
-- (void)notificationHandler:(NSNotification *)notification
-{
-    Q_UNUSED(notification);
-    engine->requestUpdate();
-}
-@end
-
-static QT_MANGLE_NAMESPACE(QNSListener) *listener = 0;
-
-QT_BEGIN_NAMESPACE
-
-void networkChangeCallback(SCDynamicStoreRef/* store*/, CFArrayRef changedKeys, void *info)
-{
-    for ( long i = 0; i < CFArrayGetCount(changedKeys); i++) {
-
-        QString changed =  QCFString::toQString(CFStringRef((CFStringRef)CFArrayGetValueAtIndex(changedKeys, i)));
-        if( changed.contains("/Network/Global/IPv4")) {
-            QCoreWlanEngine* wlanEngine = static_cast<QCoreWlanEngine*>(info);
-            wlanEngine->requestUpdate();
-        }
-    }
-    return;
-}
-
-
-QScanThread::QScanThread(QObject *parent)
-    :QThread(parent)
-{
-}
-
-QScanThread::~QScanThread()
-{
-}
-
-void QScanThread::quit()
-{
-    wait();
-}
-
-void QScanThread::run()
-{
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    QStringList found;
-    mutex.lock();
-    CWInterface *currentInterface = [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceName)];
-    mutex.unlock();
-
-    if([currentInterface power]) {
-        NSError *err = nil;
-        NSDictionary *parametersDict =  [NSDictionary dictionaryWithObjectsAndKeys:
-                                   [NSNumber numberWithBool:YES], kCWScanKeyMerge,
-                                   [NSNumber numberWithInt:kCWScanTypeFast], kCWScanKeyScanType,
-                                   [NSNumber numberWithInteger:100], kCWScanKeyRestTime, nil];
-
-        NSArray* apArray = [currentInterface scanForNetworksWithParameters:parametersDict error:&err];
-        CWNetwork *apNetwork;
-
-        if (!err) {
-
-            for(uint row=0; row < [apArray count]; row++ ) {
-                apNetwork = [apArray objectAtIndex:row];
-
-                const QString networkSsid = QCFString::toQString(CFStringRef([apNetwork ssid]));
-                const QString id = QString::number(qHash(QLatin1String("corewlan:") + networkSsid));
-                found.append(id);
-
-                QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined;
-                bool known = isKnownSsid(networkSsid);
-                if( [currentInterface.interfaceState intValue] == kCWInterfaceStateRunning) {
-                    if( networkSsid == QCFString::toQString(CFStringRef([currentInterface ssid]))) {
-                        state = QNetworkConfiguration::Active;
-                    }
-                }
-                if(state == QNetworkConfiguration::Undefined) {
-                    if(known) {
-                        state = QNetworkConfiguration::Discovered;
-                    } else {
-                        state = QNetworkConfiguration::Undefined;
-                    }
-                }
-                QNetworkConfiguration::Purpose purpose = QNetworkConfiguration::UnknownPurpose;
-                if([[apNetwork securityMode] intValue] == kCWSecurityModeOpen) {
-                    purpose = QNetworkConfiguration::PublicPurpose;
-                } else {
-                    purpose = QNetworkConfiguration::PrivatePurpose;
-                }
-
-                found.append(foundNetwork(id, networkSsid, state, interfaceName, purpose));
-
-            }
-        }
-    }
-    // add known configurations that are not around.
-    QMapIterator<QString, QMap<QString,QString> > i(userProfiles);
-    while (i.hasNext()) {
-        i.next();
-
-        QString networkName = i.key();
-        const QString id = QString::number(qHash(QLatin1String("corewlan:") + networkName));
-
-        if(!found.contains(id)) {
-            QString networkSsid = getSsidFromNetworkName(networkName);
-            const QString ssidId = QString::number(qHash(QLatin1String("corewlan:") + networkSsid));
-            QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined;
-            QString interfaceName;
-            QMapIterator<QString, QString> ij(i.value());
-            while (ij.hasNext()) {
-                ij.next();
-                interfaceName = ij.value();
-            }
-
-            if( [currentInterface.interfaceState intValue] == kCWInterfaceStateRunning) {
-                if( networkSsid == QCFString::toQString(CFStringRef([currentInterface ssid]))) {
-                    state = QNetworkConfiguration::Active;
-                }
-            }
-            if(state == QNetworkConfiguration::Undefined) {
-                if( userProfiles.contains(networkName)
-                    && found.contains(ssidId)) {
-                    state = QNetworkConfiguration::Discovered;
-                }
-            }
-
-            if(state == QNetworkConfiguration::Undefined) {
-                state = QNetworkConfiguration::Defined;
-            }
-
-            found.append(foundNetwork(id, networkName, state, interfaceName, QNetworkConfiguration::UnknownPurpose));
-        }
-    }
-    emit networksChanged();
-    [autoreleasepool release];
-}
-
-QStringList QScanThread::foundNetwork(const QString &id, const QString &name, const QNetworkConfiguration::StateFlags state, const QString &interfaceName, const QNetworkConfiguration::Purpose purpose)
-{
-    QStringList found;
-    QMutexLocker locker(&mutex);
-        QNetworkConfigurationPrivate *ptr = new QNetworkConfigurationPrivate;
-
-        ptr->name = name;
-        ptr->isValid = true;
-        ptr->id = id;
-        ptr->state = state;
-        ptr->type = QNetworkConfiguration::InternetAccessPoint;
-        ptr->bearerType = QNetworkConfiguration::BearerWLAN;
-        ptr->purpose = purpose;
-
-        fetchedConfigurations.append( ptr);
-        configurationInterface.insert(ptr->id, interfaceName);
-
-        locker.unlock();
-        locker.relock();
-       found.append(id);
-    return found;
-}
-
-QList<QNetworkConfigurationPrivate *> QScanThread::getConfigurations()
-{
-    QMutexLocker locker(&mutex);
-
-    QList<QNetworkConfigurationPrivate *> foundConfigurations = fetchedConfigurations;
-    fetchedConfigurations.clear();
-
-    return foundConfigurations;
-}
-
-void QScanThread::getUserConfigurations()
-{
-    QMutexLocker locker(&mutex);
-
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    userProfiles.clear();
-
-    NSArray *wifiInterfaces = [CWInterface supportedInterfaces];
-    for(uint row=0; row < [wifiInterfaces count]; row++ ) {
-
-        CWInterface *wifiInterface = [CWInterface interfaceWithName: [wifiInterfaces objectAtIndex:row]];
-        if ( ![wifiInterface power] )
-            continue;
-
-        NSString *nsInterfaceName = [wifiInterface name];
-// add user configured system networks
-        SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, (CFStringRef)@"Qt corewlan", nil, nil);
-        NSDictionary * airportPlist = (NSDictionary *)SCDynamicStoreCopyValue(dynRef, (CFStringRef)[NSString stringWithFormat:@"Setup:/Network/Interface/%@/AirPort", nsInterfaceName]);
-        CFRelease(dynRef);
-        if(airportPlist != nil) {
-            NSDictionary *prefNetDict = [airportPlist objectForKey:@"PreferredNetworks"];
-
-            NSArray *thisSsidarray = [prefNetDict valueForKey:@"SSID_STR"];
-            for(NSString *ssidkey in thisSsidarray) {
-                QString thisSsid = QCFString::toQString(CFStringRef(ssidkey));
-                if(!userProfiles.contains(thisSsid)) {
-                    QMap <QString,QString> map;
-                    map.insert(thisSsid, QCFString::toQString(CFStringRef(nsInterfaceName)));
-                    userProfiles.insert(thisSsid, map);
-                }
-            }
-            CFRelease(airportPlist);
-        }
-
-        // 802.1X user profiles
-        QString userProfilePath = QDir::homePath() + "/Library/Preferences/com.apple.eap.profiles.plist";
-        NSDictionary* eapDict = [[[NSDictionary alloc] initWithContentsOfFile: (NSString *)QCFString::toCFStringRef(userProfilePath)] autorelease];
-        if(eapDict != nil) {
-            NSString *profileStr= @"Profiles";
-            NSString *nameStr = @"UserDefinedName";
-            NSString *networkSsidStr = @"Wireless Network";
-            for (id profileKey in eapDict) {
-                if ([profileStr isEqualToString:profileKey]) {
-                    NSDictionary *itemDict = [eapDict objectForKey:profileKey];
-                    for (id itemKey in itemDict) {
-
-                        NSInteger dictSize = [itemKey count];
-                        id objects[dictSize];
-                        id keys[dictSize];
-
-                        [itemKey getObjects:objects andKeys:keys];
-                        QString networkName;
-                        QString ssid;
-                        for(int i = 0; i < dictSize; i++) {
-                            if([nameStr isEqualToString:keys[i]]) {
-                                networkName = QCFString::toQString(CFStringRef(objects[i]));
-                            }
-                            if([networkSsidStr isEqualToString:keys[i]]) {
-                                ssid = QCFString::toQString(CFStringRef(objects[i]));
-                            }
-                            if(!userProfiles.contains(networkName)
-                                && !ssid.isEmpty()) {
-                                QMap<QString,QString> map;
-                                map.insert(ssid, QCFString::toQString(CFStringRef(nsInterfaceName)));
-                                userProfiles.insert(networkName, map);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
-    [autoreleasepool release];
-}
-
-QString QScanThread::getSsidFromNetworkName(const QString &name)
-{
-    QMutexLocker locker(&mutex);
-
-    QMapIterator<QString, QMap<QString,QString> > i(userProfiles);
-    while (i.hasNext()) {
-        i.next();
-        QMap<QString,QString> map = i.value();
-        QMapIterator<QString, QString> ij(i.value());
-         while (ij.hasNext()) {
-             ij.next();
-             const QString networkNameHash = QString::number(qHash(QLatin1String("corewlan:") +i.key()));
-             if(name == i.key() || name == networkNameHash) {
-                 return ij.key();
-             }
-        }
-    }
-    return QString();
-}
-
-QString QScanThread::getNetworkNameFromSsid(const QString &ssid)
-{
-    QMutexLocker locker(&mutex);
-
-    QMapIterator<QString, QMap<QString,QString> > i(userProfiles);
-    while (i.hasNext()) {
-        i.next();
-        QMap<QString,QString> map = i.value();
-        QMapIterator<QString, QString> ij(i.value());
-         while (ij.hasNext()) {
-             ij.next();
-             if(ij.key() == ssid) {
-                 return i.key();
-             }
-         }
-    }
-    return QString();
-}
-
-bool QScanThread::isKnownSsid(const QString &ssid)
-{
-    QMutexLocker locker(&mutex);
-
-    QMapIterator<QString, QMap<QString,QString> > i(userProfiles);
-    while (i.hasNext()) {
-        i.next();
-        QMap<QString,QString> map = i.value();
-        if(map.keys().contains(ssid)) {
-            return true;
-        }
-    }
-    return false;
-}
-
-
-QCoreWlanEngine::QCoreWlanEngine(QObject *parent)
-:   QBearerEngineImpl(parent), scanThread(0)
-{
-    scanThread = new QScanThread(this);
-    connect(scanThread, SIGNAL(networksChanged()),
-            this, SLOT(networksChanged()));
-}
-
-QCoreWlanEngine::~QCoreWlanEngine()
-{
-    while (!foundConfigurations.isEmpty())
-        delete foundConfigurations.takeFirst();
-    [listener remove];
-    [listener release];
-}
-
-void QCoreWlanEngine::initialize()
-{
-    QMutexLocker locker(&mutex);
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-
-    if([[CWInterface supportedInterfaces] count] > 0 && !listener) {
-        listener = [[QT_MANGLE_NAMESPACE(QNSListener) alloc] init];
-        listener.engine = this;
-        hasWifi = true;
-    } else {
-        hasWifi = false;
-    }
-    storeSession = NULL;
-
-    startNetworkChangeLoop();
-    [autoreleasepool release];
-}
-
-
-QString QCoreWlanEngine::getInterfaceFromId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    return scanThread->configurationInterface.value(id);
-}
-
-bool QCoreWlanEngine::hasIdentifier(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    return scanThread->configurationInterface.contains(id);
-}
-
-void QCoreWlanEngine::connectToId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    QString interfaceString = getInterfaceFromId(id);
-
-    CWInterface *wifiInterface =
-        [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceString)];
-
-    if ([wifiInterface power]) {
-        NSError *err = nil;
-        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
-
-        QString wantedSsid;
-
-        QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-        const QString idHash = QString::number(qHash(QLatin1String("corewlan:") + ptr->name));
-        const QString idHash2 = QString::number(qHash(QLatin1String("corewlan:") + scanThread->getNetworkNameFromSsid(ptr->name)));
-
-        bool using8021X = false;
-        if (idHash2 != id) {
-            NSArray *array = [CW8021XProfile allUser8021XProfiles];
-
-            for (NSUInteger i = 0; i < [array count]; ++i) {
-                const QString networkNameHashCheck = QString::number(qHash(QLatin1String("corewlan:") + QCFString::toQString(CFStringRef([[array objectAtIndex:i] userDefinedName]))));
-
-                const QString ssidHash = QString::number(qHash(QLatin1String("corewlan:") + QCFString::toQString(CFStringRef([[array objectAtIndex:i] ssid]))));
-
-                if (id == networkNameHashCheck || id == ssidHash) {
-                    const QString thisName = scanThread->getSsidFromNetworkName(id);
-                    if (thisName.isEmpty())
-                        wantedSsid = id;
-                    else
-                        wantedSsid = thisName;
-
-                    [params setValue: [array objectAtIndex:i] forKey:kCWAssocKey8021XProfile];
-                    using8021X = true;
-                    break;
-                }
-            }
-        }
-
-        if (!using8021X) {
-            QString wantedNetwork;
-            QMapIterator<QString, QMap<QString,QString> > i(scanThread->userProfiles);
-            while (i.hasNext()) {
-                i.next();
-                wantedNetwork = i.key();
-                const QString networkNameHash = QString::number(qHash(QLatin1String("corewlan:") + wantedNetwork));
-                if (id == networkNameHash) {
-                    wantedSsid =  scanThread->getSsidFromNetworkName(wantedNetwork);
-                    break;
-                }
-            }
-        }
-        NSDictionary *scanParameters = [NSDictionary dictionaryWithObjectsAndKeys:
-                                        [NSNumber numberWithBool:YES], kCWScanKeyMerge,
-                                        [NSNumber numberWithInt:kCWScanTypeFast], kCWScanKeyScanType,
-                                        [NSNumber numberWithInteger:100], kCWScanKeyRestTime,
-                                        (NSString *)QCFString::toCFStringRef(wantedSsid), kCWScanKeySSID,
-                                        nil];
-
-        NSArray *scanArray = [wifiInterface scanForNetworksWithParameters:scanParameters error:&err];
-
-        if(!err) {
-            for(uint row=0; row < [scanArray count]; row++ ) {
-                CWNetwork *apNetwork = [scanArray objectAtIndex:row];
-
-                if(wantedSsid == QCFString::toQString(CFStringRef([apNetwork ssid]))) {
-
-                    if(!using8021X) {
-                        SecKeychainAttribute attributes[3];
-
-                        NSString *account = [apNetwork ssid];
-                        NSString *keyKind = @"AirPort network password";
-                        NSString *keyName = account;
-
-                        attributes[0].tag = kSecAccountItemAttr;
-                        attributes[0].data = (void *)[account UTF8String];
-                        attributes[0].length = [account length];
-
-                        attributes[1].tag = kSecDescriptionItemAttr;
-                        attributes[1].data = (void *)[keyKind UTF8String];
-                        attributes[1].length = [keyKind length];
-
-                        attributes[2].tag = kSecLabelItemAttr;
-                        attributes[2].data = (void *)[keyName UTF8String];
-                        attributes[2].length = [keyName length];
-
-                        SecKeychainAttributeList attributeList = {3,attributes};
-
-                        SecKeychainSearchRef searchRef;
-                        SecKeychainSearchCreateFromAttributes(NULL, kSecGenericPasswordItemClass, &attributeList, &searchRef);
-
-                        NSString *password = @"";
-                        SecKeychainItemRef searchItem;
-
-                        if (SecKeychainSearchCopyNext(searchRef, &searchItem) == noErr) {
-                            UInt32 realPasswordLength;
-                            SecKeychainAttribute attributesW[8];
-                            attributesW[0].tag = kSecAccountItemAttr;
-                            SecKeychainAttributeList listW = {1,attributesW};
-                            char *realPassword;
-                            OSStatus status = SecKeychainItemCopyContent(searchItem, NULL, &listW, &realPasswordLength,(void **)&realPassword);
-
-                            if (status == noErr) {
-                                if (realPassword != NULL) {
-
-                                    QByteArray pBuf;
-                                    pBuf.resize(realPasswordLength);
-                                    pBuf.prepend(realPassword);
-                                    pBuf.insert(realPasswordLength,'\0');
-
-                                    password = [NSString stringWithUTF8String:pBuf];
-                                }
-                                SecKeychainItemFreeContent(&listW, realPassword);
-                            }
-
-                            CFRelease(searchItem);
-                        } else {
-                            qDebug() << "SecKeychainSearchCopyNext error";
-                        }
-                        [params setValue: password forKey: kCWAssocKeyPassphrase];
-                    } // end using8021X
-
-
-                    bool result = [wifiInterface associateToNetwork: apNetwork parameters:[NSDictionary dictionaryWithDictionary:params] error:&err];
-
-                    if(!err) {
-                        if(!result) {
-                            emit connectionError(id, ConnectError);
-                        } else {
-                            return;
-                        }
-                    } else {
-                        qDebug() <<"associate ERROR"<<  QCFString::toQString(CFStringRef([err localizedDescription ]));
-                    }
-                }
-            } //end scan network
-        } else {
-            qDebug() <<"scan ERROR"<<  QCFString::toQString(CFStringRef([err localizedDescription ]));
-        }
-        emit connectionError(id, InterfaceLookupError);
-    }
-
-    locker.unlock();
-    emit connectionError(id, InterfaceLookupError);
-    [autoreleasepool release];
-}
-
-void QCoreWlanEngine::disconnectFromId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    QString interfaceString = getInterfaceFromId(id);
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-
-    CWInterface *wifiInterface =
-        [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(interfaceString)];
-
-    [wifiInterface disassociate];
-    if ([[wifiInterface interfaceState]intValue] != kCWInterfaceStateInactive) {
-        locker.unlock();
-        emit connectionError(id, DisconnectionError);
-        locker.relock();
-    }
-    [autoreleasepool release];
-}
-
-void QCoreWlanEngine::requestUpdate()
-{
-    scanThread->getUserConfigurations();
-    doRequestUpdate();
-}
-
-void QCoreWlanEngine::doRequestUpdate()
-{
-    QMutexLocker locker(&mutex);
-
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-
-    NSArray *wifiInterfaces = [CWInterface supportedInterfaces];
-    for (uint row = 0; row < [wifiInterfaces count]; ++row) {
-            scanThread->interfaceName = QCFString::toQString(CFStringRef([wifiInterfaces objectAtIndex:row]));
-            scanThread->start();
-    }
-    locker.unlock();
-    if ([wifiInterfaces count] == 0)
-        networksChanged();
-    [autoreleasepool release];
-}
-
-bool QCoreWlanEngine::isWifiReady(const QString &wifiDeviceName)
-{
-    QMutexLocker locker(&mutex);
-    bool haswifi = false;
-    if(hasWifi) {
-        NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-        CWInterface *defaultInterface = [CWInterface interfaceWithName: (NSString *)QCFString::toCFStringRef(wifiDeviceName)];
-        if([defaultInterface power]) {
-            haswifi = true;
-        }
-        [autoreleasepool release];
-    }
-    return haswifi;
-}
-
-
-QNetworkSession::State QCoreWlanEngine::sessionStateForId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-    QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-    if (!ptr)
-        return QNetworkSession::Invalid;
-
-    if (!ptr->isValid) {
-        return QNetworkSession::Invalid;
-    } else if ((ptr->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
-        return QNetworkSession::Connected;
-    } else if ((ptr->state & QNetworkConfiguration::Discovered) ==
-                QNetworkConfiguration::Discovered) {
-        return QNetworkSession::Disconnected;
-    } else if ((ptr->state & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) {
-        return QNetworkSession::NotAvailable;
-    } else if ((ptr->state & QNetworkConfiguration::Undefined) ==
-                QNetworkConfiguration::Undefined) {
-        return QNetworkSession::NotAvailable;
-    }
-
-    return QNetworkSession::Invalid;
-}
-
-QNetworkConfigurationManager::Capabilities QCoreWlanEngine::capabilities() const
-{
-    return QNetworkConfigurationManager::ForcedRoaming;
-}
-
-void QCoreWlanEngine::startNetworkChangeLoop()
-{
-
-    SCDynamicStoreContext dynStoreContext = { 0, this/*(void *)storeSession*/, NULL, NULL, NULL };
-    storeSession = SCDynamicStoreCreate(NULL,
-                                 CFSTR("networkChangeCallback"),
-                                 networkChangeCallback,
-                                 &dynStoreContext);
-    if (!storeSession ) {
-        qWarning() << "could not open dynamic store: error:" << SCErrorString(SCError());
-        return;
-    }
-
-    CFMutableArrayRef notificationKeys;
-    notificationKeys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
-    CFMutableArrayRef patternsArray;
-    patternsArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
-
-    CFStringRef storeKey;
-    storeKey = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
-                                                     kSCDynamicStoreDomainState,
-                                                     kSCEntNetIPv4);
-    CFArrayAppendValue(notificationKeys, storeKey);
-    CFRelease(storeKey);
-
-    storeKey = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
-                                                      kSCDynamicStoreDomainState,
-                                                      kSCCompAnyRegex,
-                                                      kSCEntNetIPv4);
-    CFArrayAppendValue(patternsArray, storeKey);
-    CFRelease(storeKey);
-
-    if (!SCDynamicStoreSetNotificationKeys(storeSession , notificationKeys, patternsArray)) {
-        qWarning() << "register notification error:"<< SCErrorString(SCError());
-        CFRelease(storeSession );
-        CFRelease(notificationKeys);
-        CFRelease(patternsArray);
-        return;
-    }
-    CFRelease(notificationKeys);
-    CFRelease(patternsArray);
-
-    runloopSource = SCDynamicStoreCreateRunLoopSource(NULL, storeSession , 0);
-    if (!runloopSource) {
-        qWarning() << "runloop source error:"<< SCErrorString(SCError());
-        CFRelease(storeSession );
-        return;
-    }
-
-    CFRunLoopAddSource(CFRunLoopGetCurrent(), runloopSource, kCFRunLoopDefaultMode);
-    return;
-}
-
-QNetworkSessionPrivate *QCoreWlanEngine::createSessionBackend()
-{
-    return new QNetworkSessionPrivateImpl;
-}
-
-QNetworkConfigurationPrivatePointer QCoreWlanEngine::defaultConfiguration()
-{
-    return QNetworkConfigurationPrivatePointer();
-}
-
-bool QCoreWlanEngine::requiresPolling() const
-{
-    return true;
-}
-
-void QCoreWlanEngine::networksChanged()
-{
-    QMutexLocker locker(&mutex);
-
-    QStringList previous = accessPointConfigurations.keys();
-
-    QList<QNetworkConfigurationPrivate *> foundConfigurations = scanThread->getConfigurations();
-    while (!foundConfigurations.isEmpty()) {
-        QNetworkConfigurationPrivate *cpPriv = foundConfigurations.takeFirst();
-
-        previous.removeAll(cpPriv->id);
-
-        if (accessPointConfigurations.contains(cpPriv->id)) {
-            QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(cpPriv->id);
-
-            bool changed = false;
-
-            ptr->mutex.lock();
-
-            if (ptr->isValid != cpPriv->isValid) {
-                ptr->isValid = cpPriv->isValid;
-                changed = true;
-            }
-
-            if (ptr->name != cpPriv->name) {
-                ptr->name = cpPriv->name;
-                changed = true;
-            }
-
-            if (ptr->bearerType != cpPriv->bearerType) {
-                ptr->bearerType = cpPriv->bearerType;
-                changed = true;
-            }
-
-            if (ptr->state != cpPriv->state) {
-                ptr->state = cpPriv->state;
-                changed = true;
-            }
-
-            ptr->mutex.unlock();
-
-            if (changed) {
-                locker.unlock();
-                emit configurationChanged(ptr);
-                locker.relock();
-            }
-
-            delete cpPriv;
-        } else {
-            QNetworkConfigurationPrivatePointer ptr(cpPriv);
-
-            accessPointConfigurations.insert(ptr->id, ptr);
-
-            locker.unlock();
-            emit configurationAdded(ptr);
-            locker.relock();
-        }
-    }
-
-    while (!previous.isEmpty()) {
-        QNetworkConfigurationPrivatePointer ptr =
-            accessPointConfigurations.take(previous.takeFirst());
-
-        locker.unlock();
-        emit configurationRemoved(ptr);
-        locker.relock();
-    }
-
-    locker.unlock();
-    emit updateCompleted();
-
-}
-
-quint64 QCoreWlanEngine::bytesWritten(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-    const QString interfaceStr = getInterfaceFromId(id);
-    return getBytes(interfaceStr,false);
-}
-
-quint64 QCoreWlanEngine::bytesReceived(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-    const QString interfaceStr = getInterfaceFromId(id);
-    return getBytes(interfaceStr,true);
-}
-
-quint64 QCoreWlanEngine::startTime(const QString &identifier)
-{
-    QMutexLocker locker(&mutex);
-    NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
-    quint64 timestamp = 0;
-
-    NSString *filePath = @"/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist";
-    NSDictionary* plistDict = [[[NSDictionary alloc] initWithContentsOfFile:filePath] autorelease];
-    if(plistDict == nil)
-        return timestamp;
-    NSString *input = @"KnownNetworks";
-    NSString *timeStampStr = @"_timeStamp";
-
-    NSString *ssidStr = @"SSID_STR";
-
-    for (id key in plistDict) {
-        if ([input isEqualToString:key]) {
-
-            NSDictionary *knownNetworksDict = [plistDict objectForKey:key];
-            if(knownNetworksDict == nil)
-                return timestamp;
-            for (id networkKey in knownNetworksDict) {
-                bool isFound = false;
-                NSDictionary *itemDict = [knownNetworksDict objectForKey:networkKey];
-                if(itemDict == nil)
-                    return timestamp;
-                NSInteger dictSize = [itemDict count];
-                id objects[dictSize];
-                id keys[dictSize];
-
-                [itemDict getObjects:objects andKeys:keys];
-                bool ok = false;
-                for(int i = 0; i < dictSize; i++) {
-                    if([ssidStr isEqualToString:keys[i]]) {
-                        const QString ident = QString::number(qHash(QLatin1String("corewlan:") + QCFString::toQString(CFStringRef(objects[i]))));
-                        if(ident == identifier) {
-                            ok = true;
-                        }
-                    }
-                    if(ok && [timeStampStr isEqualToString:keys[i]]) {
-                        timestamp = (quint64)[objects[i] timeIntervalSince1970];
-                        isFound = true;
-                        break;
-                    }
-                }
-                if(isFound)
-                    break;
-            }
-        }
-    }
-    [autoreleasepool release];
-    return timestamp;
-}
-
-quint64 QCoreWlanEngine::getBytes(const QString &interfaceName, bool b)
-{
-    struct ifaddrs *ifAddressList, *ifAddress;
-    struct if_data *if_data;
-
-    quint64 bytes = 0;
-    ifAddressList = nil;
-    if(getifaddrs(&ifAddressList) == 0) {
-        for(ifAddress = ifAddressList; ifAddress; ifAddress = ifAddress->ifa_next) {
-            if(interfaceName == ifAddress->ifa_name) {
-                if_data = (struct if_data*)ifAddress->ifa_data;
-                if(b) {
-                    bytes = if_data->ifi_ibytes;
-                    break;
-                } else {
-                    bytes = if_data->ifi_obytes;
-                    break;
-                }
-            }
-        }
-        freeifaddrs(ifAddressList);
-    }
-    return bytes;
-}
-
-QT_END_NAMESPACE
diff --git a/src/plugins/bearer/corewlan/qcorewlanmain.cpp b/src/plugins/bearer/corewlan/qcorewlanmain.cpp
deleted file mode 100644 (file)
index ea78e73..0000000
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qcorewlanengine.h"
-
-#include <QtNetwork/qbearerplugin_p.h>
-
-#include <QtCore/qdebug.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-class QCoreWlanEnginePlugin : public QBearerEnginePlugin
-{
-public:
-    QCoreWlanEnginePlugin();
-    ~QCoreWlanEnginePlugin();
-
-    QStringList keys() const;
-    QBearerEngine *create(const QString &key) const;
-};
-
-QCoreWlanEnginePlugin::QCoreWlanEnginePlugin()
-{
-}
-
-QCoreWlanEnginePlugin::~QCoreWlanEnginePlugin()
-{
-}
-
-QStringList QCoreWlanEnginePlugin::keys() const
-{
-    return QStringList() << QLatin1String("corewlan");
-}
-
-QBearerEngine *QCoreWlanEnginePlugin::create(const QString &key) const
-{
-    if (key == QLatin1String("corewlan"))
-        return new QCoreWlanEngine;
-    else
-        return 0;
-}
-
-Q_EXPORT_STATIC_PLUGIN(QCoreWlanEnginePlugin)
-Q_EXPORT_PLUGIN2(qcorewlanbearer, QCoreWlanEnginePlugin)
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/icd/dbusdispatcher.cpp b/src/plugins/bearer/icd/dbusdispatcher.cpp
deleted file mode 100644 (file)
index 2091191..0000000
+++ /dev/null
@@ -1,635 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QDebug>
-#include <QtCore>
-#include <poll.h>
-#include <dbus/dbus.h>
-#include <dbus/dbus-glib-lowlevel.h>
-#include <glib.h>
-#include "dbusdispatcher.h"
-
-namespace Maemo {
-
-/*!
-    \class Maemo::DBusDispatcher
-
-    \brief DBusDispatcher is a class that can send DBUS method call
-    messages and receive unicast signals from DBUS objects.
-*/
-
-class DBusDispatcherPrivate
-{
-public:
-    DBusDispatcherPrivate(const QString& service,
-                          const QString& path,
-                          const QString& interface,
-                          const QString& signalPath)
-        : service(service), path(path), interface(interface),
-          signalPath(signalPath), connection(0)
-    {
-        memset(&signal_vtable, 0, sizeof(signal_vtable));
-    }
-
-    ~DBusDispatcherPrivate()
-    {
-        foreach(DBusPendingCall *call, pending_calls) {
-            dbus_pending_call_cancel(call);
-            dbus_pending_call_unref(call);
-        }
-    }
-
-    QString service;
-    QString path;
-    QString interface;
-    QString signalPath;
-    struct DBusConnection *connection;
-    QList<DBusPendingCall *> pending_calls;
-    struct DBusObjectPathVTable signal_vtable;
-};
-
-static bool constantVariantList(const QVariantList& variantList) {
-    // Special case, empty list == empty struct
-    if (variantList.isEmpty()) {
-        return false;
-    } else {        
-        QVariant::Type type = variantList[0].type();
-        // Iterate items in the list and check if they are same type
-        foreach(QVariant variant, variantList) {
-            if (variant.type() != type) {
-                return false;
-            }
-        }
-    }
-    return true;
-}
-
-static QString variantToSignature(const QVariant& argument,
-                                  bool constantList = true) {
-    switch (argument.type()) {
-        case QVariant::Bool:
-            return "b";
-        case QVariant::ByteArray:
-            return "ay";
-        case QVariant::Char:
-            return "y";
-        case QVariant::Int:
-            return "i";
-        case QVariant::UInt:
-            return "u";
-        case QVariant::StringList:
-            return "as";
-        case QVariant::String:
-            return "s";
-        case QVariant::LongLong:
-            return "x";
-        case QVariant::ULongLong:
-            return "t";
-        case QVariant::List:
-            {
-            QString signature;
-            QVariantList variantList = argument.toList();
-            if (!constantList) {
-                signature += DBUS_STRUCT_BEGIN_CHAR_AS_STRING;
-                foreach(QVariant listItem, variantList) {
-                    signature += variantToSignature(listItem);
-                }
-                signature += DBUS_STRUCT_END_CHAR_AS_STRING;
-            } else {
-                if (variantList.isEmpty())
-                    return "";
-                signature = "a" + variantToSignature(variantList[0]);
-            }
-
-            return signature;
-            }
-        default:
-            qDebug() << "Unsupported variant type: " << argument.type();
-            break;
-    }
-
-    return "";
-}
-
-static bool appendVariantToDBusMessage(const QVariant& argument,
-                                       DBusMessageIter *dbus_iter) {
-    int idx = 0;
-    DBusMessageIter array_iter;
-    QStringList str_list;
-    dbus_bool_t bool_data;
-    dbus_int32_t int32_data;
-    dbus_uint32_t uint32_data;
-    dbus_int64_t int64_data;
-    dbus_uint64_t uint64_data;
-    char *str_data;
-    char char_data;
-
-    switch (argument.type()) {
-
-        case QVariant::Bool:
-            bool_data = argument.toBool();
-            dbus_message_iter_append_basic(dbus_iter, DBUS_TYPE_BOOLEAN, 
-                                           &bool_data);
-            break;
-
-        case QVariant::ByteArray:
-            str_data = argument.toByteArray().data();
-            dbus_message_iter_open_container(dbus_iter, DBUS_TYPE_ARRAY,
-                                             DBUS_TYPE_BYTE_AS_STRING, &array_iter);
-            dbus_message_iter_append_fixed_array(&array_iter,
-                                                 DBUS_TYPE_BYTE,
-                                                 &str_data,
-                                                 argument.toByteArray().size());
-            dbus_message_iter_close_container(dbus_iter, &array_iter);
-            break;
-
-        case QVariant::Char:
-            char_data = argument.toChar().toAscii();
-            dbus_message_iter_append_basic(dbus_iter, DBUS_TYPE_BYTE, 
-                                           &char_data);
-            break;
-
-        case QVariant::Int:
-            int32_data = argument.toInt();
-            dbus_message_iter_append_basic(dbus_iter, DBUS_TYPE_INT32, 
-                                           &int32_data);
-            break;
-
-        case QVariant::String: {
-            QByteArray data = argument.toString().toUtf8();
-            str_data = data.data();
-            dbus_message_iter_append_basic(dbus_iter, DBUS_TYPE_STRING,
-                                           &str_data);
-            break;
-        }
-
-        case QVariant::StringList:
-            str_list = argument.toStringList();
-            dbus_message_iter_open_container(dbus_iter, DBUS_TYPE_ARRAY,
-                                             "s", &array_iter);
-            for (idx = 0; idx < str_list.size(); idx++) {
-                QByteArray data = str_list.at(idx).toLatin1();
-                str_data = data.data();
-                dbus_message_iter_append_basic(&array_iter,
-                                               DBUS_TYPE_STRING,
-                                               &str_data);
-            }
-            dbus_message_iter_close_container(dbus_iter, &array_iter);
-            break;
-
-        case QVariant::UInt:
-            uint32_data = argument.toUInt();
-            dbus_message_iter_append_basic(dbus_iter, DBUS_TYPE_UINT32, 
-                                           &uint32_data);
-            break;
-
-        case QVariant::ULongLong:
-            uint64_data = argument.toULongLong();
-            dbus_message_iter_append_basic(dbus_iter, DBUS_TYPE_UINT64, 
-                                           &uint64_data);
-            break;
-
-        case QVariant::LongLong:
-            int64_data = argument.toLongLong();
-            dbus_message_iter_append_basic(dbus_iter, DBUS_TYPE_INT64, 
-                                           &int64_data);
-            break;
-
-        case QVariant::List:
-            {
-            QVariantList variantList = argument.toList();
-            bool constantList = constantVariantList(variantList);
-            DBusMessageIter array_iter;
-
-            // List is mapped either as an DBUS array (all items same type)
-            // DBUS struct (variable types) depending on constantList
-            if (constantList) {
-                // Resolve the signature for the first item
-                QString signature = "";
-                if (!variantList.isEmpty()) {
-                    signature = variantToSignature(
-                                variantList[0],
-                                constantVariantList(variantList[0].toList()));
-                }
-
-                // Mapped as DBUS array
-                dbus_message_iter_open_container(dbus_iter, DBUS_TYPE_ARRAY,
-                                                 signature.toAscii(),
-                                                 &array_iter);
-
-                foreach(QVariant listItem, variantList) {
-                    appendVariantToDBusMessage(listItem, &array_iter);
-                }
-
-                dbus_message_iter_close_container(dbus_iter, &array_iter);
-            } else {
-                // Mapped as DBUS struct
-                dbus_message_iter_open_container(dbus_iter, DBUS_TYPE_STRUCT,
-                                                 NULL,
-                                                 &array_iter);
-
-                foreach(QVariant listItem, variantList) {
-                    appendVariantToDBusMessage(listItem, &array_iter);
-                }
-
-                dbus_message_iter_close_container(dbus_iter, &array_iter);
-            }
-
-            break;
-            }
-        default:
-            qDebug() << "Unsupported variant type: " << argument.type();
-            break;
-    }
-
-    return true;
-}
-
-static QVariant getVariantFromDBusMessage(DBusMessageIter *iter) {
-    dbus_bool_t bool_data;
-    dbus_int32_t int32_data;
-    dbus_uint32_t uint32_data;
-    dbus_int64_t int64_data;
-    dbus_uint64_t uint64_data;
-    char *str_data;
-    char char_data;
-    int argtype = dbus_message_iter_get_arg_type(iter);
-
-    switch (argtype) {
-
-        case DBUS_TYPE_BOOLEAN:
-        {
-            dbus_message_iter_get_basic(iter, &bool_data);
-            QVariant variant((bool)bool_data);
-            return variant;
-        }
-
-        case DBUS_TYPE_ARRAY:
-        {
-            // Handle all arrays here
-            int elem_type = dbus_message_iter_get_element_type(iter);
-            DBusMessageIter array_iter;
-
-            dbus_message_iter_recurse(iter, &array_iter);
-
-            if (elem_type == DBUS_TYPE_BYTE) {
-                QByteArray byte_array;
-                do {
-                    dbus_message_iter_get_basic(&array_iter, &char_data);
-                    byte_array.append(char_data);
-                } while (dbus_message_iter_next(&array_iter));
-                QVariant variant(byte_array);
-                return variant;
-            } else if (elem_type == DBUS_TYPE_STRING) {
-                QStringList str_list;
-                do {
-                    dbus_message_iter_get_basic(&array_iter, &str_data);
-                    str_list.append(str_data);
-                } while (dbus_message_iter_next(&array_iter));
-                QVariant variant(str_list);
-                return variant;
-            } else {
-                QVariantList variantList;
-                do {
-                    variantList << getVariantFromDBusMessage(&array_iter);
-                } while (dbus_message_iter_next(&array_iter));
-                QVariant variant(variantList);
-                return variant;
-            }
-            break;
-        }
-
-        case DBUS_TYPE_BYTE:
-        {
-            dbus_message_iter_get_basic(iter, &char_data);
-            QChar ch(char_data);
-            QVariant variant(ch);
-            return variant;
-        }
-
-        case DBUS_TYPE_INT32:
-        {
-            dbus_message_iter_get_basic(iter, &int32_data);
-            QVariant variant((int)int32_data);
-            return variant;
-        }
-
-        case DBUS_TYPE_UINT32:
-        {
-            dbus_message_iter_get_basic(iter, &uint32_data);
-            QVariant variant((uint)uint32_data);
-            return variant;
-        }
-
-        case DBUS_TYPE_STRING:
-        {
-            dbus_message_iter_get_basic(iter, &str_data);
-            QString str(QString::fromUtf8(str_data));
-            QVariant variant(str);
-            return variant;
-        }
-
-        case DBUS_TYPE_INT64:
-        {
-            dbus_message_iter_get_basic(iter, &int64_data);
-            QVariant variant((qlonglong)int64_data);
-            return variant;
-        }
-
-        case DBUS_TYPE_UINT64:
-        {
-            dbus_message_iter_get_basic(iter, &uint64_data);
-            QVariant variant((qulonglong)uint64_data);
-            return variant;
-        }
-
-        case DBUS_TYPE_STRUCT:
-        {
-            // Handle all structs here
-            DBusMessageIter struct_iter;
-            dbus_message_iter_recurse(iter, &struct_iter);
-
-           QVariantList variantList;
-           do {
-             variantList << getVariantFromDBusMessage(&struct_iter);
-           } while (dbus_message_iter_next(&struct_iter));
-           QVariant variant(variantList);
-           return variant;
-        }
-
-        default:
-            qDebug() << "Unsupported DBUS type: " << argtype;
-    }
-
-    return QVariant();
-}
-
-static DBusHandlerResult signalHandler (DBusConnection *connection,
-                                        DBusMessage *message,
-                                        void *object_ref) {
-    (void)connection;
-    QString interface;
-    QString signal;
-    DBusDispatcher *dispatcher = (DBusDispatcher *)object_ref;
-
-    if (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL) {
-        interface = dbus_message_get_interface(message);
-        signal = dbus_message_get_member(message);
-        
-        QList<QVariant> arglist;
-        DBusMessageIter dbus_iter;
-
-        if (dbus_message_iter_init(message, &dbus_iter)) {
-            // Read return arguments
-            while (dbus_message_iter_get_arg_type (&dbus_iter) != DBUS_TYPE_INVALID) {
-                arglist << getVariantFromDBusMessage(&dbus_iter);
-                dbus_message_iter_next(&dbus_iter);
-            }
-        }
-
-        dispatcher->emitSignalReceived(interface, signal, arglist);
-        return DBUS_HANDLER_RESULT_HANDLED;
-    }
-    (void)message;
-    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-DBusDispatcher::DBusDispatcher(const QString& service,
-                               const QString& path,
-                               const QString& interface,
-                               QObject *parent)
- : QObject(parent),
-   d_ptr(new DBusDispatcherPrivate(service, path, interface, path)) {
-    setupDBus();
-}
-
-DBusDispatcher::DBusDispatcher(const QString& service,
-                               const QString& path,
-                               const QString& interface,
-                               const QString& signalPath,
-                               QObject *parent)
- : QObject(parent),
-   d_ptr(new DBusDispatcherPrivate(service, path, interface, signalPath)) {
-    setupDBus();
-}
-
-DBusDispatcher::~DBusDispatcher()
-{
-    if (d_ptr->connection) {
-        dbus_connection_close(d_ptr->connection);
-        dbus_connection_unref(d_ptr->connection);
-    }
-    delete d_ptr;
-}
-
-void DBusDispatcher::setupDBus()
-{
-    d_ptr->connection = dbus_bus_get_private(DBUS_BUS_SYSTEM, NULL);
-
-    if (d_ptr->connection == NULL)
-        qDebug() << "Unable to get DBUS connection!";
-    else {
-        d_ptr->signal_vtable.message_function = signalHandler;
-
-       dbus_connection_set_exit_on_disconnect(d_ptr->connection, FALSE);
-        dbus_connection_setup_with_g_main(d_ptr->connection, g_main_context_get_thread_default());
-        dbus_connection_register_object_path(d_ptr->connection, 
-                                             d_ptr->signalPath.toLatin1(),
-                                             &d_ptr->signal_vtable,
-                                             this);
-    }
-}
-
-static DBusMessage *prepareDBusCall(const QString& service,
-                                    const QString& path,
-                                    const QString& interface,
-                                    const QString& method, 
-                                    const QVariant& arg1 = QVariant(),
-                                    const QVariant& arg2 = QVariant(),
-                                    const QVariant& arg3 = QVariant(),
-                                    const QVariant& arg4 = QVariant(),
-                                    const QVariant& arg5 = QVariant(),
-                                    const QVariant& arg6 = QVariant(),
-                                    const QVariant& arg7 = QVariant(),
-                                    const QVariant& arg8 = QVariant()) 
-{
-    DBusMessage *message = dbus_message_new_method_call(service.toLatin1(),
-                                                        path.toLatin1(),
-                                                        interface.toLatin1(),
-                                                        method.toLatin1());
-    DBusMessageIter dbus_iter;
-
-    // Append variants to DBUS message
-    QList<QVariant> arglist;
-    if (arg1.isValid()) arglist << arg1;
-    if (arg2.isValid()) arglist << arg2;
-    if (arg3.isValid()) arglist << arg3;
-    if (arg4.isValid()) arglist << arg4;
-    if (arg5.isValid()) arglist << arg5;
-    if (arg6.isValid()) arglist << arg6;
-    if (arg7.isValid()) arglist << arg7;
-    if (arg8.isValid()) arglist << arg8;
-
-    dbus_message_iter_init_append (message, &dbus_iter);
-    
-    while (!arglist.isEmpty()) {
-        QVariant argument = arglist.takeFirst();
-        appendVariantToDBusMessage(argument, &dbus_iter);
-    }
-
-    return message;
-}
-
-QList<QVariant> DBusDispatcher::call(const QString& method, 
-                                     const QVariant& arg1,
-                                     const QVariant& arg2,
-                                     const QVariant& arg3,
-                                     const QVariant& arg4,
-                                     const QVariant& arg5,
-                                     const QVariant& arg6,
-                                     const QVariant& arg7,
-                                     const QVariant& arg8) {
-    DBusMessageIter dbus_iter;
-    DBusMessage *message = prepareDBusCall(d_ptr->service, d_ptr->path,
-                                           d_ptr->interface, method,
-                                           arg1, arg2, arg3, arg4, arg5,
-                                           arg6, arg7, arg8);
-    DBusMessage *reply = dbus_connection_send_with_reply_and_block(
-                                                    d_ptr->connection,
-                                                    message, -1, NULL);
-    dbus_message_unref(message);
-
-    QList<QVariant> replylist;
-    if (reply != NULL &&  dbus_message_iter_init(reply, &dbus_iter)) {
-        // Read return arguments
-        while (dbus_message_iter_get_arg_type (&dbus_iter) != DBUS_TYPE_INVALID) {
-            replylist << getVariantFromDBusMessage(&dbus_iter);
-            dbus_message_iter_next(&dbus_iter);
-        }
-    }
-    if (reply != NULL) dbus_message_unref(reply);
-    return replylist;
-}
-
-class PendingCallInfo {
-public:
-    QString method;
-    DBusDispatcher *dispatcher;
-    DBusDispatcherPrivate *priv;
-};
-
-static void freePendingCallInfo(void *memory) {
-    PendingCallInfo *info = (PendingCallInfo *)memory;
-    delete info;
-}
-
-static void pendingCallFunction (DBusPendingCall *pending,
-                                 void *memory) {
-    PendingCallInfo *info = (PendingCallInfo *)memory;
-    QString errorStr;
-    QList<QVariant> replyList;
-    DBusMessage *reply = dbus_pending_call_steal_reply (pending);
-
-    Q_ASSERT(reply != NULL);
-
-    if (dbus_message_get_type(reply) == DBUS_MESSAGE_TYPE_ERROR) {
-        errorStr = dbus_message_get_error_name (reply);
-    } else {
-        DBusMessageIter dbus_iter;
-        dbus_message_iter_init(reply, &dbus_iter);
-        // Read return arguments
-        while (dbus_message_iter_get_arg_type (&dbus_iter) != DBUS_TYPE_INVALID) {
-            replyList << getVariantFromDBusMessage(&dbus_iter);
-            dbus_message_iter_next(&dbus_iter);
-        }
-    }
-
-    info->priv->pending_calls.removeOne(pending);
-    info->dispatcher->emitCallReply(info->method, replyList, errorStr);
-    dbus_message_unref(reply);
-    dbus_pending_call_unref(pending);
-}
-
-bool DBusDispatcher::callAsynchronous(const QString& method, 
-                                      const QVariant& arg1,
-                                      const QVariant& arg2,
-                                      const QVariant& arg3,
-                                      const QVariant& arg4,
-                                      const QVariant& arg5,
-                                      const QVariant& arg6,
-                                      const QVariant& arg7,
-                                      const QVariant& arg8) {
-    DBusMessage *message = prepareDBusCall(d_ptr->service, d_ptr->path,
-                                           d_ptr->interface, method,
-                                           arg1, arg2, arg3, arg4, arg5,
-                                           arg6, arg7, arg8);
-    DBusPendingCall *call = NULL;
-    dbus_bool_t ret = dbus_connection_send_with_reply(d_ptr->connection,
-                                                      message, &call, -1);
-    PendingCallInfo *info = new PendingCallInfo;
-    info->method = method;
-    info->dispatcher = this;
-    info->priv = d_ptr;
-
-    dbus_pending_call_set_notify(call, pendingCallFunction, info, freePendingCallInfo);
-    d_ptr->pending_calls.append(call);
-    return (bool)ret;
-}
-
-void DBusDispatcher::emitSignalReceived(const QString& interface, 
-                                        const QString& signal,
-                                        const QList<QVariant>& args) {
-    emit signalReceived(interface, signal, args); }
-
-void DBusDispatcher::emitCallReply(const QString& method,
-                                   const QList<QVariant>& args,
-                                   const QString& error) {
-    emit callReply(method, args, error); }
-
-void DBusDispatcher::synchronousDispatch(int timeout_ms)
-{
-    dbus_connection_read_write_dispatch(d_ptr->connection, timeout_ms);
-}
-
-} // Maemo namespace
-
-#include "moc_dbusdispatcher.h"
diff --git a/src/plugins/bearer/icd/dbusdispatcher.h b/src/plugins/bearer/icd/dbusdispatcher.h
deleted file mode 100644 (file)
index 99d2bb6..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef DBUSDISPATCHER_H
-#define DBUSDISPATCHER_H
-
-#include <QObject>
-#include <QVariant>
-
-namespace Maemo {
-
-class DBusDispatcherPrivate;
-class DBusDispatcher : public QObject
-{
-    Q_OBJECT
-
-public:
-    DBusDispatcher(const QString& service,
-                   const QString& path,
-                   const QString& interface,
-                   QObject *parent = 0);
-    DBusDispatcher(const QString& service,
-                   const QString& path,
-                   const QString& interface,
-                   const QString& signalPath,
-                   QObject *parent = 0);
-    ~DBusDispatcher();
-
-    QList<QVariant> call(const QString& method, 
-                         const QVariant& arg1 = QVariant(),
-                         const QVariant& arg2 = QVariant(),
-                         const QVariant& arg3 = QVariant(),
-                         const QVariant& arg4 = QVariant(),
-                         const QVariant& arg5 = QVariant(),
-                         const QVariant& arg6 = QVariant(),
-                         const QVariant& arg7 = QVariant(),
-                         const QVariant& arg8 = QVariant());
-    bool callAsynchronous(const QString& method, 
-                          const QVariant& arg1 = QVariant(),
-                          const QVariant& arg2 = QVariant(),
-                          const QVariant& arg3 = QVariant(),
-                          const QVariant& arg4 = QVariant(),
-                          const QVariant& arg5 = QVariant(),
-                          const QVariant& arg6 = QVariant(),
-                          const QVariant& arg7 = QVariant(),
-                          const QVariant& arg8 = QVariant());
-    void emitSignalReceived(const QString& interface, 
-                            const QString& signal,
-                            const QList<QVariant>& args);
-    void emitCallReply(const QString& method,
-                       const QList<QVariant>& args,
-                       const QString& error = "");
-    void synchronousDispatch(int timeout_ms);
-
-Q_SIGNALS:
-    void signalReceived(const QString& interface, 
-                        const QString& signal,
-                        const QList<QVariant>& args);
-    void callReply(const QString& method,
-                   const QList<QVariant>& args,
-                   const QString& error);
-
-protected:
-    void setupDBus();
-
-private:
-    DBusDispatcherPrivate *d_ptr;
-};
-
-}  // Maemo namespace
-
-#endif
diff --git a/src/plugins/bearer/icd/iapconf.cpp b/src/plugins/bearer/icd/iapconf.cpp
deleted file mode 100644 (file)
index b2b40bb..0000000
+++ /dev/null
@@ -1,245 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <stdlib.h>
-#include <string.h>
-#include <conn_settings.h>
-
-#include "iapconf.h"
-
-#define QSTRING_TO_CONST_CSTR(str) \
-    str.toUtf8().constData()
-
-namespace Maemo {
-
-class IAPConfPrivate {
-public:
-    ConnSettings *settings;
-
-    ConnSettingsValue *variantToValue(const QVariant &variant);
-    QVariant valueToVariant(ConnSettingsValue *value);
-};
-
-ConnSettingsValue *IAPConfPrivate::variantToValue(const QVariant &variant)
-{
-    // Convert variant to ConnSettingsValue
-    ConnSettingsValue *value = conn_settings_value_new();
-    if (value == 0) {
-        qWarning("IAPConf: Unable to create new ConnSettingsValue");
-        return 0;
-    }
-
-    switch(variant.type()) {
-        
-    case QVariant::Invalid:
-        value->type = CONN_SETTINGS_VALUE_INVALID;
-        break;
-    
-    case QVariant::String: {
-        char *valueStr = strdup(QSTRING_TO_CONST_CSTR(variant.toString()));
-        value->type = CONN_SETTINGS_VALUE_STRING;
-        value->value.string_val = valueStr;
-        break;
-    }
-    
-    case QVariant::Int:
-        value->type = CONN_SETTINGS_VALUE_INT;
-        value->value.int_val = variant.toInt();
-        break;
-    
-    case QMetaType::Float:
-    case QVariant::Double:
-        value->type = CONN_SETTINGS_VALUE_DOUBLE;
-        value->value.double_val = variant.toDouble();
-        break;
-    
-    case QVariant::Bool:
-        value->type = CONN_SETTINGS_VALUE_BOOL;
-        value->value.bool_val = variant.toBool() ? 1 : 0;
-        break;
-    
-    case QVariant::ByteArray: {
-        QByteArray array = variant.toByteArray();
-        value->type = CONN_SETTINGS_VALUE_BYTE_ARRAY;
-        value->value.byte_array.len = array.size();
-        value->value.byte_array.val = (unsigned char *)malloc(array.size());
-        memcpy(value->value.byte_array.val, array.constData(), array.size());
-        break;
-    }
-    
-    case QVariant::List: {
-        QVariantList list = variant.toList();
-        ConnSettingsValue **list_val = (ConnSettingsValue **)malloc(
-            (list.size() + 1) * sizeof(ConnSettingsValue *));
-
-        for (int idx = 0; idx < list.size(); idx++) {
-            list_val[idx] = variantToValue(list.at(idx));
-        }
-        list_val[list.size()] = 0;
-
-        value->type = CONN_SETTINGS_VALUE_LIST;
-        value->value.list_val = list_val;
-        break;
-    }
-    
-    default:
-        qWarning("IAPConf: Can not handle QVariant of type %d",
-                 variant.type());
-        conn_settings_value_destroy(value);
-        return 0;
-    }
-
-    return value;
-}
-
-QVariant IAPConfPrivate::valueToVariant(ConnSettingsValue *value)
-{
-    if (value == 0 || value->type == CONN_SETTINGS_VALUE_INVALID) {
-        return QVariant();
-    }
-
-    switch(value->type) {
-    
-    case CONN_SETTINGS_VALUE_BOOL:
-        return QVariant(value->value.bool_val ? true : false);
-    
-    case CONN_SETTINGS_VALUE_STRING:
-        return QVariant(QString::fromUtf8(value->value.string_val));
-    
-    case CONN_SETTINGS_VALUE_DOUBLE:
-        return QVariant(value->value.double_val);
-    
-    case CONN_SETTINGS_VALUE_INT:
-        return QVariant(value->value.int_val);
-    
-    case CONN_SETTINGS_VALUE_LIST: {
-        // At least with GConf backend connsettings returns byte array as list
-        // of ints, first check for that case
-        if (value->value.list_val && value->value.list_val[0]) {
-            bool canBeConvertedToByteArray = true;
-            for (int idx = 0; value->value.list_val[idx]; idx++) {
-                ConnSettingsValue *val = value->value.list_val[idx];
-                if (val->type != CONN_SETTINGS_VALUE_INT
-                     || val->value.int_val > 255
-                     || val->value.int_val < 0) {
-                    canBeConvertedToByteArray = false;
-                    break;
-                }
-            }
-
-            if (canBeConvertedToByteArray) {
-                QByteArray array;
-                for (int idx = 0; value->value.list_val[idx]; idx++) {
-                    array.append(value->value.list_val[idx]->value.int_val);
-                }
-                return array;
-            }
-
-           // Create normal list
-           QVariantList list;
-           for (int idx = 0; value->value.list_val[idx]; idx++) {
-             list.append(valueToVariant(value->value.list_val[idx]));
-           }
-           return list;
-        }
-    }
-    
-    case CONN_SETTINGS_VALUE_BYTE_ARRAY:
-        return QByteArray::fromRawData((char *)value->value.byte_array.val, 
-                                       value->value.byte_array.len);
-    
-    default:
-        return QVariant();
-    }
-}
-
-// Public class implementation
-
-IAPConf::IAPConf(const QString &iap_id)
-    : d_ptr(new IAPConfPrivate)
-{
-    d_ptr->settings = conn_settings_open(CONN_SETTINGS_CONNECTION,
-                                         QSTRING_TO_CONST_CSTR(iap_id));
-    if (d_ptr->settings == 0) {
-        qWarning("IAPConf: Unable to open ConnSettings for %s", 
-                 QSTRING_TO_CONST_CSTR(iap_id));
-    }
-}
-
-IAPConf::~IAPConf()
-{
-    conn_settings_close(d_ptr->settings);
-    delete d_ptr;
-}
-
-
-QVariant IAPConf::value(const QString& key) const
-{
-    ConnSettingsValue *val = conn_settings_get(d_ptr->settings,
-                                               QSTRING_TO_CONST_CSTR(key));
-
-    QVariant variant = d_ptr->valueToVariant(val);
-    conn_settings_value_destroy(val);
-    return variant;
-}
-
-
-void IAPConf::getAll(QList<QString> &all_iaps, bool return_path)
-{
-    Q_UNUSED(return_path); // We don't use return path currently
-
-    // Go through all available connections and add them to the list
-    char **ids = conn_settings_list_ids(CONN_SETTINGS_CONNECTION);
-    if (ids == 0) {
-        // No ids found - nothing to do
-        return;
-    }
-
-    for (int idx = 0; ids[idx]; idx++) {
-        all_iaps.append(QString(ids[idx]));
-        free(ids[idx]);
-    }
-    free(ids);
-}
-
-
-} // namespace Maemo
diff --git a/src/plugins/bearer/icd/iapconf.h b/src/plugins/bearer/icd/iapconf.h
deleted file mode 100644 (file)
index 791ec84..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef IAPCONF_H
-#define IAPCONF_H
-
-#include <QString>
-#include <QVariant>
-
-namespace Maemo {
-
-class IAPConfPrivate;
-class IAPConf {
-public:
-    IAPConf(const QString &iap_id);
-    virtual ~IAPConf();
-
-    /**
-        Get one IAP value.
-    */
-    QVariant value(const QString& key) const;
-
-    /**
-        Return all the IAPs found in the system. If return_path is true,
-       then do not strip the IAP path away.
-    */
-    static void getAll(QList<QString> &all_iaps, bool return_path=false);
-
-private:
-    IAPConfPrivate *d_ptr;
-};
-
-} // namespace Maemo
-
-#endif
diff --git a/src/plugins/bearer/icd/iapmonitor.cpp b/src/plugins/bearer/icd/iapmonitor.cpp
deleted file mode 100644 (file)
index da8028a..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QStringList>
-
-#include <conn_settings.h>
-#include "iapmonitor.h"
-
-namespace Maemo {
-
-
-void conn_settings_notify_func (ConnSettingsType type,
-                                const char *id,
-                                const char *key,
-                                ConnSettingsValue *value,
-                                void *user_data);
-
-class IAPMonitorPrivate {
-private:
-    IAPMonitor *monitor;
-    ConnSettings *settings;
-
-public:
-
-    IAPMonitorPrivate(IAPMonitor *monitor)
-        : monitor(monitor)
-    {
-        settings = conn_settings_open(CONN_SETTINGS_CONNECTION, NULL);
-        conn_settings_add_notify(
-                        settings,
-                        (ConnSettingsNotifyFunc *)conn_settings_notify_func,
-                        this);
-    }
-
-    ~IAPMonitorPrivate()
-    {
-        conn_settings_del_notify(settings);
-        conn_settings_close(settings);
-    }
-
-    void iapAdded(const QString &iap)
-    {
-        monitor->iapAdded(iap);
-    }
-
-    void iapRemoved(const QString &iap)
-    {
-        monitor->iapRemoved(iap);
-    }
-};
-
-void conn_settings_notify_func (ConnSettingsType type,
-                                const char *id,
-                                const char *key,
-                                ConnSettingsValue *value,
-                                void *user_data)
-{
-    Q_UNUSED(id);
-
-    if (type != CONN_SETTINGS_CONNECTION) return;
-    IAPMonitorPrivate *priv = (IAPMonitorPrivate *)user_data;
-
-    QString iapId(key);
-    iapId = iapId.split("/")[0];
-    if (value != 0) {
-        priv->iapAdded(iapId);
-    } else if (iapId == QString(key)) {
-        // IAP is removed only when the directory gets removed
-        priv->iapRemoved(iapId);
-    }
-}
-
-IAPMonitor::IAPMonitor()
-    : d_ptr(new IAPMonitorPrivate(this))
-{
-}
-
-IAPMonitor::~IAPMonitor()
-{
-    delete d_ptr;
-}
-
-void IAPMonitor::iapAdded(const QString &id)
-{
-    Q_UNUSED(id);
-    // By default do nothing
-}
-
-void IAPMonitor::iapRemoved(const QString &id)
-{
-    Q_UNUSED(id);
-    // By default do nothing
-}
-
-} // namespace Maemo
diff --git a/src/plugins/bearer/icd/iapmonitor.h b/src/plugins/bearer/icd/iapmonitor.h
deleted file mode 100644 (file)
index 634db00..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef IAPMONITOR_H
-#define IAPMONITOR_H
-
-#include <QString>
-
-namespace Maemo {
-
-class IAPMonitorPrivate;
-class IAPMonitor {
-public:
-    IAPMonitor();
-    ~IAPMonitor();
-
-protected:
-    virtual void iapAdded(const QString &id);
-    virtual void iapRemoved(const QString &id);
-
-private:
-    IAPMonitorPrivate *d_ptr;
-    Q_DECLARE_PRIVATE(IAPMonitor);
-};
-
-} // namespace Maemo
-
-#endif // IAPMONITOR_H
-
diff --git a/src/plugins/bearer/icd/icdmain.cpp b/src/plugins/bearer/icd/icdmain.cpp
deleted file mode 100644 (file)
index 6ffc5ae..0000000
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qicdengine.h"
-
-#include <QtNetwork/qbearerplugin_p.h>
-
-#include <QtCore/qdebug.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-class QIcdEnginePlugin : public QBearerEnginePlugin
-{
-public:
-    QIcdEnginePlugin();
-    ~QIcdEnginePlugin();
-
-    QStringList keys() const;
-    QBearerEngine *create(const QString &key) const;
-};
-
-QIcdEnginePlugin::QIcdEnginePlugin()
-{
-}
-
-QIcdEnginePlugin::~QIcdEnginePlugin()
-{
-}
-
-QStringList QIcdEnginePlugin::keys() const
-{
-    return QStringList() << QLatin1String("icd");
-}
-
-QBearerEngine *QIcdEnginePlugin::create(const QString &key) const
-{
-    if (key == QLatin1String("icd"))
-        return new QIcdEngine;
-    else
-        return 0;
-}
-
-Q_EXPORT_STATIC_PLUGIN(QIcdEnginePlugin)
-Q_EXPORT_PLUGIN2(qicdbearer, QIcdEnginePlugin)
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/plugins/bearer/icd/maemo_icd.cpp b/src/plugins/bearer/icd/maemo_icd.cpp
deleted file mode 100644 (file)
index a7a4a29..0000000
+++ /dev/null
@@ -1,856 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include "maemo_icd.h"
-#include "dbusdispatcher.h"
-
-#include <QObject>
-#include <QTimer>
-#include <QCoreApplication>
-#include <QEventLoop>
-#include <QDebug>
-#include <dbus/dbus.h>
-#include <dbus/dbus-glib-lowlevel.h>
-
-#include <stdio.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-namespace Maemo {
-
-#undef PRINT_DEBUGINFO
-#ifdef PRINT_DEBUGINFO
-  static FILE *fdebug = NULL;
-#define PDEBUG(fmt, args...)                                           \
-  do {                                                                 \
-    struct timeval tv;                                                 \
-    gettimeofday(&tv, 0);                                              \
-    fprintf(fdebug, "DEBUG[%d]:%ld.%ld:%s:%s():%d: " fmt,              \
-           getpid(),                                                   \
-           tv.tv_sec, tv.tv_usec,                                      \
-           __FILE__, __FUNCTION__, __LINE__, args);                    \
-    fflush(fdebug);                                                    \
-  } while(0)
-#else
-#define PDEBUG(fmt...)
-#endif
-
-
-class IcdPrivate
-{
-public:
-    IcdPrivate(Icd *myfriend)
-    {
-        init(10000, IcdNewDbusInterface, myfriend);
-    }
-
-    IcdPrivate(unsigned int timeout, Icd *myfriend)
-    {
-        init(timeout, IcdNewDbusInterface, myfriend);
-    }
-
-    IcdPrivate(unsigned int timeout, IcdDbusInterfaceVer ver, Icd *myfriend)
-    {
-        Q_UNUSED(ver);
-
-        /* Note that the old Icd interface is currently disabled and
-        * the new one is always used.
-        */
-        init(timeout, IcdNewDbusInterface, myfriend);
-    }
-
-    ~IcdPrivate()
-    {
-      QObject::disconnect(mDBus, 
-                         SIGNAL(signalReceived(const QString&, 
-                                               const QString&,
-                                               const QList<QVariant>&)),
-                         icd,
-                         SLOT(icdSignalReceived(const QString&, 
-                                                const QString&,
-                                                const QList<QVariant>&)));
-
-      QObject::disconnect(mDBus,
-                         SIGNAL(callReply(const QString&,
-                                          const QList<QVariant>&,
-                                          const QString&)),
-                         icd,
-                         SLOT(icdCallReply(const QString&,
-                                           const QList<QVariant>&,
-                                           const QString&)));
-
-        delete mDBus;
-        mDBus = 0;
-    }
-
-    /* Icd2 dbus API functions */
-    QStringList scan(icd_scan_request_flags flags,
-                    QStringList &network_types,
-                    QList<IcdScanResult>& scan_results,
-                    QString& error);
-
-    uint state(QString& service_type, uint service_attrs,
-              QString& service_id, QString& network_type,
-              uint network_attrs, QByteArray& network_id,
-              IcdStateResult &state_result);
-
-    uint addrinfo(QString& service_type, uint service_attrs,
-                 QString& service_id, QString& network_type,
-                 uint network_attrs, QByteArray& network_id,
-                 IcdAddressInfoResult& addr_result);
-
-    uint state(QList<IcdStateResult>& state_results);
-    uint statistics(QList<IcdStatisticsResult>& stats_results);
-    uint addrinfo(QList<IcdAddressInfoResult>& addr_results);
-
-    void signalReceived(const QString& interface, 
-                        const QString& signal,
-                        const QList<QVariant>& args);
-    void callReply(const QString& method, 
-                   const QList<QVariant>& args,
-                   const QString& error);
-
-public:
-    DBusDispatcher *mDBus;
-    QString mMethod;
-    QString mInterface;
-    QString mSignal;
-    QString mError;
-    QList<QVariant> mArgs;
-    QList<QVariant> receivedSignals;
-    unsigned int timeout;
-    IcdDbusInterfaceVer icd_dbus_version;
-    Icd *icd;
-
-    void init(unsigned int dbus_timeout, IcdDbusInterfaceVer ver,
-             Icd *myfriend)
-    {
-      if (ver == IcdNewDbusInterface) {
-       mDBus = new DBusDispatcher(ICD_DBUS_API_INTERFACE,
-                                  ICD_DBUS_API_PATH,
-                                  ICD_DBUS_API_INTERFACE);
-      } else {
-       mDBus = new DBusDispatcher(ICD_DBUS_SERVICE,
-                                  ICD_DBUS_PATH,
-                                  ICD_DBUS_INTERFACE);
-      }
-      icd_dbus_version = ver;
-
-      /* This connect has a side effect as it means that only one
-       * Icd object can exists in one time. This should be fixed!
-       */
-      QObject::connect(mDBus, 
-                      SIGNAL(signalReceived(const QString&, 
-                                            const QString&,
-                                            const QList<QVariant>&)),
-                      myfriend,
-                      SLOT(icdSignalReceived(const QString&, 
-                                             const QString&,
-                                             const QList<QVariant>&)));
-
-      QObject::connect(mDBus,
-                      SIGNAL(callReply(const QString&,
-                                       const QList<QVariant>&,
-                                       const QString&)),
-                      myfriend,
-                      SLOT(icdCallReply(const QString&,
-                                        const QList<QVariant>&,
-                                        const QString&)));
-
-      icd = myfriend;
-      timeout = dbus_timeout;
-
-#ifdef PRINT_DEBUGINFO
-      if (!fdebug) {
-       fdebug = fopen("/tmp/maemoicd.log", "a+");
-      }
-      PDEBUG("created %s\n", "IcdPrivate");
-#endif
-    }
-
-    void clearState()
-    {
-      mMethod.clear();
-      mInterface.clear();
-      mSignal.clear();
-      mError.clear();
-      mArgs.clear();
-      receivedSignals.clear();
-    }
-
-    bool doState();
-};
-
-
-void IcdPrivate::signalReceived(const QString& interface, 
-                               const QString& signal,
-                               const QList<QVariant>& args)
-{
-    // Signal handler, which simply records what has been signalled
-    mInterface = interface;
-    mSignal = signal;
-    mArgs = args;
-
-    //qDebug() << "signal" << signal << "received:" << args;
-    receivedSignals << QVariant(interface) << QVariant(signal) << QVariant(args);
-}
-
-
-void IcdPrivate::callReply(const QString& method, 
-                          const QList<QVariant>& /*args*/,
-                          const QString& error)
-{
-    mMethod = method;
-    mError = error;
-}
-
-
-static void get_scan_result(QList<QVariant>& args,
-                           IcdScanResult& ret)
-{
-    int i=0;
-
-    if (args.isEmpty())
-      return;
-
-    ret.status = args[i++].toUInt();
-    ret.timestamp = args[i++].toUInt();
-    ret.scan.service_type = args[i++].toString();
-    ret.service_name = args[i++].toString();
-    ret.scan.service_attrs = args[i++].toUInt();
-    ret.scan.service_id = args[i++].toString();
-    ret.service_priority = args[i++].toInt();
-    ret.scan.network_type = args[i++].toString();
-    ret.network_name = args[i++].toString();
-    ret.scan.network_attrs = args[i++].toUInt();
-    ret.scan.network_id = args[i++].toByteArray();
-    ret.network_priority = args[i++].toInt();
-    ret.signal_strength = args[i++].toInt();
-    ret.station_id = args[i++].toString();
-    ret.signal_dB = args[i++].toInt();
-}
-
-
-QStringList IcdPrivate::scan(icd_scan_request_flags flags,
-                            QStringList &network_types,
-                            QList<IcdScanResult>& scan_results,
-                            QString& error)
-{
-    Q_UNUSED(network_types);
-
-    QStringList scanned_types;
-    QTimer timer;
-    QVariant reply;
-    QVariantList vl;
-    bool last_result = false;
-    IcdScanResult result;
-    int all_waited;
-    
-    clearState();
-    reply = mDBus->call(ICD_DBUS_API_SCAN_REQ, (uint)flags);
-    if (reply.type() != QVariant::List)
-        return scanned_types;
-    vl = reply.toList();
-    if (vl.isEmpty()) {
-        error = "Scan did not return anything.";
-       return scanned_types;
-    }
-    reply = vl.first();
-    scanned_types = reply.toStringList();
-    //qDebug() << "Scanning:" << scanned_types;
-    all_waited = scanned_types.size();
-
-    timer.setSingleShot(true);
-    timer.start(timeout);
-
-    scan_results.clear();
-    while (!last_result) {
-       while (timer.isActive() && mInterface.isEmpty() && mError.isEmpty()) {
-           QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
-       }
-
-       if (!timer.isActive()) {
-           //qDebug() << "Timeout happened";
-           break;
-       }
-
-       if (mSignal != ICD_DBUS_API_SCAN_SIG) {
-           //qDebug() << "Received" << mSignal << "while waiting" << ICD_DBUS_API_SCAN_SIG << ", ignoring";
-           mInterface.clear();
-           continue;
-       }
-
-       if (mError.isEmpty()) {
-           QString msgInterface = receivedSignals.takeFirst().toString();
-           QString msgSignal = receivedSignals.takeFirst().toString();
-           QList<QVariant> msgArgs = receivedSignals.takeFirst().toList();
-           //qDebug() << "Signal" << msgSignal << "received.";
-           //qDebug() << "Params:" << msgArgs;
-
-           while (!msgSignal.isEmpty()) {
-               get_scan_result(msgArgs, result);
-
-#if 0
-               qDebug() << "Received: " <<
-                   "status =" << result.status <<
-                   ", timestamp =" << result.timestamp <<
-                   ", service_type =" << result.scan.service_type <<
-                   ", service_name =" << result.service_name <<
-                   ", service_attrs =" << result.scan.service_attrs <<
-                   ", service_id =" << result.scan.service_id <<
-                   ", service_priority =" << result.service_priority <<
-                   ", network_type =" << result.scan.network_type <<
-                   ", network_name =" << result.network_name <<
-                   ", network_attrs =" << result.scan.network_attrs <<
-                   ", network_id =" << "-" <<
-                   ", network_priority =" << result.network_priority <<
-                   ", signal_strength =" << result.signal_strength <<
-                   ", station_id =" << result.station_id <<
-                   ", signal_dB =" << result.signal_dB;
-#endif
-
-               if (result.status == ICD_SCAN_COMPLETE) {
-                   //qDebug() << "waited =" << all_waited;
-                   if (--all_waited == 0) {
-                       last_result = true;
-                       break;
-                   }
-               } else
-                   scan_results << result;
-
-               if (receivedSignals.isEmpty())
-                   break;
-
-               msgInterface = receivedSignals.takeFirst().toString();
-               msgSignal = receivedSignals.takeFirst().toString();
-               msgArgs = receivedSignals.takeFirst().toList();
-           }
-           mInterface.clear();
-
-       } else {
-           qWarning() << "Error while scanning:" << mError;
-           break;
-       }
-    }
-    timer.stop();
-
-    error = mError;
-    return scanned_types;
-}
-
-
-static void get_state_all_result(QList<QVariant>& args,
-                                IcdStateResult& ret)
-{
-    int i=0;
-
-    ret.params.service_type = args[i++].toString();
-    ret.params.service_attrs = args[i++].toUInt();
-    ret.params.service_id = args[i++].toString();
-    ret.params.network_type = args[i++].toString();
-    ret.params.network_attrs = args[i++].toUInt();
-    ret.params.network_id = args[i++].toByteArray();
-    ret.error = args[i++].toString();
-    ret.state = args[i++].toInt();
-}
-
-
-static void get_state_all_result2(QList<QVariant>& args,
-                                IcdStateResult& ret)
-{
-    int i=0;
-
-    ret.params.network_type = args[i++].toString();
-    ret.state = args[i++].toInt();
-
-    // Initialize the other values so that the caller can
-    // notice we only returned partial status
-    ret.params.service_type = QString();
-    ret.params.service_attrs = 0;
-    ret.params.service_id = QString();
-    ret.params.network_attrs = 0;
-    ret.params.network_id = QByteArray();
-    ret.error = QString();
-}
-
-
-uint IcdPrivate::state(QString& service_type, uint service_attrs,
-                      QString& service_id, QString& network_type,
-                      uint network_attrs, QByteArray& network_id,
-                      IcdStateResult& state_result)
-{
-    QTimer timer;
-    QVariant reply;
-    uint total_signals;
-    QVariantList vl;
-
-    clearState();
-
-    reply = mDBus->call(ICD_DBUS_API_STATE_REQ,
-                       service_type, service_attrs, service_id,
-                       network_type, network_attrs, network_id);
-    if (reply.type() != QVariant::List)
-        return 0;
-    vl = reply.toList();
-    if (vl.isEmpty())
-        return 0;
-    reply = vl.first();
-    total_signals = reply.toUInt();
-    if (!total_signals)
-        return 0;
-
-    timer.setSingleShot(true);
-    timer.start(timeout);
-
-    mInterface.clear();
-    while (timer.isActive() && mInterface.isEmpty()) {
-        QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
-
-       if (mSignal != ICD_DBUS_API_STATE_SIG) {
-            mInterface.clear();
-           continue;
-       }
-    }
-
-    timer.stop();
-
-    if (mError.isEmpty()) {
-        if (!mArgs.isEmpty()) {
-           if (mArgs.size()>2)
-               get_state_all_result(mArgs, state_result);
-           else {
-               // We are not connected as we did not get the status we asked
-               return 0;
-           }
-       }
-    } else {
-        qWarning() << "Error:" << mError;
-    }
-
-    // The returned value should be one because we asked for one state
-    return total_signals;
-}
-
-
-/* Special version of the state() call which does not call event loop.
- * Needed in order to fix NB#175098 where Qt4.7 webkit crashes because event
- * loop is run when webkit does not expect it. This function is called from
- * bearer management API syncStateWithInterface() in QNetworkSession
- * constructor.
- */
-uint IcdPrivate::state(QList<IcdStateResult>& state_results)
-{
-    QVariant reply;
-    QVariantList vl;
-    uint signals_left, total_signals;
-    IcdStateResult result;
-    time_t started;
-    int timeout_secs = timeout / 1000;
-
-    PDEBUG("%s\n", "state_results");
-
-    clearState();
-    reply = mDBus->call(ICD_DBUS_API_STATE_REQ);
-    if (reply.type() != QVariant::List)
-        return 0;
-    vl = reply.toList();
-    if (vl.isEmpty())
-        return 0;
-    reply = vl.first();
-    signals_left = total_signals = reply.toUInt();
-    if (!signals_left)
-        return 0;
-
-    started = time(0);
-    state_results.clear();
-    mError.clear();
-    while (signals_left) {
-        mInterface.clear();
-       while ((time(0)<=(started+timeout_secs)) && mInterface.isEmpty()) {
-           mDBus->synchronousDispatch(1000);
-        QCoreApplication::sendPostedEvents(icd, QEvent::MetaCall);
-       }
-
-        if (time(0)>(started+timeout_secs)) {
-           total_signals = 0;
-           break;
-       }
-
-       if (mSignal != ICD_DBUS_API_STATE_SIG) {
-           continue;
-       }
-
-       if (mError.isEmpty()) {
-           if (!mArgs.isEmpty()) {
-               if (mArgs.size()==2)
-                   get_state_all_result2(mArgs, result);
-               else
-                   get_state_all_result(mArgs, result);
-               state_results << result;
-           }
-           signals_left--;
-       } else {
-           qWarning() << "Error:" << mError;
-           break;
-       }
-    }
-
-    PDEBUG("total_signals=%d\n", total_signals);
-    return total_signals;
-}
-
-
-static void get_statistics_all_result(QList<QVariant>& args,
-                                     IcdStatisticsResult& ret)
-{
-    int i=0;
-
-    if (args.isEmpty())
-      return;
-
-    ret.params.service_type = args[i++].toString();
-    ret.params.service_attrs = args[i++].toUInt();
-    ret.params.service_id = args[i++].toString();
-    ret.params.network_type = args[i++].toString();
-    ret.params.network_attrs = args[i++].toUInt();
-    ret.params.network_id = args[i++].toByteArray();
-    ret.time_active = args[i++].toUInt();
-    ret.signal_strength = (enum icd_nw_levels)args[i++].toUInt();
-    ret.bytes_sent = args[i++].toUInt();
-    ret.bytes_received = args[i++].toUInt();
-}
-
-
-uint IcdPrivate::statistics(QList<IcdStatisticsResult>& stats_results)
-{
-    QTimer timer;
-    QVariant reply;
-    QVariantList vl;
-    uint signals_left, total_signals;
-    IcdStatisticsResult result;
-
-    clearState();
-    reply = mDBus->call(ICD_DBUS_API_STATISTICS_REQ);
-    if (reply.type() != QVariant::List)
-        return 0;
-    vl = reply.toList();
-    if (vl.isEmpty())
-        return 0;
-    reply = vl.first();
-    if (reply.type() != QVariant::UInt)
-        return 0;
-    signals_left = total_signals = reply.toUInt();
-
-    if (!signals_left)
-        return 0;
-
-    timer.setSingleShot(true);
-    timer.start(timeout);
-    stats_results.clear();
-    while (signals_left) {
-       mInterface.clear();
-       while (timer.isActive() && mInterface.isEmpty()) {
-           QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
-       }
-
-       if (!timer.isActive()) {
-           total_signals = 0;
-           break;
-       }
-
-       if (mSignal != ICD_DBUS_API_STATISTICS_SIG) {
-           continue;
-       }
-
-       if (mError.isEmpty()) {
-           get_statistics_all_result(mArgs, result);
-           stats_results << result;
-           signals_left--;
-       } else {
-           qWarning() << "Error:" << mError;
-           break;
-       }
-    }
-    timer.stop();
-
-    return total_signals;
-}
-
-
-static void get_addrinfo_all_result(QList<QVariant>& args,
-                                   IcdAddressInfoResult& ret)
-{
-    int i=0;
-
-    if (args.isEmpty())
-      return;
-
-    ret.params.service_type = args[i++].toString();
-    ret.params.service_attrs = args[i++].toUInt();
-    ret.params.service_id = args[i++].toString();
-    ret.params.network_type = args[i++].toString();
-    ret.params.network_attrs = args[i++].toUInt();
-    ret.params.network_id = args[i++].toByteArray();
-
-    QVariantList vl = args[i].toList();
-    QVariant reply = vl.first();
-    QList<QVariant> lst = reply.toList();
-    for (int k=0; k<lst.size()/6; k=k+6) {
-        IcdIPInformation ip_info;
-       ip_info.address = lst[k].toString();
-       ip_info.netmask = lst[k++].toString();
-       ip_info.default_gateway = lst[k++].toString();
-       ip_info.dns1 = lst[k++].toString();
-       ip_info.dns2 = lst[k++].toString();
-       ip_info.dns3 = lst[k++].toString();
-
-       ret.ip_info << ip_info;
-    }
-}
-
-
-/* Special version of the addrinfo() call which does not call event loop.
- * Needed in order to fix NB#175098 where Qt4.7 webkit crashes because event
- * loop is run when webkit does not expect it. This function is called from
- * bearer management API syncStateWithInterface() in QNetworkSession
- * constructor.
- */
-uint IcdPrivate::addrinfo(QList<IcdAddressInfoResult>& addr_results)
-{
-    QVariant reply;
-    QVariantList vl;
-    uint signals_left, total_signals;
-    IcdAddressInfoResult result;
-    time_t started;
-    int timeout_secs = timeout / 1000;
-
-    PDEBUG("%s\n", "addr_results");
-
-    clearState();
-    reply = mDBus->call(ICD_DBUS_API_ADDRINFO_REQ);
-    if (reply.type() != QVariant::List)
-        return 0;
-    vl = reply.toList();
-    if (vl.isEmpty())
-        return 0;
-    reply = vl.first();
-    if (reply.type() != QVariant::UInt)
-        return 0;
-    signals_left = total_signals = reply.toUInt();
-    if (!signals_left)
-        return 0;
-
-    started = time(0);
-    addr_results.clear();
-    while (signals_left) {
-        mInterface.clear();
-       while ((time(0)<=(started+timeout_secs)) && mInterface.isEmpty()) {
-           mDBus->synchronousDispatch(1000);
-        QCoreApplication::sendPostedEvents(icd, QEvent::MetaCall);
-       }
-
-        if (time(0)>(started+timeout_secs)) {
-           total_signals = 0;
-           break;
-       }
-
-       if (mSignal != ICD_DBUS_API_ADDRINFO_SIG) {
-           continue;
-       }
-
-       if (mError.isEmpty()) {
-           get_addrinfo_all_result(mArgs, result);
-           addr_results << result;
-           signals_left--;
-       } else {
-           qWarning() << "Error:" << mError;
-           break;
-       }
-    }
-
-    PDEBUG("total_signals=%d\n", total_signals);
-    return total_signals;
-}
-
-
-uint IcdPrivate::addrinfo(QString& service_type, uint service_attrs,
-                         QString& service_id, QString& network_type,
-                         uint network_attrs, QByteArray& network_id,
-                         IcdAddressInfoResult& addr_result)
-{
-    QTimer timer;
-    QVariant reply;
-    uint total_signals;
-    QVariantList vl;
-
-    clearState();
-
-    reply = mDBus->call(ICD_DBUS_API_ADDRINFO_REQ,
-                       service_type, service_attrs, service_id,
-                       network_type, network_attrs, network_id);
-    if (reply.type() != QVariant::List)
-        return 0;
-    vl = reply.toList();
-    if (vl.isEmpty())
-        return 0;
-    reply = vl.first();
-    total_signals = reply.toUInt();
-
-    if (!total_signals)
-        return 0;
-
-    timer.setSingleShot(true);
-    timer.start(timeout);
-
-    mInterface.clear();
-    while (timer.isActive() && mInterface.isEmpty()) {
-        QCoreApplication::processEvents(QEventLoop::AllEvents, 1000);
-
-       if (mSignal != ICD_DBUS_API_ADDRINFO_SIG) {
-            mInterface.clear();
-           continue;
-       }
-    }
-
-    timer.stop();
-
-    if (mError.isEmpty()) {
-        get_addrinfo_all_result(mArgs, addr_result);
-    } else {
-        qWarning() << "Error:" << mError;
-    }
-
-    // The returned value should be one because we asked for one addrinfo
-    return total_signals;
-}
-
-
-Icd::Icd(QObject *parent)
-  : QObject(parent), d(new IcdPrivate(this))
-{
-}
-
-Icd::Icd(unsigned int timeout, QObject *parent)
-  : QObject(parent), d(new IcdPrivate(timeout, this))
-{
-}
-
-Icd::Icd(unsigned int timeout, IcdDbusInterfaceVer ver, QObject *parent)
-  : QObject(parent), d(new IcdPrivate(timeout, ver, this))
-{
-}
-
-Icd::~Icd()
-{
-    delete d;
-}
-
-
-QStringList Icd::scan(icd_scan_request_flags flags,
-                     QStringList &network_types,
-                     QList<IcdScanResult>& scan_results,
-                     QString& error)
-{
-    return d->scan(flags, network_types, scan_results, error);
-}
-
-
-uint Icd::state(QString& service_type, uint service_attrs,
-               QString& service_id, QString& network_type,
-               uint network_attrs, QByteArray& network_id,
-               IcdStateResult &state_result)
-{
-    return d->state(service_type, service_attrs, service_id,
-                   network_type, network_attrs, network_id,
-                   state_result);
-}
-
-
-uint Icd::addrinfo(QString& service_type, uint service_attrs,
-                  QString& service_id, QString& network_type,
-                  uint network_attrs, QByteArray& network_id,
-                  IcdAddressInfoResult& addr_result)
-{
-    return d->addrinfo(service_type, service_attrs, service_id,
-                      network_type, network_attrs, network_id,
-                      addr_result);
-}
-
-
-uint Icd::state(QList<IcdStateResult>& state_results)
-{
-    return d->state(state_results);
-}
-
-
-uint Icd::statistics(QList<IcdStatisticsResult>& stats_results)
-{
-    return d->statistics(stats_results);
-}
-
-
-uint Icd::addrinfo(QList<IcdAddressInfoResult>& addr_results)
-{
-    return d->addrinfo(addr_results);
-}
-
-
-void Icd::icdSignalReceived(const QString& interface, 
-                        const QString& signal,
-                        const QList<QVariant>& args)
-{
-    d->signalReceived(interface, signal, args);
-}
-
-
-void Icd::icdCallReply(const QString& method, 
-                   const QList<QVariant>& args,
-                   const QString& error)
-{
-    d->callReply(method, args, error);
-}
-
-}  // Maemo namespace
-
-
-#include "moc_maemo_icd.h"
diff --git a/src/plugins/bearer/icd/maemo_icd.h b/src/plugins/bearer/icd/maemo_icd.h
deleted file mode 100644 (file)
index 48cea02..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef MAEMO_ICD_H
-#define MAEMO_ICD_H
-
-#include <QObject>
-#include <QStringList>
-#include <QByteArray>
-#include <QMetaType>
-#include <QtDBus>
-#include <QDBusArgument>
-
-#include <glib.h>
-#include <icd/dbus_api.h>
-#include <icd/osso-ic.h>
-#include <icd/osso-ic-dbus.h>
-#include <icd/network_api_defines.h>
-
-#define ICD_LONG_SCAN_TIMEOUT (30*1000)  /* 30sec */
-#define ICD_SHORT_SCAN_TIMEOUT (10*1000)  /* 10sec */
-#define ICD_SHORT_CONNECT_TIMEOUT (10*1000) /* 10sec */
-#define ICD_LONG_CONNECT_TIMEOUT (150*1000) /* 2.5min */
-
-namespace Maemo {
-
-struct CommonParams {
-       QString service_type;
-       uint service_attrs;
-       QString service_id;
-       QString network_type;
-       uint network_attrs;
-       QByteArray network_id;
-};
-
-struct IcdScanResult {
-       uint status; // see #icd_scan_status
-       uint timestamp; // when last seen
-       QString service_name;
-       uint service_priority; // within a service type
-       QString network_name;
-       uint network_priority;
-       struct CommonParams scan;
-       uint signal_strength; // quality, 0 (none) - 10 (good)
-       QString station_id; // e.g. MAC address or similar id
-       uint signal_dB; // use signal strength above unless you know what you are doing
-
-       IcdScanResult() {
-               status = timestamp = scan.service_attrs = service_priority =
-                       scan.network_attrs = network_priority = signal_strength =
-                       signal_dB = 0;
-       }
-};
-
-struct IcdStateResult {
-       struct CommonParams params;
-       QString error;
-       uint state;
-};
-
-struct IcdStatisticsResult {
-       struct CommonParams params;
-       uint time_active;  // in seconds
-       enum icd_nw_levels signal_strength; // see network_api_defines.h in icd2-dev package
-       uint bytes_sent;
-       uint bytes_received;
-};
-
-struct IcdIPInformation {
-       QString address;
-       QString netmask;
-       QString default_gateway;
-       QString dns1;
-       QString dns2;
-       QString dns3;
-};
-
-struct IcdAddressInfoResult {
-       struct CommonParams params;
-       QList<IcdIPInformation> ip_info;
-};
-
-enum IcdDbusInterfaceVer {
-       IcdOldDbusInterface = 0,  // use the old OSSO-IC interface
-       IcdNewDbusInterface       // use the new Icd2 interface (default)
-};
-
-
-class IcdPrivate;
-class Icd : public QObject
-{
-    Q_OBJECT
-
-public:
-    Icd(QObject *parent = 0);
-    Icd(unsigned int timeout, QObject *parent = 0);
-    Icd(unsigned int timeout, IcdDbusInterfaceVer ver, QObject *parent = 0);
-    ~Icd();
-
-    /* Icd2 dbus API functions */
-    QStringList scan(icd_scan_request_flags flags,
-                    QStringList &network_types,
-                    QList<IcdScanResult>& scan_results,
-                    QString& error);
-
-    uint state(QString& service_type, uint service_attrs,
-              QString& service_id, QString& network_type,
-              uint network_attrs, QByteArray& network_id,
-              IcdStateResult &state_result);
-
-    uint addrinfo(QString& service_type, uint service_attrs,
-                 QString& service_id, QString& network_type,
-                 uint network_attrs, QByteArray& network_id,
-                 IcdAddressInfoResult& addr_result);
-
-    uint state(QList<IcdStateResult>& state_results);
-    uint statistics(QList<IcdStatisticsResult>& stats_results);
-    uint addrinfo(QList<IcdAddressInfoResult>& addr_results);
-
-private Q_SLOTS:
-    void icdSignalReceived(const QString& interface, 
-                        const QString& signal,
-                        const QList<QVariant>& args);
-    void icdCallReply(const QString& method, 
-                   const QList<QVariant>& args,
-                   const QString& error);
-
-private:
-    IcdPrivate *d;
-    friend class IcdPrivate;
-};
-
-}  // Maemo namespace
-
-#endif
diff --git a/src/plugins/bearer/icd/proxyconf.cpp b/src/plugins/bearer/icd/proxyconf.cpp
deleted file mode 100644 (file)
index 6f7b7a0..0000000
+++ /dev/null
@@ -1,424 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#include <QVariant>
-#include <QStringList>
-#include <QDebug>
-#include <QWriteLocker>
-#include <QtNetwork/qnetworkproxy.h>
-#include <QNetworkProxy>
-#include <gconf/gconf-value.h>
-#include <gconf/gconf-client.h>
-#include "proxyconf.h"
-
-#define CONF_PROXY "/system/proxy"
-#define HTTP_PROXY "/system/http_proxy"
-
-
-namespace Maemo {
-
-static QString convertKey(const char *key)
-{
-    return QString::fromUtf8(key);
-}
-
-static QVariant convertValue(GConfValue *src)
-{
-    if (!src) {
-        return QVariant();
-    } else {
-        switch (src->type) {
-        case GCONF_VALUE_INVALID:
-            return QVariant(QVariant::Invalid);
-        case GCONF_VALUE_BOOL:
-            return QVariant((bool)gconf_value_get_bool(src));
-        case GCONF_VALUE_INT:
-            return QVariant(gconf_value_get_int(src));
-        case GCONF_VALUE_FLOAT:
-            return QVariant(gconf_value_get_float(src));
-        case GCONF_VALUE_STRING:
-            return QVariant(QString::fromUtf8(gconf_value_get_string(src)));
-        case GCONF_VALUE_LIST:
-            switch (gconf_value_get_list_type(src)) {
-            case GCONF_VALUE_STRING:
-                {
-                    QStringList result;
-                    for (GSList *elts = gconf_value_get_list(src); elts; elts = elts->next)
-                        result.append(QString::fromUtf8(gconf_value_get_string((GConfValue *)elts->data)));
-                    return QVariant(result);
-                }
-            default:
-                {
-                    QList<QVariant> result;
-                    for (GSList *elts = gconf_value_get_list(src); elts; elts = elts->next)
-                        result.append(convertValue((GConfValue *)elts->data));
-                    return QVariant(result);
-                }
-            }
-        case GCONF_VALUE_SCHEMA:
-        default:
-            return QVariant();
-        }
-    }
-}
-
-
-/* Fast version of GConfItem, allows reading subtree at a time */
-class GConfItemFast {
-public:
-  GConfItemFast(const QString &k) : key(k) {}
-  QHash<QString,QVariant> getEntries() const;
-
-private:
-  QString key;
-};
-
-#define withClient(c) for (GConfClient *c = gconf_client_get_default(); c; c=0)
-
-
-QHash<QString,QVariant> GConfItemFast::getEntries() const
-{
-    QHash<QString,QVariant> children;
-
-    withClient(client) {
-        QByteArray k = key.toUtf8();
-        GSList *entries = gconf_client_all_entries(client, k.data(), NULL);
-        for (GSList *e = entries; e; e = e->next) {
-           char *key_name = strrchr(((GConfEntry *)e->data)->key, '/');
-           if (!key_name)
-               key_name = ((GConfEntry *)e->data)->key;
-           else
-               key_name++;
-           QString key(convertKey(key_name));
-           QVariant value = convertValue(((GConfEntry *)e->data)->value);
-           gconf_entry_unref((GConfEntry *)e->data);
-           //qDebug()<<"key="<<key<<"value="<<value;
-           children.insert(key, value);
-        }
-        g_slist_free (entries);
-    }
-
-    return children;
-}
-
-
-
-class NetworkProxyFactory : QNetworkProxyFactory
-{
-    ProxyConf proxy_conf;
-    bool proxy_data_read;
-
-public:
-    NetworkProxyFactory() : proxy_data_read(false) {  }
-    QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query = QNetworkProxyQuery());
-};
-
-
-QList<QNetworkProxy> NetworkProxyFactory::queryProxy(const QNetworkProxyQuery &query)
-{
-    if (proxy_data_read == false) {
-        proxy_data_read = true;
-        proxy_conf.readProxyData();
-    }
-
-    QList<QNetworkProxy> result = proxy_conf.flush(query);
-    if (result.isEmpty())
-        result << QNetworkProxy::NoProxy;
-
-    return result;
-}
-
-
-class ProxyConfPrivate {
-private:
-    // proxy values from gconf
-    QString mode;
-    bool use_http_host;
-    QString autoconfig_url;
-    QString http_proxy;
-    quint16 http_port;
-    QList<QVariant> ignore_hosts;
-    QString secure_host;
-    quint16 secure_port;
-    QString ftp_host;
-    quint16 ftp_port;
-    QString socks_host;
-    quint16 socks_port;
-    QString rtsp_host;
-    quint16 rtsp_port;
-
-    bool isHostExcluded(const QString &host);
-
-public:
-    QString prefix;
-    QString http_prefix;
-
-    void readProxyData();
-    QList<QNetworkProxy> flush(const QNetworkProxyQuery &query);
-};
-
-
-static QHash<QString,QVariant> getValues(const QString& prefix)
-{
-    GConfItemFast item(prefix);
-    return item.getEntries();
-}
-
-static QHash<QString,QVariant> getHttpValues(const QString& prefix)
-{
-    GConfItemFast item(prefix);
-    return item.getEntries();
-}
-
-#define GET(var, type)                         \
-  do {                                         \
-    QVariant v = values.value(#var);           \
-    if (v.isValid())                           \
-      var = v.to##type ();                     \
-  } while(0)
-
-#define GET_HTTP(var, name, type)              \
-  do {                                         \
-    QVariant v = httpValues.value(#name);      \
-    if (v.isValid())                           \
-      var = v.to##type ();                     \
-  } while(0)
-
-
-void ProxyConfPrivate::readProxyData()
-{
-    QHash<QString,QVariant> values = getValues(prefix);
-    QHash<QString,QVariant> httpValues = getHttpValues(http_prefix);
-
-    //qDebug()<<"values="<<values;
-
-    /* Read the proxy settings from /system/proxy* */
-    GET_HTTP(http_proxy, host, String);
-    GET_HTTP(http_port, port, Int);
-    GET_HTTP(ignore_hosts, ignore_hosts, List);
-
-    GET(mode, String);
-    GET(autoconfig_url, String);
-    GET(secure_host, String);
-    GET(secure_port, Int);
-    GET(ftp_host, String);
-    GET(ftp_port, Int);
-    GET(socks_host, String);
-    GET(socks_port, Int);
-    GET(rtsp_host, String);
-    GET(rtsp_port, Int);
-
-    if (http_proxy.isEmpty())
-        use_http_host = false;
-    else
-        use_http_host = true;
-}
-
-
-bool ProxyConfPrivate::isHostExcluded(const QString &host)
-{
-    if (host.isEmpty())
-        return true;
-
-    if (ignore_hosts.isEmpty())
-        return false;
-
-    QHostAddress ipAddress;
-    bool isIpAddress = ipAddress.setAddress(host);
-
-    foreach (QVariant h, ignore_hosts) {
-        QString entry = h.toString();
-        if (isIpAddress && ipAddress.isInSubnet(QHostAddress::parseSubnet(entry))) {
-            return true;  // excluded
-        } else {
-            // do wildcard matching
-            QRegExp rx(entry, Qt::CaseInsensitive, QRegExp::Wildcard);
-            if (rx.exactMatch(host))
-                return true;
-        }
-    }
-
-    // host was not excluded
-    return false;
-}
-
-
-QList<QNetworkProxy> ProxyConfPrivate::flush(const QNetworkProxyQuery &query)
-{
-    QList<QNetworkProxy> result;
-
-#if 0
-    qDebug()<<"http_proxy" << http_proxy;
-    qDebug()<<"http_port" << http_port;
-    qDebug()<<"ignore_hosts" << ignore_hosts;
-    qDebug()<<"use_http_host" << use_http_host;
-    qDebug()<<"mode" << mode;
-    qDebug()<<"autoconfig_url" << autoconfig_url;
-    qDebug()<<"secure_host" << secure_host;
-    qDebug()<<"secure_port" << secure_port;
-    qDebug()<<"ftp_host" << ftp_host;
-    qDebug()<<"ftp_port" << ftp_port;
-    qDebug()<<"socks_host" << socks_host;
-    qDebug()<<"socks_port" << socks_port;
-    qDebug()<<"rtsp_host" << rtsp_host;
-    qDebug()<<"rtsp_port" << rtsp_port;
-#endif
-
-    if (isHostExcluded(query.peerHostName()))
-        return result;          // no proxy for this host
-
-    if (mode == QLatin1String("AUTO")) {
-        // TODO: pac currently not supported, fix me
-        return result;
-    }
-
-    if (mode == QLatin1String("MANUAL")) {
-        bool isHttps = false;
-       QString protocol = query.protocolTag().toLower();
-
-       // try the protocol-specific proxy
-       QNetworkProxy protocolSpecificProxy;
-
-       if (protocol == QLatin1String("ftp")) {
-           if (!ftp_host.isEmpty()) {
-               protocolSpecificProxy.setType(QNetworkProxy::FtpCachingProxy);
-               protocolSpecificProxy.setHostName(ftp_host);
-               protocolSpecificProxy.setPort(ftp_port);
-           }
-       } else if (protocol == QLatin1String("http")) {
-           if (!http_proxy.isEmpty()) {
-               protocolSpecificProxy.setType(QNetworkProxy::HttpProxy);
-               protocolSpecificProxy.setHostName(http_proxy);
-               protocolSpecificProxy.setPort(http_port);
-           }
-       } else if (protocol == QLatin1String("https")) {
-           isHttps = true;
-           if (!secure_host.isEmpty()) {
-               protocolSpecificProxy.setType(QNetworkProxy::HttpProxy);
-               protocolSpecificProxy.setHostName(secure_host);
-               protocolSpecificProxy.setPort(secure_port);
-           }
-       }
-
-       if (protocolSpecificProxy.type() != QNetworkProxy::DefaultProxy)
-           result << protocolSpecificProxy;
-
-
-        if (!socks_host.isEmpty()) {
-           QNetworkProxy proxy;
-           proxy.setType(QNetworkProxy::Socks5Proxy);
-           proxy.setHostName(socks_host);
-           proxy.setPort(socks_port);
-           result << proxy;
-       }
-
-
-       // Add the HTTPS proxy if present (and if we haven't added yet)
-       if (!isHttps) {
-           QNetworkProxy https;
-           if (!secure_host.isEmpty()) {
-               https.setType(QNetworkProxy::HttpProxy);
-               https.setHostName(secure_host);
-               https.setPort(secure_port);
-           }
-
-           if (https.type() != QNetworkProxy::DefaultProxy &&
-               https != protocolSpecificProxy)
-               result << https;
-       }
-    }
-
-    return result;
-}
-
-
-ProxyConf::ProxyConf()
-    : d_ptr(new ProxyConfPrivate)
-{
-#if !GLIB_CHECK_VERSION(2,35,0)
-    g_type_init ();
-#endif
-    d_ptr->prefix = CONF_PROXY;
-    d_ptr->http_prefix = HTTP_PROXY;
-}
-
-ProxyConf::~ProxyConf()
-{
-    delete d_ptr;
-}
-
-void ProxyConf::readProxyData()
-{
-    d_ptr->readProxyData();
-}
-
-QList<QNetworkProxy> ProxyConf::flush(const QNetworkProxyQuery &query)
-{
-    return d_ptr->flush(query);
-}
-
-
-static int refcount = 0;
-static QReadWriteLock lock;
-
-void ProxyConf::update()
-{
-    QWriteLocker locker(&lock);
-    NetworkProxyFactory *factory = new NetworkProxyFactory();
-    QNetworkProxyFactory::setApplicationProxyFactory((QNetworkProxyFactory*)factory);
-    refcount++;
-}
-
-
-void ProxyConf::clear(void)
-{
-    QWriteLocker locker(&lock);
-    refcount--;
-    if (refcount == 0)
-        QNetworkProxyFactory::setApplicationProxyFactory(NULL);
-
-    if (refcount<0)
-        refcount = 0;
-}
-
-
-} // namespace Maemo
diff --git a/src/plugins/bearer/icd/proxyconf.h b/src/plugins/bearer/icd/proxyconf.h
deleted file mode 100644 (file)
index eb1f3fd..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef PROXYCONF_H
-#define PROXYCONF_H
-
-#include <QString>
-#include <QNetworkProxy>
-
-namespace Maemo {
-
-class ProxyConfPrivate;
-class ProxyConf {
-private:
-    ProxyConfPrivate *d_ptr;
-
-public:
-    ProxyConf();
-    virtual ~ProxyConf();
-
-    QList<QNetworkProxy> flush(const QNetworkProxyQuery &query = QNetworkProxyQuery());  // read the proxies from db
-    void readProxyData();
-
-    /* Note that for each update() call there should be corresponding
-     * clear() call because the ProxyConf class implements a reference
-     * counting mechanism. The factory is removed only when there is
-     * no one using the factory any more.
-     */
-    static void update(void);          // this builds QNetworkProxy factory
-    static void clear(void);           // this removes QNetworkProxy factory
-};
-
-} // namespace Maemo
-
-#endif
diff --git a/src/plugins/bearer/icd/qicdengine.cpp b/src/plugins/bearer/icd/qicdengine.cpp
deleted file mode 100644 (file)
index 230518a..0000000
+++ /dev/null
@@ -1,1128 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qicdengine.h"
-#include "qnetworksession_impl.h"
-
-#include <wlancond.h>
-#include <wlan-utils.h>
-#include <iapconf.h>
-#include <iapmonitor.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-IcdNetworkConfigurationPrivate::IcdNetworkConfigurationPrivate()
-:   service_attrs(0), network_attrs(0)
-{
-}
-
-IcdNetworkConfigurationPrivate::~IcdNetworkConfigurationPrivate()
-{
-}
-
-QString IcdNetworkConfigurationPrivate::bearerTypeName() const
-{
-    QMutexLocker locker(&mutex);
-
-    return iap_type;
-}
-
-/******************************************************************************/
-/** IapAddTimer specific                                                      */
-/******************************************************************************/
-
-/* The IapAddTimer is a helper class that makes sure we update
- * the configuration only after all db additions to certain
- * iap are finished (after a certain timeout)
- */
-class _IapAddTimer : public QObject
-{
-    Q_OBJECT
-
-public:
-    _IapAddTimer() {}
-    ~_IapAddTimer()
-    {
-       if (timer.isActive()) {
-           QObject::disconnect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
-           timer.stop();
-       }
-    }
-
-    void add(QString& iap_id, QIcdEngine *d);
-
-    QString iap_id;
-    QTimer timer;
-    QIcdEngine *d;
-
-public Q_SLOTS:
-    void timeout();
-};
-
-
-void _IapAddTimer::add(QString& id, QIcdEngine *d_ptr)
-{
-    iap_id = id;
-    d = d_ptr;
-
-    if (timer.isActive()) {
-       QObject::disconnect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
-       timer.stop();
-    }
-    timer.setSingleShot(true);
-    QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));
-    timer.start(1500);
-}
-
-
-void _IapAddTimer::timeout()
-{
-    d->addConfiguration(iap_id);
-}
-
-
-class IapAddTimer {
-    QHash<QString, _IapAddTimer* > timers;
-
-public:
-    IapAddTimer() {}
-    ~IapAddTimer() {}
-
-    void add(QString& iap_id, QIcdEngine *d);
-    void del(QString& iap_id);
-    void removeAll();
-};
-
-
-void IapAddTimer::removeAll()
-{
-    QHashIterator<QString, _IapAddTimer* > i(timers);
-    while (i.hasNext()) {
-       i.next();
-       _IapAddTimer *t = i.value();
-       delete t;
-    }
-    timers.clear();
-}
-
-
-void IapAddTimer::add(QString& iap_id, QIcdEngine *d)
-{
-    if (timers.contains(iap_id)) {
-       _IapAddTimer *iap = timers.value(iap_id);
-       iap->add(iap_id, d);
-    } else {
-       _IapAddTimer *iap = new _IapAddTimer;
-       iap->add(iap_id, d);
-       timers.insert(iap_id, iap);
-    }
-}
-
-void IapAddTimer::del(QString& iap_id)
-{
-    if (timers.contains(iap_id)) {
-       _IapAddTimer *iap = timers.take(iap_id);
-       delete iap;
-    }
-}
-
-/******************************************************************************/
-/** IAPMonitor specific                                                       */
-/******************************************************************************/
-
-class IapMonitor : public Maemo::IAPMonitor
-{
-public:
-    IapMonitor() : first_call(true) { }
-
-    void setup(QIcdEngine *d);
-    void cleanup();
-
-protected:
-    void iapAdded(const QString &iapId);
-    void iapRemoved(const QString &iapId);
-
-private:
-    bool first_call;
-
-    QIcdEngine *d;
-    IapAddTimer timers;
-};
-
-void IapMonitor::setup(QIcdEngine *d_ptr)
-{
-    if (first_call) {
-       d = d_ptr;
-       first_call = false;
-    }
-}
-
-
-void IapMonitor::cleanup()
-{
-    if (!first_call) {
-       timers.removeAll();
-       first_call = true;
-    }
-}
-
-
-void IapMonitor::iapAdded(const QString &iap_id)
-{
-    /* We cannot know when the IAP is fully added to db, so a timer is
-     * installed instead. When the timer expires we hope that IAP is added ok.
-     */
-    QString id = iap_id;
-    timers.add(id, d);
-}
-
-
-void IapMonitor::iapRemoved(const QString &iap_id)
-{
-    QString id = iap_id;
-    d->deleteConfiguration(id);
-}
-
-
-/******************************************************************************/
-/** QIcdEngine implementation                                                 */
-/******************************************************************************/
-
-QIcdEngine::QIcdEngine(QObject *parent)
-:   QBearerEngine(parent), iapMonitor(0), m_dbusInterface(0), m_icdServiceWatcher(0),
-    firstUpdate(true), m_scanGoingOn(false)
-{
-}
-
-QIcdEngine::~QIcdEngine()
-{
-    cleanup();
-    delete iapMonitor;
-}
-
-QNetworkConfigurationManager::Capabilities QIcdEngine::capabilities() const
-{
-    return QNetworkConfigurationManager::CanStartAndStopInterfaces |
-           QNetworkConfigurationManager::DataStatistics |
-           QNetworkConfigurationManager::ForcedRoaming |
-           QNetworkConfigurationManager::NetworkSessionRequired;
-}
-
-bool QIcdEngine::ensureDBusConnection()
-{
-    if (m_dbusInterface)
-        return true;
-
-    // Setup DBus Interface for ICD
-    m_dbusInterface = new QDBusInterface(ICD_DBUS_API_INTERFACE,
-                                         ICD_DBUS_API_PATH,
-                                         ICD_DBUS_API_INTERFACE,
-                                         QDBusConnection::systemBus(),
-                                         this);
-
-    if (!m_dbusInterface->isValid()) {
-        delete m_dbusInterface;
-        m_dbusInterface = 0;
-
-        if (!m_icdServiceWatcher) {
-            m_icdServiceWatcher = new QDBusServiceWatcher(ICD_DBUS_API_INTERFACE,
-                                                          QDBusConnection::systemBus(),
-                                                          QDBusServiceWatcher::WatchForOwnerChange,
-                                                          this);
-
-            connect(m_icdServiceWatcher, SIGNAL(serviceOwnerChanged(QString,QString,QString)),
-                    this, SLOT(icdServiceOwnerChanged(QString,QString,QString)));
-        }
-
-        return false;
-    }
-
-    connect(&m_scanTimer, SIGNAL(timeout()), this, SLOT(finishAsyncConfigurationUpdate()));
-    m_scanTimer.setSingleShot(true);
-
-    /* Turn on IAP state monitoring */
-    startListeningStateSignalsForAllConnections();
-
-    /* Turn on IAP add/remove monitoring */
-    iapMonitor = new IapMonitor;
-    iapMonitor->setup(this);
-
-    /* We create a default configuration which is a pseudo config */
-    QNetworkConfigurationPrivate *cpPriv = new IcdNetworkConfigurationPrivate;
-    cpPriv->name = "UserChoice";
-    cpPriv->state = QNetworkConfiguration::Discovered;
-    cpPriv->isValid = true;
-    cpPriv->id = OSSO_IAP_ANY;
-    cpPriv->type = QNetworkConfiguration::UserChoice;
-    cpPriv->purpose = QNetworkConfiguration::UnknownPurpose;
-    cpPriv->roamingSupported = false;
-
-    QNetworkConfigurationPrivatePointer ptr(cpPriv);
-    userChoiceConfigurations.insert(cpPriv->id, ptr);
-
-    doRequestUpdate();
-
-    getIcdInitialState();
-
-    return true;
-}
-
-void QIcdEngine::initialize()
-{
-    QMutexLocker locker(&mutex);
-
-    if (!ensureDBusConnection()) {
-        locker.unlock();
-        emit updateCompleted();
-        locker.relock();
-    }
-}
-
-static inline QString network_attrs_to_security(uint network_attrs)
-{
-    uint cap = 0;
-    nwattr2cap(network_attrs, &cap); /* from libicd-network-wlan-dev.h */
-    if (cap & WLANCOND_OPEN)
-        return "NONE";
-    else if (cap & WLANCOND_WEP)
-        return "WEP";
-    else if (cap & WLANCOND_WPA_PSK)
-        return "WPA_PSK";
-    else if (cap & WLANCOND_WPA_EAP)
-        return "WPA_EAP";
-    return "";
-}
-
-
-struct SSIDInfo {
-    QString iap_id;
-    QString wlan_security;
-};
-
-
-void QIcdEngine::deleteConfiguration(const QString &iap_id)
-{
-    QMutexLocker locker(&mutex);
-
-    /* Called when IAPs are deleted in db, in this case we do not scan
-     * or read all the IAPs from db because it might take too much power
-     * (multiple applications would need to scan and read all IAPs from db)
-     */
-    QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.take(iap_id);
-    if (ptr) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug() << "IAP" << iap_id << "was removed from storage.";
-#endif
-
-        locker.unlock();
-        emit configurationRemoved(ptr);
-    } else {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("IAP: %s, already missing from the known list", iap_id.toAscii().data());
-#endif
-    }
-}
-
-
-static quint32 getNetworkAttrs(bool is_iap_id,
-                               const QString &iap_id,
-                               const QString &iap_type,
-                               QString security_method)
-{
-    guint network_attr = 0;
-    dbus_uint32_t cap = 0;
-
-    if (iap_type == "WLAN_INFRA")
-    cap |= WLANCOND_INFRA;
-    else if (iap_type == "WLAN_ADHOC")
-    cap |= WLANCOND_ADHOC;
-
-    if (security_method.isEmpty() && (cap & (WLANCOND_INFRA | WLANCOND_ADHOC))) {
-    Maemo::IAPConf saved_ap(iap_id);
-    security_method = saved_ap.value("wlan_security").toString();
-    }
-
-    if (!security_method.isEmpty()) {
-    if (security_method == "WEP")
-        cap |= WLANCOND_WEP;
-    else if (security_method == "WPA_PSK")
-        cap |= WLANCOND_WPA_PSK;
-    else if (security_method == "WPA_EAP")
-        cap |= WLANCOND_WPA_EAP;
-    else if (security_method == "NONE")
-        cap |= WLANCOND_OPEN;
-
-    if (cap & (WLANCOND_WPA_PSK | WLANCOND_WPA_EAP)) {
-        Maemo::IAPConf saved_iap(iap_id);
-        bool wpa2_only = saved_iap.value("EAP_wpa2_only_mode").toBool();
-        if (wpa2_only) {
-        cap |= WLANCOND_WPA2;
-        }
-    }
-    }
-
-    cap2nwattr(cap, &network_attr);
-    if (is_iap_id)
-    network_attr |= ICD_NW_ATTR_IAPNAME;
-
-    return quint32(network_attr);
-}
-
-
-void QIcdEngine::addConfiguration(QString& iap_id)
-{
-    // Note: When new IAP is created, this function gets called multiple times
-    //       in a row.
-    //       For example: Empty type & name for WLAN was stored into newly
-    //                    created IAP data in gconf when this function gets
-    //                    called for the first time.
-    //                    WLAN type & name are updated into IAP data in gconf
-    //                    as soon as WLAN connection is up and running.
-    //                    => And this function gets called again.
-
-    QMutexLocker locker(&mutex);
-
-    if (!accessPointConfigurations.contains(iap_id)) {
-       Maemo::IAPConf saved_iap(iap_id);
-        QString iap_type = saved_iap.value("type").toString();
-        QString iap_name = saved_iap.value("name").toString();
-        QByteArray ssid = saved_iap.value("wlan_ssid").toByteArray();
-        if (!iap_type.isEmpty() && !iap_name.isEmpty()) {
-            // Check if new IAP is actually Undefined WLAN configuration
-            // Note: SSID is used as an iap id for Undefined WLAN configurations
-            //       => configuration must be searched using SSID
-            if (!ssid.isEmpty() && accessPointConfigurations.contains(ssid)) {
-                QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.take(ssid);
-                if (ptr) {
-                    ptr->mutex.lock();
-                    ptr->id = iap_id;
-                    toIcdConfig(ptr)->iap_type = iap_type;
-                    ptr->bearerType = bearerTypeFromIapType(iap_type);
-                    toIcdConfig(ptr)->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString());
-                    toIcdConfig(ptr)->network_id = ssid;
-                    toIcdConfig(ptr)->service_id = saved_iap.value("service_id").toString();
-                    toIcdConfig(ptr)->service_type = saved_iap.value("service_type").toString();
-                    if (m_onlineIapId == iap_id) {
-                        ptr->state = QNetworkConfiguration::Active;
-                    } else {
-                        ptr->state = QNetworkConfiguration::Defined;
-                    }
-                    ptr->mutex.unlock();
-                    accessPointConfigurations.insert(iap_id, ptr);
-
-                    locker.unlock();
-                    emit configurationChanged(ptr);
-                    locker.relock();
-                }
-            } else {
-                IcdNetworkConfigurationPrivate *cpPriv = new IcdNetworkConfigurationPrivate;
-                cpPriv->name = saved_iap.value("name").toString();
-                if (cpPriv->name.isEmpty())
-                    cpPriv->name = iap_id;
-                cpPriv->isValid = true;
-                cpPriv->id = iap_id;
-                cpPriv->iap_type = iap_type;
-                cpPriv->bearerType = bearerTypeFromIapType(iap_type);
-                cpPriv->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString());
-                cpPriv->service_id = saved_iap.value("service_id").toString();
-                cpPriv->service_type = saved_iap.value("service_type").toString();
-                if (iap_type.startsWith(QLatin1String("WLAN"))) {
-                    QByteArray ssid = saved_iap.value("wlan_ssid").toByteArray();
-                    if (ssid.isEmpty()) {
-                        qWarning() << "Cannot get ssid for" << iap_id;
-                    }
-                    cpPriv->network_id = ssid;
-                }
-                cpPriv->type = QNetworkConfiguration::InternetAccessPoint;
-                if (m_onlineIapId == iap_id) {
-                    cpPriv->state = QNetworkConfiguration::Active;
-                } else {
-                    cpPriv->state = QNetworkConfiguration::Defined;
-                }
-
-                QNetworkConfigurationPrivatePointer ptr(cpPriv);
-                accessPointConfigurations.insert(iap_id, ptr);
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-                qDebug("IAP: %s, name: %s, added to known list", iap_id.toAscii().data(), cpPriv->name.toAscii().data());
-#endif
-                locker.unlock();
-                emit configurationAdded(ptr);
-                locker.relock();
-            }
-        } else {
-            qWarning("IAP %s does not have \"type\" or \"name\" fields defined, skipping this IAP.", iap_id.toAscii().data());
-        }
-    } else {
-#ifdef BEARER_MANAGEMENT_DEBUG
-       qDebug() << "IAP" << iap_id << "already in db.";
-#endif
-
-       /* Check if the data in db changed and update configuration accordingly
-        */
-    QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(iap_id);
-       if (ptr) {
-           Maemo::IAPConf changed_iap(iap_id);
-           QString iap_type = changed_iap.value("type").toString();
-           bool update_needed = false; /* if IAP type or ssid changed, we need to change the state */
-
-        QMutexLocker configLocker(&ptr->mutex);
-
-           toIcdConfig(ptr)->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString());
-           toIcdConfig(ptr)->service_id = changed_iap.value("service_id").toString();
-           toIcdConfig(ptr)->service_type = changed_iap.value("service_type").toString();
-
-           if (!iap_type.isEmpty()) {
-            ptr->name = changed_iap.value("name").toString();
-            if (ptr->name.isEmpty())
-                ptr->name = iap_id;
-            ptr->isValid = true;
-            if (toIcdConfig(ptr)->iap_type != iap_type) {
-                toIcdConfig(ptr)->iap_type = iap_type;
-                ptr->bearerType = bearerTypeFromIapType(iap_type);
-                update_needed = true;
-            }
-            if (iap_type.startsWith(QLatin1String("WLAN"))) {
-                QByteArray ssid = changed_iap.value("wlan_ssid").toByteArray();
-                if (ssid.isEmpty()) {
-                    qWarning() << "Cannot get ssid for" << iap_id;
-                }
-                if (toIcdConfig(ptr)->network_id != ssid) {
-                    toIcdConfig(ptr)->network_id = ssid;
-                    update_needed = true;
-                }
-            }
-           }
-
-           if (update_needed) {
-            ptr->type = QNetworkConfiguration::InternetAccessPoint;
-            if (m_onlineIapId == iap_id) {
-                if (ptr->state < QNetworkConfiguration::Active) {
-                    ptr->state = QNetworkConfiguration::Active;
-
-                    configLocker.unlock();
-                    locker.unlock();
-                    emit configurationChanged(ptr);
-                    locker.relock();
-                }
-            } else if (ptr->state < QNetworkConfiguration::Defined) {
-                ptr->state = QNetworkConfiguration::Defined;
-
-                configLocker.unlock();
-                locker.unlock();
-                emit configurationChanged(ptr);
-                locker.relock();
-            }
-           }
-       } else {
-           qWarning("Cannot find IAP %s from current configuration although it should be there.", iap_id.toAscii().data());
-       }
-    }
-}
-
-void QIcdEngine::doRequestUpdate(QList<Maemo::IcdScanResult> scanned)
-{
-    /* Contains all known iap_ids from storage */
-    QList<QString> knownConfigs = accessPointConfigurations.keys();
-
-    /* Contains all known WLAN network ids (like ssid) from storage */
-    QMultiHash<QByteArray, SSIDInfo* > notDiscoveredWLANConfigs;
-
-    QList<QString> all_iaps;
-    Maemo::IAPConf::getAll(all_iaps);
-
-    foreach (const QString &iap_id, all_iaps) {
-        QByteArray ssid;
-
-        Maemo::IAPConf saved_ap(iap_id);
-        bool is_temporary = saved_ap.value("temporary").toBool();
-        if (is_temporary) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug() << "IAP" << iap_id << "is temporary, skipping it.";
-#endif
-            continue;
-        }
-
-        QString iap_type = saved_ap.value("type").toString();
-        if (iap_type.startsWith(QLatin1String("WLAN"))) {
-            ssid = saved_ap.value("wlan_ssid").toByteArray();
-            if (ssid.isEmpty())
-                continue;
-
-            QString security_method = saved_ap.value("wlan_security").toString();
-            SSIDInfo *info = new SSIDInfo;
-            info->iap_id = iap_id;
-            info->wlan_security = security_method;
-                notDiscoveredWLANConfigs.insert(ssid, info);
-        } else if (iap_type.isEmpty()) {
-            continue;
-        } else {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug() << "IAP" << iap_id << "network type is" << iap_type;
-#endif
-            ssid.clear();
-        }
-
-        if (!accessPointConfigurations.contains(iap_id)) {
-            IcdNetworkConfigurationPrivate *cpPriv = new IcdNetworkConfigurationPrivate;
-
-            cpPriv->name = saved_ap.value("name").toString();
-            if (cpPriv->name.isEmpty()) {
-                if (!ssid.isEmpty() && ssid.size() > 0)
-                    cpPriv->name = ssid.data();
-                else
-                    cpPriv->name = iap_id;
-            }
-            cpPriv->isValid = true;
-            cpPriv->id = iap_id;
-            cpPriv->network_id = ssid;
-            cpPriv->network_attrs = getNetworkAttrs(true, iap_id, iap_type, QString());
-            cpPriv->iap_type = iap_type;
-            cpPriv->bearerType = bearerTypeFromIapType(iap_type);
-            cpPriv->service_id = saved_ap.value("service_id").toString();
-            cpPriv->service_type = saved_ap.value("service_type").toString();
-            cpPriv->type = QNetworkConfiguration::InternetAccessPoint;
-            cpPriv->state = QNetworkConfiguration::Defined;
-
-            QNetworkConfigurationPrivatePointer ptr(cpPriv);
-            accessPointConfigurations.insert(iap_id, ptr);
-
-            mutex.unlock();
-            emit configurationAdded(ptr);
-            mutex.lock();
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("IAP: %s, name: %s, ssid: %s, added to known list",
-                   iap_id.toAscii().data(), ptr->name.toAscii().data(),
-                   !ssid.isEmpty() ? ssid.data() : "-");
-#endif
-        } else {
-            knownConfigs.removeOne(iap_id);
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("IAP: %s, ssid: %s, already exists in the known list",
-                   iap_id.toAscii().data(), !ssid.isEmpty() ? ssid.data() : "-");
-#endif
-        }
-    }
-
-    /* This is skipped in the first update as scanned size is zero */
-    if (!scanned.isEmpty()) {
-        for (int i=0; i<scanned.size(); ++i) {
-            const Maemo::IcdScanResult ap = scanned.at(i);
-
-            if (ap.scan.network_attrs & ICD_NW_ATTR_IAPNAME) {
-                /* The network_id is IAP id, so the IAP is a known one */
-                QString iapid = ap.scan.network_id.data();
-                QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(iapid);
-                if (ptr) {
-                    bool changed = false;
-
-                    ptr->mutex.lock();
-
-                    if (!ptr->isValid) {
-                        ptr->isValid = true;
-                        changed = true;
-                    }
-
-                    /* If this config is the current active one, we do not set it
-                     * to discovered.
-                     */
-                    if ((ptr->state != QNetworkConfiguration::Discovered) &&
-                        (ptr->state != QNetworkConfiguration::Active)) {
-                        ptr->state = QNetworkConfiguration::Discovered;
-                        changed = true;
-                    }
-
-                    toIcdConfig(ptr)->network_attrs = ap.scan.network_attrs;
-                    toIcdConfig(ptr)->service_id = ap.scan.service_id;
-                    toIcdConfig(ptr)->service_type = ap.scan.service_type;
-                    toIcdConfig(ptr)->service_attrs = ap.scan.service_attrs;
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-                    qDebug("IAP: %s, ssid: %s, discovered",
-                           iapid.toAscii().data(), toIcdConfig(ptr)->network_id.data());
-#endif
-
-                    ptr->mutex.unlock();
-
-                    if (changed) {
-                        mutex.unlock();
-                        emit configurationChanged(ptr);
-                        mutex.lock();
-                    }
-
-                    if (!ap.scan.network_type.startsWith(QLatin1String("WLAN")))
-                        continue; // not a wlan AP
-
-                    /* Remove scanned AP from discovered WLAN configurations so that we can
-                     * emit configurationRemoved signal later
-                     */
-                    ptr->mutex.lock();
-                    QList<SSIDInfo* > known_iaps = notDiscoveredWLANConfigs.values(toIcdConfig(ptr)->network_id);
-rescan_list:
-                    if (!known_iaps.isEmpty()) {
-                        for (int k=0; k<known_iaps.size(); ++k) {
-                            SSIDInfo *iap = known_iaps.at(k);
-
-                            if (iap->wlan_security ==
-                                network_attrs_to_security(ap.scan.network_attrs)) {
-                                /* Remove IAP from the list */
-                                notDiscoveredWLANConfigs.remove(toIcdConfig(ptr)->network_id, iap);
-#ifdef BEARER_MANAGEMENT_DEBUG
-                                qDebug() << "Removed IAP" << iap->iap_id << "from unknown config";
-#endif
-                                known_iaps.removeAt(k);
-                                delete iap;
-                                goto rescan_list;
-                            }
-                        }
-                    }
-                    ptr->mutex.unlock();
-                }
-            } else {
-                /* Non saved access point data */
-                QByteArray scanned_ssid = ap.scan.network_id;
-                if (!accessPointConfigurations.contains(scanned_ssid)) {
-                    IcdNetworkConfigurationPrivate *cpPriv = new IcdNetworkConfigurationPrivate;
-                    QString hrs = scanned_ssid.data();
-
-                    cpPriv->name = ap.network_name.isEmpty() ? hrs : ap.network_name;
-                    cpPriv->isValid = true;
-                    cpPriv->id = scanned_ssid.data();  // Note: id is now ssid, it should be set to IAP id if the IAP is saved
-                    cpPriv->network_id = scanned_ssid;
-                    cpPriv->iap_type = ap.scan.network_type;
-                    cpPriv->bearerType = bearerTypeFromIapType(cpPriv->iap_type);
-                    cpPriv->network_attrs = ap.scan.network_attrs;
-                    cpPriv->service_id = ap.scan.service_id;
-                    cpPriv->service_type = ap.scan.service_type;
-                    cpPriv->service_attrs = ap.scan.service_attrs;
-
-                    cpPriv->type = QNetworkConfiguration::InternetAccessPoint;
-                    cpPriv->state = QNetworkConfiguration::Undefined;
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-                    qDebug() << "IAP with network id" << cpPriv->id << "was found in the scan.";
-#endif
-
-                    QNetworkConfigurationPrivatePointer ptr(cpPriv);
-                    accessPointConfigurations.insert(ptr->id, ptr);
-
-                    mutex.unlock();
-                    emit configurationAdded(ptr);
-                    mutex.lock();
-                } else {
-                    knownConfigs.removeOne(scanned_ssid);
-                }
-            }
-        }
-    }
-
-    if (!firstUpdate) {
-        // Update Defined status to all defined WLAN IAPs which
-        // could not be found when access points were scanned
-        QHashIterator<QByteArray, SSIDInfo* > i(notDiscoveredWLANConfigs);
-        while (i.hasNext()) {
-            i.next();
-            SSIDInfo *iap = i.value();
-            QString iap_id = iap->iap_id;
-            //qDebug() << i.key() << ": " << iap_id;
-
-            QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(iap_id);
-            if (ptr) {
-                QMutexLocker configLocker(&ptr->mutex);
-
-                // WLAN AccessPoint configuration could not be Discovered
-                // => Make sure that configuration state is Defined
-                if (ptr->state > QNetworkConfiguration::Defined) {
-                    ptr->state = QNetworkConfiguration::Defined;
-
-                    configLocker.unlock();
-                    mutex.unlock();
-                    emit configurationChanged(ptr);
-                    mutex.lock();
-                }
-            }
-        }
-
-        /* Remove non existing iaps since last update */
-        foreach (const QString &oldIface, knownConfigs) {
-            QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.take(oldIface);
-            if (ptr) {
-                mutex.unlock();
-                emit configurationRemoved(ptr);
-                mutex.lock();
-                //if we would have SNAP support we would have to remove the references
-                //from existing ServiceNetworks to the removed access point configuration
-            }
-        }
-    }
-
-    QMutableHashIterator<QByteArray, SSIDInfo* > i(notDiscoveredWLANConfigs);
-    while (i.hasNext()) {
-        i.next();
-        SSIDInfo *iap = i.value();
-        delete iap;
-        i.remove();
-    }
-
-    if (!firstUpdate) {
-        mutex.unlock();
-        emit updateCompleted();
-        mutex.lock();
-    }
-
-    if (firstUpdate)
-        firstUpdate = false;
-}
-
-QNetworkConfigurationPrivatePointer QIcdEngine::defaultConfiguration()
-{
-    QMutexLocker locker(&mutex);
-
-    if (!ensureDBusConnection())
-        return QNetworkConfigurationPrivatePointer();
-
-    // Here we just return [ANY] request to icd and let the icd decide which IAP to connect.
-    return userChoiceConfigurations.value(OSSO_IAP_ANY);
-}
-
-void QIcdEngine::startListeningStateSignalsForAllConnections()
-{
-    // Start listening ICD_DBUS_API_STATE_SIG signals
-    m_dbusInterface->connection().connect(ICD_DBUS_API_INTERFACE,
-                                          ICD_DBUS_API_PATH,
-                                          ICD_DBUS_API_INTERFACE,
-                                          ICD_DBUS_API_STATE_SIG,
-                                          this, SLOT(connectionStateSignalsSlot(QDBusMessage)));
-}
-
-void QIcdEngine::getIcdInitialState()
-{
-    /* Instead of requesting ICD status asynchronously, we ask it synchronously.
-     * It ensures that we always get right icd status BEFORE initialize() ends.
-     * If not, initialize()  might end before we got icd status and
-     * QNetworkConfigurationManager::updateConfigurations()
-     * call from user might also end before receiving icd status.
-     * In such case, we come up to a bug:
-     * QNetworkConfigurationManagerPrivate::isOnline() will be false even
-     * if we are connected.
-     */
-    Maemo::Icd icd;
-    QList<Maemo::IcdStateResult> state_results;
-    QNetworkConfigurationPrivatePointer ptr;
-
-    if (icd.state(state_results) && !state_results.isEmpty()) {
-
-        if (!(state_results.first().params.network_attrs == 0 &&
-              state_results.first().params.network_id.isEmpty())) {
-
-            switch (state_results.first().state) {
-            case ICD_STATE_CONNECTED:
-                m_onlineIapId = state_results.first().params.network_id;
-
-                ptr = accessPointConfigurations.value(m_onlineIapId);
-                if (ptr) {
-                    QMutexLocker configLocker(&ptr->mutex);
-                    ptr->state = QNetworkConfiguration::Active;
-                    configLocker.unlock();
-
-                    mutex.unlock();
-                    emit configurationChanged(ptr);
-                    mutex.lock();
-                }
-                break;
-            default:
-                break;
-            }
-        }
-    }
-}
-
-void QIcdEngine::connectionStateSignalsSlot(QDBusMessage msg)
-{
-    QMutexLocker locker(&mutex);
-
-    QList<QVariant> arguments = msg.arguments();
-    if (arguments[1].toUInt() != 0 || arguments.count() < 8) {
-        return;
-    }
-
-    QString iapid = arguments[5].toByteArray().data();
-    uint icd_connection_state = arguments[7].toUInt();
-
-    switch (icd_connection_state) {
-    case ICD_STATE_CONNECTED:
-        {
-        QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(iapid);
-        if (ptr) {
-            QMutexLocker configLocker(&ptr->mutex);
-
-            ptr->type = QNetworkConfiguration::InternetAccessPoint;
-            if (ptr->state != QNetworkConfiguration::Active) {
-                ptr->state = QNetworkConfiguration::Active;
-
-                configLocker.unlock();
-                locker.unlock();
-                emit configurationChanged(ptr);
-                locker.relock();
-
-                m_onlineIapId = iapid;
-            }
-        } else {
-            // This gets called when new WLAN IAP is created using Connection dialog
-            // At this point Undefined WLAN configuration has SSID as iap id
-            // => Because of that configuration can not be found from
-            //    accessPointConfigurations using correct iap id
-            m_onlineIapId = iapid;
-        }
-        break;
-        }
-    case ICD_STATE_DISCONNECTED:
-        {
-        QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(iapid);
-        if (ptr) {
-            QMutexLocker configLocker(&ptr->mutex);
-
-            ptr->type = QNetworkConfiguration::InternetAccessPoint;
-            if (ptr->state == QNetworkConfiguration::Active) {
-                ptr->state = QNetworkConfiguration::Discovered;
-
-                configLocker.unlock();
-                locker.unlock();
-                emit iapStateChanged(iapid, icd_connection_state);
-                emit configurationChanged(ptr);
-                locker.relock();
-
-                // Note: If ICD switches used IAP from one to another:
-                //       1) new IAP is reported to be online first
-                //       2) old IAP is reported to be offline then
-                // => Device can be reported to be offline only
-                //    if last known online IAP is reported to be disconnected
-                if (iapid == m_onlineIapId) {
-                    // It's known that there is only one global ICD connection
-                    // => Because ICD state was reported to be DISCONNECTED, Device is offline
-                    m_onlineIapId.clear();
-                }
-            }
-        } else {
-            // Disconnected IAP was not found from accessPointConfigurations
-            // => Reason: Online IAP was removed which resulted ICD to disconnect
-            if (iapid == m_onlineIapId) {
-                // It's known that there is only one global ICD connection
-                // => Because ICD state was reported to be DISCONNECTED, Device is offline
-                m_onlineIapId.clear();
-            }
-        }
-        break;
-        }
-    default:
-        break;
-    }
-    
-    locker.unlock();
-    emit iapStateChanged(iapid, icd_connection_state);
-    locker.relock();
-}
-
-void QIcdEngine::icdServiceOwnerChanged(const QString &serviceName, const QString &oldOwner,
-                                        const QString &newOwner)
-{
-    Q_UNUSED(serviceName);
-    Q_UNUSED(oldOwner);
-
-    QMutexLocker locker(&mutex);
-
-    if (newOwner.isEmpty()) {
-        // Disconnected from ICD, remove all configurations
-        cleanup();
-        delete iapMonitor;
-        iapMonitor = 0;
-        delete m_dbusInterface;
-        m_dbusInterface = 0;
-
-        QMutableHashIterator<QString, QNetworkConfigurationPrivatePointer> i(accessPointConfigurations);
-        while (i.hasNext()) {
-            i.next();
-
-            QNetworkConfigurationPrivatePointer ptr = i.value();
-            i.remove();
-
-            locker.unlock();
-            emit configurationRemoved(ptr);
-            locker.relock();
-        }
-
-        userChoiceConfigurations.clear();
-    } else {
-        // Connected to ICD ensure connection.
-        ensureDBusConnection();
-    }
-}
-
-void QIcdEngine::requestUpdate()
-{
-    QMutexLocker locker(&mutex);
-
-    if (!ensureDBusConnection()) {
-        locker.unlock();
-        emit updateCompleted();
-        locker.relock();
-        return;
-    }
-
-    if (m_scanGoingOn)
-        return;
-
-    m_scanGoingOn = true;
-
-    m_dbusInterface->connection().connect(ICD_DBUS_API_INTERFACE,
-                                          ICD_DBUS_API_PATH,
-                                          ICD_DBUS_API_INTERFACE,
-                                          ICD_DBUS_API_SCAN_SIG,
-                                          this, SLOT(asyncUpdateConfigurationsSlot(QDBusMessage)));
-
-    QDBusMessage msg = m_dbusInterface->call(ICD_DBUS_API_SCAN_REQ,
-                                             (uint)ICD_SCAN_REQUEST_ACTIVE);
-    m_typesToBeScanned = msg.arguments()[0].value<QStringList>();
-    m_scanTimer.start(ICD_SHORT_SCAN_TIMEOUT);
-}
-
-void QIcdEngine::cancelAsyncConfigurationUpdate()
-{
-    if (!ensureDBusConnection())
-        return;
-
-    if (!m_scanGoingOn)
-        return;
-
-    m_scanGoingOn = false;
-
-    if (m_scanTimer.isActive())
-        m_scanTimer.stop();
-
-    m_dbusInterface->connection().disconnect(ICD_DBUS_API_INTERFACE,
-                                             ICD_DBUS_API_PATH,
-                                             ICD_DBUS_API_INTERFACE,
-                                             ICD_DBUS_API_SCAN_SIG,
-                                             this, SLOT(asyncUpdateConfigurationsSlot(QDBusMessage)));
-
-    // Stop scanning rounds by calling ICD_DBUS_API_SCAN_CANCEL
-    // <=> If ICD_DBUS_API_SCAN_CANCEL is not called, new scanning round will
-    //     be started after the module scan timeout.
-    m_dbusInterface->call(ICD_DBUS_API_SCAN_CANCEL);
-}
-
-void QIcdEngine::finishAsyncConfigurationUpdate()
-{
-    QMutexLocker locker(&mutex);
-
-    cancelAsyncConfigurationUpdate();
-    doRequestUpdate(m_scanResult);
-    m_scanResult.clear();
-}
-
-void QIcdEngine::asyncUpdateConfigurationsSlot(QDBusMessage msg)
-{
-    QMutexLocker locker(&mutex);
-
-    QList<QVariant> arguments = msg.arguments();
-    uint icd_scan_status = arguments.takeFirst().toUInt();
-    if (icd_scan_status == ICD_SCAN_COMPLETE) {
-        m_typesToBeScanned.removeOne(arguments[6].toString());
-        if (!m_typesToBeScanned.count()) {
-            locker.unlock();
-            finishAsyncConfigurationUpdate();
-            locker.relock();
-        }
-    } else {
-        Maemo::IcdScanResult scanResult;
-        scanResult.status = icd_scan_status;
-        scanResult.timestamp = arguments.takeFirst().toUInt();
-        scanResult.scan.service_type = arguments.takeFirst().toString();
-        scanResult.service_name = arguments.takeFirst().toString();
-        scanResult.scan.service_attrs = arguments.takeFirst().toUInt();
-        scanResult.scan.service_id = arguments.takeFirst().toString();
-        scanResult.service_priority = arguments.takeFirst().toInt();
-        scanResult.scan.network_type = arguments.takeFirst().toString();
-        scanResult.network_name = arguments.takeFirst().toString();
-        scanResult.scan.network_attrs = arguments.takeFirst().toUInt();
-        scanResult.scan.network_id = arguments.takeFirst().toByteArray();
-        scanResult.network_priority = arguments.takeFirst().toInt();
-        scanResult.signal_strength = arguments.takeFirst().toInt();
-        scanResult.station_id = arguments.takeFirst().toString();
-        scanResult.signal_dB = arguments.takeFirst().toInt();
-
-        m_scanResult.append(scanResult);
-    }
-}
-
-void QIcdEngine::cleanup()
-{
-    if (m_scanGoingOn) {
-        m_scanTimer.stop();
-        m_dbusInterface->call(ICD_DBUS_API_SCAN_CANCEL);
-    }
-    if (iapMonitor)
-        iapMonitor->cleanup();
-}
-
-bool QIcdEngine::hasIdentifier(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    return accessPointConfigurations.contains(id) ||
-           snapConfigurations.contains(id) ||
-           userChoiceConfigurations.contains(id);
-}
-
-QNetworkSessionPrivate *QIcdEngine::createSessionBackend()
-{
-    return new QNetworkSessionPrivateImpl(this);
-}
-
-#include "qicdengine.moc"
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
-#include "moc_qicdengine.h"
diff --git a/src/plugins/bearer/icd/qicdengine.h b/src/plugins/bearer/icd/qicdengine.h
deleted file mode 100644 (file)
index c62ca76..0000000
+++ /dev/null
@@ -1,177 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QICDENGINE_H
-#define QICDENGINE_H
-
-#include <QtNetwork/qbearerengine_p.h>
-
-#include <QtCore/qtimer.h>
-
-#include "maemo_icd.h"
-
-QT_BEGIN_NAMESPACE
-
-class QNetworkConfigurationPrivate;
-class IapMonitor;
-class QDBusInterface;
-class QDBusServiceWatcher;
-
-inline QNetworkConfiguration::BearerType bearerTypeFromIapType(const QString &iapType)
-{
-    if (iapType == QLatin1String("WLAN_INFRA") ||
-        iapType == QLatin1String("WLAN_ADHOC")) {
-        return QNetworkConfiguration::BearerWLAN;
-    } else if (iapType == QLatin1String("GPRS")) {
-        return QNetworkConfiguration::BearerHSPA;
-    } else {
-        return QNetworkConfiguration::BearerUnknown;
-    }
-}
-
-class IcdNetworkConfigurationPrivate : public QNetworkConfigurationPrivate
-{
-public:
-    IcdNetworkConfigurationPrivate();
-    ~IcdNetworkConfigurationPrivate();
-
-    virtual QString bearerTypeName() const;
-
-    // In Maemo the id field (defined in QNetworkConfigurationPrivate)
-    // is the IAP id (which typically is UUID)
-    QByteArray network_id;  // typically WLAN ssid or similar
-    QString iap_type;       // is this one WLAN or GPRS
-
-    QString service_type;
-    QString service_id;
-    quint32 service_attrs;
-
-    // Network attributes for this IAP, this is the value returned by icd and
-    // passed to it when connecting.
-    quint32 network_attrs;
-};
-
-inline IcdNetworkConfigurationPrivate *toIcdConfig(QNetworkConfigurationPrivatePointer ptr)
-{
-    return static_cast<IcdNetworkConfigurationPrivate *>(ptr.data());
-}
-
-class QIcdEngine : public QBearerEngine
-{
-    Q_OBJECT
-
-public:
-    QIcdEngine(QObject *parent = 0);
-    ~QIcdEngine();
-
-    bool hasIdentifier(const QString &id);
-
-    Q_INVOKABLE void initialize();
-    Q_INVOKABLE void requestUpdate();
-
-    QNetworkConfigurationManager::Capabilities capabilities() const;
-
-    QNetworkSessionPrivate *createSessionBackend();
-
-    QNetworkConfigurationPrivatePointer defaultConfiguration();
-
-    void deleteConfiguration(const QString &iap_id);
-
-    inline QNetworkConfigurationPrivatePointer configuration(const QString &id)
-    {
-        QMutexLocker locker(&mutex);
-
-        return accessPointConfigurations.value(id);
-    }
-
-    inline void addSessionConfiguration(QNetworkConfigurationPrivatePointer ptr)
-    {
-        QMutexLocker locker(&mutex);
-
-        accessPointConfigurations.insert(ptr->id, ptr);
-
-        locker.unlock();
-        emit configurationAdded(ptr);
-    }
-
-    inline void changedSessionConfiguration(QNetworkConfigurationPrivatePointer ptr)
-    {
-        emit configurationChanged(ptr);
-    }
-
-    void cleanup();
-
-    void addConfiguration(QString &iap_id);
-
-Q_SIGNALS:
-    void iapStateChanged(const QString& iapid, uint icd_connection_state);
-
-private Q_SLOTS:
-    void finishAsyncConfigurationUpdate();
-    void asyncUpdateConfigurationsSlot(QDBusMessage msg);
-    void connectionStateSignalsSlot(QDBusMessage msg);
-    void icdServiceOwnerChanged(const QString &serviceName, const QString &oldOwner,
-                                const QString &newOwner);
-
-private:
-    void startListeningStateSignalsForAllConnections();
-    void doRequestUpdate(QList<Maemo::IcdScanResult> scanned = QList<Maemo::IcdScanResult>());
-    void cancelAsyncConfigurationUpdate();
-    void getIcdInitialState();
-    bool ensureDBusConnection();
-
-private:
-    IapMonitor *iapMonitor;
-    QDBusInterface *m_dbusInterface;
-    QTimer m_scanTimer;
-    QString m_onlineIapId;
-    QStringList m_typesToBeScanned;
-    QList<Maemo::IcdScanResult> m_scanResult;
-
-    QDBusServiceWatcher *m_icdServiceWatcher;
-
-    bool firstUpdate;
-    bool m_scanGoingOn;
-};
-
-QT_END_NAMESPACE
-
-#endif // QICDENGINE_H
diff --git a/src/plugins/bearer/icd/qnetworksession_impl.cpp b/src/plugins/bearer/icd/qnetworksession_impl.cpp
deleted file mode 100644 (file)
index 2f8bb42..0000000
+++ /dev/null
@@ -1,1079 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qnetworksession_impl.h"
-#include "qicdengine.h"
-
-#include <QHash>
-
-#include <maemo_icd.h>
-#include <iapconf.h>
-#include <proxyconf.h>
-
-#include <ifaddrs.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-QDBusArgument &operator<<(QDBusArgument &argument,
-                          const ICd2DetailsDBusStruct &icd2)
-{
-    argument.beginStructure();
-
-    argument << icd2.serviceType;
-    argument << icd2.serviceAttributes;
-    argument << icd2.setviceId;
-    argument << icd2.networkType;
-    argument << icd2.networkAttributes;
-    argument << icd2.networkId;
-
-    argument.endStructure();
-
-    return argument;
-}
-
-const QDBusArgument &operator>>(const QDBusArgument &argument,
-                                ICd2DetailsDBusStruct &icd2)
-{
-    argument.beginStructure();
-
-    argument >> icd2.serviceType;
-    argument >> icd2.serviceAttributes;
-    argument >> icd2.setviceId;
-    argument >> icd2.networkType;
-    argument >> icd2.networkAttributes;
-    argument >> icd2.networkId;
-
-    argument.endStructure();
-
-    return argument;
-}
-
-const QDBusArgument &operator>>(const QDBusArgument &argument,
-                                ICd2DetailsList &detailsList)
-{
-     argument.beginArray();
-     detailsList.clear();
-
-     while (!argument.atEnd()) {
-         ICd2DetailsDBusStruct element;
-         argument >> element;
-         detailsList.append(element);
-     }
-
-     argument.endArray();
-     return argument;
-}
-
-QDBusArgument &operator<<(QDBusArgument &argument,
-                          const ICd2DetailsList &detailsList)
-{
-     argument.beginArray(qMetaTypeId<ICd2DetailsDBusStruct>());
-
-     for (int i = 0; i < detailsList.count(); ++i)
-         argument << detailsList[i];
-
-     argument.endArray();
-
-     return argument;
-}
-
-static QHash<QString, QVariant> properties;
-
-static QString get_network_interface();
-
-void QNetworkSessionPrivateImpl::iapStateChanged(const QString& iapid, uint icd_connection_state)
-{
-
-    if (((publicConfig.type() == QNetworkConfiguration::UserChoice) &&
-         (activeConfig.identifier() == iapid)) ||
-        (publicConfig.identifier() == iapid)) {
-        switch (icd_connection_state) {
-        case ICD_STATE_CONNECTING:
-            updateState(QNetworkSession::Connecting);
-            break;
-        case ICD_STATE_CONNECTED:
-            updateState(QNetworkSession::Connected);
-            break;
-        case ICD_STATE_DISCONNECTING:
-            updateState(QNetworkSession::Closing);
-            break;
-        case ICD_STATE_DISCONNECTED:
-            updateState(QNetworkSession::Disconnected);
-            break;
-        default:
-            break;
-        }
-    }
-    if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
-        updateIdentifier(iapid);
-    }
-}
-
-void QNetworkSessionPrivateImpl::cleanupSession(void)
-{
-    QObject::disconnect(q, SIGNAL(stateChanged(QNetworkSession::State)),
-                        this, SLOT(updateProxies(QNetworkSession::State)));
-}
-
-
-void QNetworkSessionPrivateImpl::updateState(QNetworkSession::State newState)
-{
-    if (newState != state) {
-        if (newState == QNetworkSession::Disconnected) {
-            if (isOpen) {
-                // The Session was aborted by the user or system
-                lastError = QNetworkSession::SessionAbortedError;
-                emit QNetworkSessionPrivate::error(lastError);
-                emit closed();
-            }
-            if (m_stopTimer.isActive()) {
-                // Session was closed by calling stop()
-                m_stopTimer.stop();
-            }
-            isOpen = false;
-            opened = false;
-            currentNetworkInterface.clear();
-            if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
-                copyConfig(publicConfig, activeConfig);
-                IcdNetworkConfigurationPrivate *icdConfig =
-                    toIcdConfig(privateConfiguration(activeConfig));
-
-                icdConfig->mutex.lock();
-                icdConfig->state = QNetworkConfiguration::Defined;
-                icdConfig->mutex.unlock();
-
-                // Reset the state of the default configuration to Discovered
-                icdConfig = toIcdConfig(privateConfiguration(publicConfig));
-                icdConfig->mutex.lock();
-                icdConfig->state = QNetworkConfiguration::Discovered;
-                icdConfig->mutex.unlock();
-            } else {
-                if (!activeConfig.isValid()) {
-                    // Active configuration (IAP) was removed from system
-                    // => Connection was disconnected and configuration became
-                    //    invalid
-                    // => Also Session state must be changed to invalid
-                    newState = QNetworkSession::Invalid;
-                }
-            }
-        } else if (newState == QNetworkSession::Connected) {
-            if (opened) {
-                isOpen = true;
-            }
-           if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
-            IcdNetworkConfigurationPrivate *icdConfig =
-                toIcdConfig(privateConfiguration(activeConfig));
-
-            icdConfig->mutex.lock();
-            icdConfig->state = QNetworkConfiguration::Active;
-            icdConfig->type = QNetworkConfiguration::InternetAccessPoint;
-            icdConfig->mutex.unlock();
-           }
-
-        IcdNetworkConfigurationPrivate *icdConfig =
-            toIcdConfig(privateConfiguration(publicConfig));
-
-        icdConfig->mutex.lock();
-        icdConfig->state = QNetworkConfiguration::Active;
-        icdConfig->mutex.unlock();
-       }
-
-        if (newState != state) {
-            state = newState;
-            emit stateChanged(newState);
-        }
-    }
-}
-
-
-void QNetworkSessionPrivateImpl::updateIdentifier(const QString &newId)
-{
-    if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
-        IcdNetworkConfigurationPrivate *icdConfig =
-            toIcdConfig(privateConfiguration(activeConfig));
-
-        icdConfig->mutex.lock();
-        icdConfig->network_attrs |= ICD_NW_ATTR_IAPNAME;
-        icdConfig->id = newId;
-        icdConfig->mutex.unlock();
-    } else {
-        IcdNetworkConfigurationPrivate *icdConfig =
-            toIcdConfig(privateConfiguration(publicConfig));
-
-        icdConfig->mutex.lock();
-        icdConfig->network_attrs |= ICD_NW_ATTR_IAPNAME;
-        if (icdConfig->id != newId)
-            icdConfig->id = newId;
-        icdConfig->mutex.unlock();
-    }
-}
-
-
-QNetworkSessionPrivateImpl::Statistics QNetworkSessionPrivateImpl::getStatistics() const
-{
-    /* This could be also implemented by using the Maemo::Icd::statistics()
-     * that gets the statistics data for a specific IAP. Change if
-     * necessary.
-     */
-    Maemo::Icd icd;
-    QList<Maemo::IcdStatisticsResult> stats_results;
-    Statistics stats = { 0, 0, 0};
-
-    if (!icd.statistics(stats_results))
-        return stats;
-
-    foreach (const Maemo::IcdStatisticsResult &res, stats_results) {
-        if (res.params.network_attrs & ICD_NW_ATTR_IAPNAME) {
-            /* network_id is the IAP UUID */
-            if (QString(res.params.network_id.data()) == activeConfig.identifier()) {
-                stats.txData = res.bytes_sent;
-                stats.rxData = res.bytes_received;
-                stats.activeTime = res.time_active;
-            }
-        } else {
-            /* We probably will never get to this branch */
-            IcdNetworkConfigurationPrivate *icdConfig =
-                toIcdConfig(privateConfiguration(activeConfig));
-
-            icdConfig->mutex.lock();
-            if (res.params.network_id == icdConfig->network_id) {
-                stats.txData = res.bytes_sent;
-                stats.rxData = res.bytes_received;
-                stats.activeTime = res.time_active;
-            }
-            icdConfig->mutex.unlock();
-        }
-    }
-
-    return stats;
-}
-
-
-quint64 QNetworkSessionPrivateImpl::bytesWritten() const
-{
-    return getStatistics().txData;
-}
-
-quint64 QNetworkSessionPrivateImpl::bytesReceived() const
-{
-    return getStatistics().rxData;
-}
-
-quint64 QNetworkSessionPrivateImpl::activeTime() const
-{
-    return getStatistics().activeTime;
-}
-
-
-QNetworkConfiguration& QNetworkSessionPrivateImpl::copyConfig(QNetworkConfiguration &fromConfig,
-                                                              QNetworkConfiguration &toConfig,
-                                                              bool deepCopy)
-{
-    IcdNetworkConfigurationPrivate *cpPriv;
-    if (deepCopy) {
-        cpPriv = new IcdNetworkConfigurationPrivate;
-        setPrivateConfiguration(toConfig, QNetworkConfigurationPrivatePointer(cpPriv));
-    } else {
-        cpPriv = toIcdConfig(privateConfiguration(toConfig));
-    }
-
-    IcdNetworkConfigurationPrivate *fromPriv = toIcdConfig(privateConfiguration(fromConfig));
-
-    QMutexLocker toLocker(&cpPriv->mutex);
-    QMutexLocker fromLocker(&fromPriv->mutex);
-
-    cpPriv->name = fromPriv->name;
-    cpPriv->isValid = fromPriv->isValid;
-    // Note that we do not copy id field here as the publicConfig does
-    // not contain a valid IAP id.
-    cpPriv->state = fromPriv->state;
-    cpPriv->type = fromPriv->type;
-    cpPriv->roamingSupported = fromPriv->roamingSupported;
-    cpPriv->purpose = fromPriv->purpose;
-    cpPriv->network_id = fromPriv->network_id;
-    cpPriv->iap_type = fromPriv->iap_type;
-    cpPriv->bearerType = fromPriv->bearerType;
-    cpPriv->network_attrs = fromPriv->network_attrs;
-    cpPriv->service_type = fromPriv->service_type;
-    cpPriv->service_id = fromPriv->service_id;
-    cpPriv->service_attrs = fromPriv->service_attrs;
-
-    return toConfig;
-}
-
-
-/* This is called by QNetworkSession constructor and it updates the current
- * state of the configuration.
- */
-void QNetworkSessionPrivateImpl::syncStateWithInterface()
-{
-    /* Initially we are not active although the configuration might be in
-     * connected state.
-     */
-    isOpen = false;
-    opened = false;
-
-    connect(engine, SIGNAL(iapStateChanged(QString,uint)),
-            this, SLOT(iapStateChanged(QString,uint)));
-
-    QObject::connect(q, SIGNAL(stateChanged(QNetworkSession::State)), this, SLOT(updateProxies(QNetworkSession::State)));
-
-    state = QNetworkSession::Invalid;
-    lastError = QNetworkSession::UnknownSessionError;
-
-    switch (publicConfig.type()) {
-    case QNetworkConfiguration::InternetAccessPoint:
-        activeConfig = publicConfig;
-        break;
-    case QNetworkConfiguration::ServiceNetwork:
-        serviceConfig = publicConfig;
-       break;
-    case QNetworkConfiguration::UserChoice:
-       // active config will contain correct data after open() has succeeded
-        copyConfig(publicConfig, activeConfig);
-
-       /* We create new configuration that holds the actual configuration
-        * returned by icd. This way publicConfig still contains the
-        * original user specified configuration.
-        *
-        * Note that the new activeConfig configuration is not inserted
-        * to configurationManager as manager class will get the newly
-        * connected configuration from gconf when the IAP is saved.
-        * This configuration manager update is done by IapMonitor class.
-        * If the ANY connection fails in open(), then the configuration
-        * data is not saved to gconf and will not be added to
-        * configuration manager IAP list.
-        */
-#ifdef BEARER_MANAGEMENT_DEBUG
-       qDebug()<<"New configuration created for" << publicConfig.identifier();
-#endif
-       break;
-    default:
-       /* Invalid configuration, no point continuing */
-       return;
-    }
-
-    if (!activeConfig.isValid())
-       return;
-
-    /* Get the initial state from icd */
-    Maemo::Icd icd;
-    QList<Maemo::IcdStateResult> state_results;
-
-    /* Update the active config from first connection, this is ok as icd
-     * supports only one connection anyway.
-     */
-    if (icd.state(state_results) && !state_results.isEmpty()) {
-       /* If we did not get full state back, then we are not
-        * connected and can skip the next part.
-        */
-       if (!(state_results.first().params.network_attrs == 0 &&
-               state_results.first().params.network_id.isEmpty())) {
-
-           /* If we try to connect to specific IAP and we get results back
-            * that tell the icd is actually connected to another IAP,
-            * then do not update current state etc.
-            */
-           if (publicConfig.type() == QNetworkConfiguration::UserChoice ||
-            publicConfig.identifier() == state_results.first().params.network_id) {
-               switch (state_results.first().state) {
-               case ICD_STATE_DISCONNECTED:
-            state = QNetworkSession::Disconnected;
-            if (QNetworkConfigurationPrivatePointer ptr = privateConfiguration(activeConfig)) {
-                ptr->mutex.lock();
-                ptr->isValid = true;
-                ptr->mutex.unlock();
-            }
-            break;
-               case ICD_STATE_CONNECTING:
-            state = QNetworkSession::Connecting;
-            if (QNetworkConfigurationPrivatePointer ptr = privateConfiguration(activeConfig)) {
-                ptr->mutex.lock();
-                ptr->isValid = true;
-                ptr->mutex.unlock();
-            }
-            break;
-               case ICD_STATE_CONNECTED:
-        {
-            if (!state_results.first().error.isEmpty())
-                break;
-
-            const QString id = state_results.first().params.network_id;
-
-            QNetworkConfiguration config = manager.configurationFromIdentifier(id);
-            if (config.isValid()) {
-                //we don't want the copied data if the config is already known by the manager
-                //just reuse it so that existing references to the old data get the same update
-                setPrivateConfiguration(activeConfig, privateConfiguration(config));
-            }
-
-            QNetworkConfigurationPrivatePointer ptr = privateConfiguration(activeConfig);
-
-            QMutexLocker configLocker(&ptr->mutex);
-
-                       state = QNetworkSession::Connected;
-            toIcdConfig(ptr)->network_id = state_results.first().params.network_id;
-            ptr->id = toIcdConfig(ptr)->network_id;
-            toIcdConfig(ptr)->network_attrs = state_results.first().params.network_attrs;
-            toIcdConfig(ptr)->iap_type = state_results.first().params.network_type;
-            ptr->bearerType = bearerTypeFromIapType(toIcdConfig(ptr)->iap_type);
-            toIcdConfig(ptr)->service_type = state_results.first().params.service_type;
-            toIcdConfig(ptr)->service_id = state_results.first().params.service_id;
-            toIcdConfig(ptr)->service_attrs = state_results.first().params.service_attrs;
-            ptr->type = QNetworkConfiguration::InternetAccessPoint;
-            ptr->state = QNetworkConfiguration::Active;
-            ptr->isValid = true;
-            currentNetworkInterface = get_network_interface();
-
-            Maemo::IAPConf iap_name(ptr->id);
-                       QString name_value = iap_name.value("name").toString();
-                       if (!name_value.isEmpty())
-                ptr->name = name_value;
-                       else
-                ptr->name = ptr->id;
-
-            const QString identifier = ptr->id;
-
-            configLocker.unlock();
-
-            // Add the new active configuration to manager or update the old config
-            if (!engine->hasIdentifier(identifier))
-                engine->addSessionConfiguration(ptr);
-            else
-                engine->changedSessionConfiguration(ptr);
-        }
-        break;
-
-               case ICD_STATE_DISCONNECTING:
-            state = QNetworkSession::Closing;
-            if (QNetworkConfigurationPrivatePointer ptr = privateConfiguration(activeConfig)) {
-                ptr->mutex.lock();
-                ptr->isValid = true;
-                ptr->mutex.unlock();
-            }
-            break;
-               default:
-            break;
-               }
-    }
-       } else {
-#ifdef BEARER_MANAGEMENT_DEBUG
-           qDebug() << "status_req tells icd is not connected";
-#endif
-       }
-    } else {
-#ifdef BEARER_MANAGEMENT_DEBUG
-       qDebug() << "status_req did not return any results from icd";
-#endif
-    }
-
-    networkConfigurationsChanged();
-}
-
-
-void QNetworkSessionPrivateImpl::networkConfigurationsChanged()
-{
-    if (serviceConfig.isValid())
-        updateStateFromServiceNetwork();
-    else
-        updateStateFromActiveConfig();
-}
-
-
-void QNetworkSessionPrivateImpl::updateStateFromServiceNetwork()
-{
-    QNetworkSession::State oldState = state;
-
-    foreach (const QNetworkConfiguration &config, serviceConfig.children()) {
-        if ((config.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active)
-            continue;
-
-        if (activeConfig != config) {
-            activeConfig = config;
-            emit newConfigurationActivated();
-        }
-
-        state = QNetworkSession::Connected;
-        if (state != oldState)
-            emit stateChanged(state);
-
-        return;
-    }
-
-    if (serviceConfig.children().isEmpty())
-        state = QNetworkSession::NotAvailable;
-    else
-        state = QNetworkSession::Disconnected;
-
-    if (state != oldState)
-        emit stateChanged(state);
-}
-
-
-void QNetworkSessionPrivateImpl::clearConfiguration(QNetworkConfiguration &config)
-{
-    IcdNetworkConfigurationPrivate *icdConfig = toIcdConfig(privateConfiguration(config));
-
-    QMutexLocker locker(&icdConfig->mutex);
-
-    icdConfig->network_id.clear();
-    icdConfig->iap_type.clear();
-    icdConfig->network_attrs = 0;
-    icdConfig->service_type.clear();
-    icdConfig->service_id.clear();
-    icdConfig->service_attrs = 0;
-}
-
-
-void QNetworkSessionPrivateImpl::updateStateFromActiveConfig()
-{
-    QNetworkSession::State oldState = state;
-
-    bool newActive = false;
-
-    if (!activeConfig.isValid())
-        return;
-
-    if (!activeConfig.isValid()) {
-        state = QNetworkSession::Invalid;
-        clearConfiguration(activeConfig);
-    } else if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
-        state = QNetworkSession::Connected;
-        newActive = opened;
-    } else if ((activeConfig.state() & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) {
-        state = QNetworkSession::Disconnected;
-    } else if ((activeConfig.state() & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) {
-        state = QNetworkSession::NotAvailable;
-    } else if ((activeConfig.state() & QNetworkConfiguration::Undefined) == QNetworkConfiguration::Undefined) {
-        state = QNetworkSession::NotAvailable;
-    }
-
-    bool oldActive = isOpen;
-    isOpen = newActive;
-
-    if (!oldActive && isOpen)
-        emit quitPendingWaitsForOpened();
-
-    if (oldActive && !isOpen)
-        emit closed();
-
-    if (oldState != state) {
-        emit stateChanged(state);
-
-    if (state == QNetworkSession::Disconnected && oldActive) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-           //qDebug()<<"session aborted error emitted for"<<activeConfig.identifier();
-#endif
-           lastError = QNetworkSession::SessionAbortedError;
-        emit QNetworkSessionPrivate::error(lastError);
-       }
-    }
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-    //qDebug()<<"oldState ="<<oldState<<" state ="<<state<<" oldActive ="<<oldActive<<" newActive ="<<newActive<<" opened ="<<opened;
-#endif
-}
-
-static QString get_network_interface()
-{
-    Maemo::Icd icd;
-    QList<Maemo::IcdAddressInfoResult> addr_results;
-    uint ret;
-    QString iface;
-
-    ret = icd.addrinfo(addr_results);
-    if (ret == 0) {
-       /* No results */
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug() << "Cannot get addrinfo from icd, are you connected or is icd running?";
-#endif
-        return iface;
-    }
-
-    if (addr_results.first().ip_info.isEmpty())
-        return QString();
-
-    QByteArray data = addr_results.first().ip_info.first().address.toAscii();
-    struct in_addr addr;
-    if (inet_aton(data.constData(), &addr) == 0) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug() << "address" << data.constData() << "invalid";
-#endif
-        return iface;
-    }
-
-    struct ifaddrs *ifaddr, *ifa;
-    int family;
-
-    if (getifaddrs(&ifaddr) == -1) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-       qDebug() << "getifaddrs() failed";
-#endif
-       return iface;
-    }
-
-    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
-        if (ifa->ifa_addr) {
-            family = ifa->ifa_addr->sa_family;
-            if (family != AF_INET) {
-                continue; /* Currently only IPv4 is supported by icd dbus interface */
-            }
-            if (((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr == addr.s_addr) {
-                iface = QString(ifa->ifa_name);
-                break;
-            }
-        }
-    }
-
-    freeifaddrs(ifaddr);
-    return iface;
-}
-
-
-void QNetworkSessionPrivateImpl::open()
-{
-    if (m_stopTimer.isActive()) {
-        m_stopTimer.stop();
-    }
-    if (!publicConfig.isValid()) {
-        lastError = QNetworkSession::InvalidConfigurationError;
-        emit QNetworkSessionPrivate::error(lastError);
-        return;
-    }
-    if (serviceConfig.isValid()) {
-        lastError = QNetworkSession::OperationNotSupportedError;
-        emit QNetworkSessionPrivate::error(lastError);
-    } else if (!opened) {
-       if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
-           /* Caller is trying to connect to default IAP.
-            * At this time we will not know the IAP details so we just
-            * connect and update the active config when the IAP is
-            * connected.
-            */
-           opened = true;
-            state = QNetworkSession::Connecting;
-            emit stateChanged(state);
-           QTimer::singleShot(0, this, SLOT(do_open()));
-           return;
-       }
-
-       /* User is connecting to one specific IAP. If that IAP is not
-        * in discovered state we cannot continue.
-        */
-        if ((activeConfig.state() & QNetworkConfiguration::Discovered) !=
-            QNetworkConfiguration::Discovered) {
-            lastError =QNetworkSession::InvalidConfigurationError;
-            emit QNetworkSessionPrivate::error(lastError);
-            return;
-        }
-        opened = true;
-
-        if ((activeConfig.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active) {
-            state = QNetworkSession::Connecting;
-            emit stateChanged(state);
-            QTimer::singleShot(0, this, SLOT(do_open()));
-            return;
-        }
-        isOpen = (activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active;
-        if (isOpen)
-            emit quitPendingWaitsForOpened();
-    } else {
-        /* We seem to be active so inform caller */
-        emit quitPendingWaitsForOpened();
-    }
-}
-
-void QNetworkSessionPrivateImpl::do_open()
-{
-    icd_connection_flags flags = connectFlags;
-    QString iap = publicConfig.identifier();
-
-    if (state == QNetworkSession::Connected) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug() << "Already connected to" << activeConfig.identifier();
-#endif
-        emit stateChanged(QNetworkSession::Connected);
-        emit quitPendingWaitsForOpened();
-       return;
-    }
-
-    if (publicConfig.type() == QNetworkConfiguration::UserChoice)
-        config = activeConfig;
-    else
-        config = publicConfig;
-
-    if (iap == OSSO_IAP_ANY) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug() << "connecting to default IAP" << iap;
-#endif
-        m_connectRequestTimer.start(ICD_LONG_CONNECT_TIMEOUT);
-        m_dbusInterface->asyncCall(ICD_DBUS_API_CONNECT_REQ, (uint)flags); // Return value ignored
-        m_asynchCallActive = true;
-    } else {
-        IcdNetworkConfigurationPrivate *icdConfig = toIcdConfig(privateConfiguration(config));
-
-        icdConfig->mutex.lock();
-        ICd2DetailsDBusStruct icd2;
-        icd2.serviceType = icdConfig->service_type;
-        icd2.serviceAttributes = icdConfig->service_attrs;
-        icd2.setviceId = icdConfig->service_id;
-        icd2.networkType = icdConfig->iap_type;
-        icd2.networkAttributes = icdConfig->network_attrs;
-        if (icdConfig->network_attrs & ICD_NW_ATTR_IAPNAME) {
-            icd2.networkId  = QByteArray(iap.toLatin1());
-        } else {
-            icd2.networkId  = icdConfig->network_id;
-        }
-        icdConfig->mutex.unlock();
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-    qDebug("connecting to %s/%s/0x%x/%s/0x%x/%s",
-        icd2.networkId.data(),
-        icd2.networkType.toAscii().constData(),
-        icd2.networkAttributes,
-        icd2.serviceType.toAscii().constData(),
-        icd2.serviceAttributes,
-        icd2.setviceId.toAscii().constData());
-#endif
-
-        ICd2DetailsList paramArray;
-        paramArray.append(icd2);
-        m_connectRequestTimer.start(ICD_LONG_CONNECT_TIMEOUT);
-        m_dbusInterface->asyncCall(ICD_DBUS_API_CONNECT_REQ, (uint)flags, QVariant::fromValue(paramArray)); // Return value ignored
-        m_asynchCallActive = true;
-    }
-}
-
-void QNetworkSessionPrivateImpl::stateChange(const QDBusMessage& rep)
-{
-     if (m_asynchCallActive == true) {
-        if (m_connectRequestTimer.isActive())
-            m_connectRequestTimer.stop();
-        m_asynchCallActive = false;
-
-        QString result = rep.arguments().at(5).toString(); // network id or empty string
-        QString connected_iap = result;
-        if (connected_iap.isEmpty()) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug() << "connect to"<< publicConfig.identifier() << "failed, result is empty";
-#endif
-            updateState(QNetworkSession::Disconnected);
-            emit QNetworkSessionPrivate::error(QNetworkSession::SessionAbortedError);
-            if (publicConfig.type() == QNetworkConfiguration::UserChoice)
-                    copyConfig(publicConfig, activeConfig);
-            return;
-        }
-
-         /* If the user tried to connect to some specific connection (foo)
-         * and we were already connected to some other connection (bar),
-         * then we cannot activate this session although icd has a valid
-         * connection to somewhere.
-         */
-        if ((publicConfig.type() != QNetworkConfiguration::UserChoice) &&
-            (connected_iap != config.identifier())) {
-            updateState(QNetworkSession::Disconnected);
-            emit QNetworkSessionPrivate::error(QNetworkSession::UnknownSessionError);
-            return;
-        }
-
-        IcdNetworkConfigurationPrivate *icdConfig = toIcdConfig(privateConfiguration(config));
-
-        /* Did we connect to non saved IAP? */
-        icdConfig->mutex.lock();
-        if (!(icdConfig->network_attrs & ICD_NW_ATTR_IAPNAME)) {
-            /* Because the connection succeeded, the IAP is now known.
-             */
-            icdConfig->network_attrs |= ICD_NW_ATTR_IAPNAME;
-            icdConfig->id = connected_iap;
-        }
-
-        /* User might have changed the IAP name when a new IAP was saved */
-        Maemo::IAPConf iap_name(icdConfig->id);
-        QString name = iap_name.value("name").toString();
-        if (!name.isEmpty())
-            icdConfig->name = name;
-
-        icdConfig->iap_type = rep.arguments().at(3).toString(); // connect_result.connect.network_type;
-        icdConfig->bearerType = bearerTypeFromIapType(icdConfig->iap_type);
-        icdConfig->isValid = true;
-        icdConfig->state = QNetworkConfiguration::Active;
-        icdConfig->type = QNetworkConfiguration::InternetAccessPoint;
-
-        icdConfig->mutex.unlock();
-
-        startTime = QDateTime::currentDateTime();
-        updateState(QNetworkSession::Connected);
-        //currentNetworkInterface = get_network_interface();
-#ifdef BEARER_MANAGEMENT_DEBUG
-        //qDebug() << "connected to" << result << config.name() << "at" << currentNetworkInterface;
-#endif
-
-        /* We first check if the configuration already exists in the manager
-         * and if it is not found there, we then insert it. Note that this
-         * is only done for user choice config only because it can be missing
-         * from config manager list.
-         */
-        if (publicConfig.type() == QNetworkConfiguration::UserChoice) {
-            if (!engine->hasIdentifier(result)) {
-                engine->addSessionConfiguration(privateConfiguration(config));
-            } else {
-                QNetworkConfigurationPrivatePointer priv = engine->configuration(result);
-                QNetworkConfiguration reference;
-                setPrivateConfiguration(reference, priv);
-                copyConfig(config, reference, false);
-                privateConfiguration(reference)->id = result; // Note: Id was not copied in copyConfig() function
-                config = reference;
-                activeConfig = reference;
-                engine->changedSessionConfiguration(privateConfiguration(config));
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-                qDebug()<<"Existing configuration"<<result<<"updated in manager in open";
-#endif
-            }
-        }
-
-        emit quitPendingWaitsForOpened();
-    }
-}
-
-void QNetworkSessionPrivateImpl::connectTimeout()
-{
-    updateState(QNetworkSession::Disconnected);
-    if (publicConfig.type() == QNetworkConfiguration::UserChoice)
-            copyConfig(publicConfig, activeConfig);
-        emit QNetworkSessionPrivate::error(QNetworkSession::UnknownSessionError);
-}
-
-void QNetworkSessionPrivateImpl::close()
-{
-    if (m_connectRequestTimer.isActive())
-        m_connectRequestTimer.stop();
-
-    if (serviceConfig.isValid()) {
-        lastError = QNetworkSession::OperationNotSupportedError;
-        emit QNetworkSessionPrivate::error(lastError);
-    } else if (isOpen) {
-        if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
-           // We will not wait any disconnect from icd as it might never come
-#ifdef BEARER_MANAGEMENT_DEBUG
-           qDebug() << "closing session" << publicConfig.identifier();
-#endif
-           state = QNetworkSession::Closing;
-           emit stateChanged(state);
-
-           // we fake a disconnection, session error is sent
-           updateState(QNetworkSession::Disconnected);
-
-           opened = false;
-           isOpen = false;
-
-        m_dbusInterface->call(ICD_DBUS_API_DISCONNECT_REQ, ICD_CONNECTION_FLAG_APPLICATION_EVENT);
-           startTime = QDateTime();
-        } else {
-           opened = false;
-           isOpen = false;
-           emit closed();
-       }
-    }
-}
-
-
-void QNetworkSessionPrivateImpl::stop()
-{
-    if (m_connectRequestTimer.isActive())
-        m_connectRequestTimer.stop();
-
-    if (serviceConfig.isValid()) {
-        lastError = QNetworkSession::OperationNotSupportedError;
-        emit QNetworkSessionPrivate::error(lastError);
-    } else {
-        if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-           qDebug() << "stopping session" << publicConfig.identifier();
-#endif
-           state = QNetworkSession::Closing;
-           emit stateChanged(state);
-
-           // we fake a disconnection, a session error is sent also
-           updateState(QNetworkSession::Disconnected);
-
-           opened = false;
-           isOpen = false;
-
-        m_dbusInterface->call(ICD_DBUS_API_DISCONNECT_REQ, ICD_CONNECTION_FLAG_APPLICATION_EVENT);
-           startTime = QDateTime();
-        } else {
-           opened = false;
-           isOpen = false;
-           emit closed();
-       }
-    }
-}
-
-void QNetworkSessionPrivateImpl::finishStopBySendingClosedSignal()
-{
-    if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
-        state = QNetworkSession::Connected;
-        emit stateChanged(state);
-    }
-
-    emit closed();
-}
-
-void QNetworkSessionPrivateImpl::migrate()
-{
-}
-
-
-void QNetworkSessionPrivateImpl::accept()
-{
-}
-
-
-void QNetworkSessionPrivateImpl::ignore()
-{
-}
-
-
-void QNetworkSessionPrivateImpl::reject()
-{
-}
-
-#ifndef QT_NO_NETWORKINTERFACE
-QNetworkInterface QNetworkSessionPrivateImpl::currentInterface() const
-{
-    if (!publicConfig.isValid() || state != QNetworkSession::Connected)
-        return QNetworkInterface();
-
-    if (currentNetworkInterface.isEmpty())
-        return QNetworkInterface();
-
-    return QNetworkInterface::interfaceFromName(currentNetworkInterface);
-}
-#endif
-
-void QNetworkSessionPrivateImpl::setSessionProperty(const QString& key, const QVariant& value)
-{
-    if (value.isValid()) {
-       properties.insert(key, value);
-
-       if (key == "ConnectInBackground") {
-           bool v = value.toBool();
-           if (v)
-               connectFlags = ICD_CONNECTION_FLAG_APPLICATION_EVENT;
-           else
-               connectFlags = ICD_CONNECTION_FLAG_USER_EVENT;
-       }
-    } else {
-       properties.remove(key);
-
-       /* Set default value when property is removed */
-       if (key == "ConnectInBackground")
-           connectFlags = ICD_CONNECTION_FLAG_USER_EVENT;
-    }
-}
-
-
-QVariant QNetworkSessionPrivateImpl::sessionProperty(const QString& key) const
-{
-    return properties.value(key);
-}
-
-
-QString QNetworkSessionPrivateImpl::errorString() const
-{
-    QString errorStr;
-    switch(q->error()) {
-    case QNetworkSession::RoamingError:
-        errorStr = QNetworkSessionPrivateImpl::tr("Roaming error");
-        break;
-    case QNetworkSession::SessionAbortedError:
-        errorStr = QNetworkSessionPrivateImpl::tr("Session aborted by user or system");
-        break;
-    case QNetworkSession::InvalidConfigurationError:
-        errorStr = QNetworkSessionPrivateImpl::tr("The specified configuration cannot be used.");
-        break;
-    default:
-    case QNetworkSession::UnknownSessionError:
-        errorStr = QNetworkSessionPrivateImpl::tr("Unidentified Error");
-        break;
-    }
-    return errorStr;
-}
-
-
-QNetworkSession::SessionError QNetworkSessionPrivateImpl::error() const
-{
-    return QNetworkSession::UnknownSessionError;
-}
-
-void QNetworkSessionPrivateImpl::updateProxies(QNetworkSession::State newState)
-{
-    if ((newState == QNetworkSession::Connected) &&
-       (newState != currentState))
-       updateProxyInformation();
-    else if ((newState == QNetworkSession::Disconnected) &&
-           (currentState == QNetworkSession::Closing))
-       clearProxyInformation();
-
-    currentState = newState;
-}
-
-
-void QNetworkSessionPrivateImpl::updateProxyInformation()
-{
-    Maemo::ProxyConf::update();
-}
-
-
-void QNetworkSessionPrivateImpl::clearProxyInformation()
-{
-    Maemo::ProxyConf::clear();
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
-#include "moc_qnetworksession_impl.h"
diff --git a/src/plugins/bearer/icd/qnetworksession_impl.h b/src/plugins/bearer/icd/qnetworksession_impl.h
deleted file mode 100644 (file)
index 8ddaa9f..0000000
+++ /dev/null
@@ -1,229 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QNETWORKSESSION_IMPL_H
-#define QNETWORKSESSION_IMPL_H
-
-//
-//  W A R N I N G
-//  -------------
-//
-// This file is not part of the Qt API.  It exists for the convenience
-// of the QLibrary class.  This header file may change from
-// version to version without notice, or even be removed.
-//
-// We mean it.
-//
-
-#include <QtNetwork/qnetworksession_p.h>
-#include <QtNetwork/qnetworkconfigmanager.h>
-
-#include <QtCore/qdatetime.h>
-#include <QtCore/qtimer.h>
-#include <QtCore/quuid.h>
-
-#include <QtDBus/qdbusconnection.h>
-#include <QtDBus/qdbusinterface.h>
-#include <QtDBus/qdbusmessage.h>
-#include <QtDBus/qdbusmetatype.h>
-
-#include <icd/dbus_api.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-class QIcdEngine;
-
-struct ICd2DetailsDBusStruct
-{
-    QString serviceType;
-    uint serviceAttributes;
-    QString setviceId;
-    QString networkType;
-    uint networkAttributes;
-    QByteArray networkId;
-};
-
-typedef QList<ICd2DetailsDBusStruct> ICd2DetailsList;
-
-class QNetworkSessionPrivateImpl : public QNetworkSessionPrivate
-{
-    Q_OBJECT
-
-public:
-    QNetworkSessionPrivateImpl(QIcdEngine *engine)
-    :   engine(engine),
-        connectFlags(ICD_CONNECTION_FLAG_USER_EVENT),
-        currentState(QNetworkSession::Invalid),
-        m_asynchCallActive(false)
-    {
-        m_stopTimer.setSingleShot(true);
-        connect(&m_stopTimer, SIGNAL(timeout()), this, SLOT(finishStopBySendingClosedSignal()));
-
-        QDBusConnection systemBus = QDBusConnection::connectToBus(
-            QDBusConnection::SystemBus,
-            QUuid::createUuid().toString());
-
-        m_dbusInterface = new QDBusInterface(ICD_DBUS_API_INTERFACE,
-                                         ICD_DBUS_API_PATH,
-                                         ICD_DBUS_API_INTERFACE,
-                                         systemBus,
-                                         this);
-
-        systemBus.connect(ICD_DBUS_API_INTERFACE,
-                        ICD_DBUS_API_PATH,
-                        ICD_DBUS_API_INTERFACE,
-                        ICD_DBUS_API_CONNECT_SIG,
-                        this,
-                        SLOT(stateChange(const QDBusMessage&)));
-
-        qDBusRegisterMetaType<ICd2DetailsDBusStruct>();
-        qDBusRegisterMetaType<ICd2DetailsList>();
-
-        m_connectRequestTimer.setSingleShot(true);
-        connect(&m_connectRequestTimer, SIGNAL(timeout()), this, SLOT(connectTimeout()));
-    }
-
-    ~QNetworkSessionPrivateImpl()
-    {
-        cleanupSession();
-
-        QDBusConnection::disconnectFromBus(m_dbusInterface->connection().name());
-    }
-
-    //called by QNetworkSession constructor and ensures
-    //that the state is immediately updated (w/o actually opening
-    //a session). Also this function should take care of 
-    //notification hooks to discover future state changes.
-    void syncStateWithInterface();
-
-#ifndef QT_NO_NETWORKINTERFACE
-    QNetworkInterface currentInterface() const;
-#endif
-    QVariant sessionProperty(const QString& key) const;
-    void setSessionProperty(const QString& key, const QVariant& value);
-
-    void open();
-    void close();
-    void stop();
-
-    void migrate();
-    void accept();
-    void ignore();
-    void reject();
-
-    QString errorString() const; //must return translated string
-    QNetworkSession::SessionError error() const;
-
-    quint64 bytesWritten() const;
-    quint64 bytesReceived() const;
-    quint64 activeTime() const;
-
-private:
-    void updateStateFromServiceNetwork();
-    void updateStateFromActiveConfig();
-
-private Q_SLOTS:
-    void do_open();
-    void networkConfigurationsChanged();
-    void iapStateChanged(const QString& iapid, uint icd_connection_state);
-    void updateProxies(QNetworkSession::State newState);
-    void finishStopBySendingClosedSignal();
-    void stateChange(const QDBusMessage& rep);
-    void connectTimeout();
-
-private:
-    QNetworkConfigurationManager manager;
-    QIcdEngine *engine;
-
-    struct Statistics {
-        quint64 txData;
-        quint64 rxData;
-        quint64 activeTime;
-    };
-
-    // The config set on QNetworkSession.
-    QNetworkConfiguration config;
-
-    QNetworkConfiguration& copyConfig(QNetworkConfiguration &fromConfig, QNetworkConfiguration &toConfig, bool deepCopy = true);
-    void clearConfiguration(QNetworkConfiguration &config);
-
-    bool opened;
-    icd_connection_flags connectFlags;
-
-    QNetworkSession::SessionError lastError;
-
-    QDateTime startTime;
-    QString currentNetworkInterface;
-    friend class IcdListener;
-    void updateState(QNetworkSession::State);
-    void updateIdentifier(const QString &newId);
-    Statistics getStatistics() const;
-    void cleanupSession(void);
-
-    void updateProxyInformation();
-    void clearProxyInformation();
-    QNetworkSession::State currentState;
-
-    QDBusInterface *m_dbusInterface;
-
-    QTimer m_stopTimer;
-
-    bool m_asynchCallActive;
-    QTimer m_connectRequestTimer;
-};
-
-// Marshall the ICd2DetailsDBusStruct data into a D-Bus argument
-QDBusArgument &operator<<(QDBusArgument &argument, const ICd2DetailsDBusStruct &icd2);
-
-// Retrieve the ICd2DetailsDBusStruct data from the D-Bus argument
-const QDBusArgument &operator>>(const QDBusArgument &argument, ICd2DetailsDBusStruct &icd2);
-
-Q_DECLARE_METATYPE(ICd2DetailsDBusStruct);
-Q_DECLARE_METATYPE(ICd2DetailsList);
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
-
-#endif //QNETWORKSESSIONPRIVATE_H
-
diff --git a/src/plugins/bearer/icd/wlan-utils.h b/src/plugins/bearer/icd/wlan-utils.h
deleted file mode 100644 (file)
index 5a3a7d7..0000000
+++ /dev/null
@@ -1,110 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-
-#ifndef WLAN_UTILS_H
-#define WLAN_UTILS_H
-
-/** Originally taken from: libicd-network-wlan-dev.h*/
-
-#include <glib.h>
-#include <dbus/dbus.h>
-#include <wlancond.h>
-#include <icd/network_api_defines.h>
-
-/* capability bits inside network attributes var */
-#define NWATTR_WPS_MASK       0x0000F000
-#define NWATTR_ALGORITHM_MASK 0x00000F00
-#define NWATTR_WPA2_MASK      0x00000080
-#define NWATTR_METHOD_MASK    0x00000078
-#define NWATTR_MODE_MASK      0x00000007
-
-#define CAP_LOCALMASK         0x0FFFE008
-
-/* how much to shift between capability and network attributes var */
-#define CAP_SHIFT_WPS        3
-#define CAP_SHIFT_ALGORITHM 20
-#define CAP_SHIFT_WPA2       1
-#define CAP_SHIFT_METHOD     1
-#define CAP_SHIFT_MODE       0
-#define CAP_SHIFT_ALWAYS_ONLINE 26
-
-/* ------------------------------------------------------------------------- */
-/* From combined to capability */
-static inline dbus_uint32_t nwattr2cap(guint nwattrs, dbus_uint32_t *cap)
-{
-       guint oldval = *cap;
-
-       *cap &= CAP_LOCALMASK; /* clear old capabilities */
-       *cap |=
-               ((nwattrs & ICD_NW_ATTR_ALWAYS_ONLINE) >> CAP_SHIFT_ALWAYS_ONLINE) |
-               ((nwattrs & NWATTR_WPS_MASK) >> CAP_SHIFT_WPS) |
-               ((nwattrs & NWATTR_ALGORITHM_MASK) << CAP_SHIFT_ALGORITHM) |
-               ((nwattrs & NWATTR_WPA2_MASK) << CAP_SHIFT_WPA2) |
-               ((nwattrs & NWATTR_METHOD_MASK) << CAP_SHIFT_METHOD) |
-               (nwattrs & NWATTR_MODE_MASK);
-
-       return oldval;
-}
-
-
-/* ------------------------------------------------------------------------- */
-/* From capability to combined */
-static inline guint cap2nwattr(dbus_uint32_t cap, guint *nwattrs)
-{
-       guint oldval = *nwattrs;
-
-       *nwattrs &= ~ICD_NW_ATTR_LOCALMASK; /* clear old capabilities */
-        *nwattrs |=
-#ifdef WLANCOND_WPS_MASK
-               ((cap & WLANCOND_WPS_MASK) << CAP_SHIFT_WPS) |
-#endif
-               ((cap & (WLANCOND_ENCRYPT_ALG_MASK |
-                        WLANCOND_ENCRYPT_GROUP_ALG_MASK)) >> CAP_SHIFT_ALGORITHM)|
-               ((cap & WLANCOND_ENCRYPT_WPA2_MASK) >> CAP_SHIFT_WPA2) |
-               ((cap & WLANCOND_ENCRYPT_METHOD_MASK) >> CAP_SHIFT_METHOD) |
-               (cap & WLANCOND_MODE_MASK);
-
-       return oldval;
-}
-
-
-#endif
diff --git a/src/plugins/bearer/nativewifi/platformdefs.h b/src/plugins/bearer/nativewifi/platformdefs.h
deleted file mode 100644 (file)
index 4f10c26..0000000
+++ /dev/null
@@ -1,329 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef PLATFORMDEFS_H
-#define PLATFORMDEFS_H
-
-#include <wtypes.h>
-#undef interface
-
-//proper header is wlanapi.h, but that is not included in windows XP
-
-#define WLAN_MAX_NAME_LENGTH 256
-#define WLAN_MAX_PHY_TYPE_NUMBER 8
-#define WLAN_NOTIFICATION_SOURCE_ACM 0x00000008
-#define WLAN_NOTIFICATION_SOURCE_ALL 0x0000ffff
-#define WLAN_AVAILABLE_NETWORK_CONNECTED 1
-#define WLAN_AVAILABLE_NETWORK_HAS_PROFILE 2
-#define DOT11_SSID_MAX_LENGTH 32
-
-QT_BEGIN_NAMESPACE
-
-struct WLAN_NOTIFICATION_DATA {
-    DWORD NotificationSource;
-    DWORD NotificationCode;
-    GUID InterfaceGuid;
-    DWORD dwDataSize;
-    PVOID pData;
-};
-
-enum WLAN_INTERFACE_STATE {
-    wlan_interface_state_not_ready = 0,
-    wlan_interface_state_connected,
-    wlan_interface_state_ad_hoc_network_formed,
-    wlan_interface_state_disconnecting,
-    wlan_interface_state_disconnected,
-    wlan_interface_state_associating,
-    wlan_interface_state_discovering,
-    wlan_interface_state_authenticating
-};
-
-struct WLAN_INTERFACE_INFO {
-    GUID InterfaceGuid;
-    WCHAR strInterfaceDescription[WLAN_MAX_NAME_LENGTH];
-    WLAN_INTERFACE_STATE isState;
-};
-
-struct WLAN_INTERFACE_INFO_LIST {
-    DWORD dwNumberOfItems;
-    DWORD dwIndex;
-    WLAN_INTERFACE_INFO InterfaceInfo[1];
-};
-
-struct DOT11_SSID {
-    ULONG uSSIDLength;
-    UCHAR ucSSID[DOT11_SSID_MAX_LENGTH];
-};
-
-struct NDIS_OBJECT_HEADER {
-    UCHAR Type;
-    UCHAR Revision;
-    USHORT Size;
-};
-
-typedef UCHAR DOT11_MAC_ADDRESS[6];
-struct DOT11_BSSID_LIST {
-    NDIS_OBJECT_HEADER Header;
-    ULONG uNumberOfEntries;
-    ULONG uTotalNumOfEntries;
-    DOT11_MAC_ADDRESS BSSIDs[1];
-};
-
-enum DOT11_BSS_TYPE {
-    dot11_BSS_type_infrastructure = 1,
-    dot11_BSS_type_independent = 2,
-    dot11_BSS_type_any = 3
-};
-
-enum DOT11_PHY_TYPE {
-    dot11_phy_type_unknown = 0,
-    dot11_phy_type_any = dot11_phy_type_unknown,
-    dot11_phy_type_fhss = 1,
-    dot11_phy_type_dsss = 2,
-    dot11_phy_type_irbaseband = 3,
-    dot11_phy_type_ofdm = 4,
-    dot11_phy_type_hrdsss = 5,
-    dot11_phy_type_erp = 6,
-    dot11_phy_type_ht = 7,
-    dot11_phy_type_IHV_start = 0x80000000,
-    dot11_phy_type_IHV_end = 0xffffffff
-};
-
-enum DOT11_AUTH_ALGORITHM {
-    DOT11_AUTH_ALGO_80211_OPEN = 1,
-    DOT11_AUTH_ALGO_80211_SHARED_KEY = 2,
-    DOT11_AUTH_ALGO_WPA = 3,
-    DOT11_AUTH_ALGO_WPA_PSK = 4,
-    DOT11_AUTH_ALGO_WPA_NONE = 5,
-    DOT11_AUTH_ALGO_RSNA = 6,
-    DOT11_AUTH_ALGO_RSNA_PSK = 7,
-    DOT11_AUTH_ALGO_IHV_START = 0x80000000,
-    DOT11_AUTH_ALGO_IHV_END = 0xffffffff
-};
-
-enum DOT11_CIPHER_ALGORITHM {
-    DOT11_CIPHER_ALGO_NONE = 0x00,
-    DOT11_CIPHER_ALGO_WEP40 = 0x01,
-    DOT11_CIPHER_ALGO_TKIP = 0x02,
-    DOT11_CIPHER_ALGO_CCMP = 0x04,
-    DOT11_CIPHER_ALGO_WEP104 = 0x05,
-    DOT11_CIPHER_ALGO_WPA_USE_GROUP = 0x100,
-    DOT11_CIPHER_ALGO_RSN_USE_GROUP = 0x100,
-    DOT11_CIPHER_ALGO_WEP = 0x101,
-    DOT11_CIPHER_ALGO_IHV_START = 0x80000000,
-    DOT11_CIPHER_ALGO_IHV_END = 0xffffffff
-};
-
-struct WLAN_AVAILABLE_NETWORK {
-    WCHAR strProfileName[WLAN_MAX_NAME_LENGTH];
-    DOT11_SSID dot11Ssid;
-    DOT11_BSS_TYPE dot11BssType;
-    ULONG uNumberOfBssids;
-    BOOL bNetworkConnectable;
-    DWORD wlanNotConnectableReason;
-    ULONG uNumberOfPhyTypes;
-    DOT11_PHY_TYPE dot11PhyTypes[WLAN_MAX_PHY_TYPE_NUMBER];
-    BOOL bMorePhyTypes;
-    ULONG wlanSignalQuality;
-    BOOL bSecurityEnabled;
-    DOT11_AUTH_ALGORITHM dot11DefaultAuthAlgorithm;
-    DOT11_CIPHER_ALGORITHM dot11DefaultCipherAlgorithm;
-    DWORD dwFlags;
-    DWORD dwReserved;
-};
-
-struct WLAN_AVAILABLE_NETWORK_LIST {
-    DWORD dwNumberOfItems;
-    DWORD dwIndex;
-    WLAN_AVAILABLE_NETWORK Network[1];
-};
-
-enum WLAN_INTF_OPCODE {
-    wlan_intf_opcode_autoconf_start = 0x000000000,
-    wlan_intf_opcode_autoconf_enabled,
-    wlan_intf_opcode_background_scan_enabled,
-    wlan_intf_opcode_media_streaming_mode,
-    wlan_intf_opcode_radio_state,
-    wlan_intf_opcode_bss_type,
-    wlan_intf_opcode_interface_state,
-    wlan_intf_opcode_current_connection,
-    wlan_intf_opcode_channel_number,
-    wlan_intf_opcode_supported_infrastructure_auth_cipher_pairs,
-    wlan_intf_opcode_supported_adhoc_auth_cipher_pairs,
-    wlan_intf_opcode_supported_country_or_region_string_list,
-    wlan_intf_opcode_current_operation_mode,
-    wlan_intf_opcode_supported_safe_mode,
-    wlan_intf_opcode_certified_safe_mode,
-    wlan_intf_opcode_autoconf_end = 0x0fffffff,
-    wlan_intf_opcode_msm_start = 0x10000100,
-    wlan_intf_opcode_statistics,
-    wlan_intf_opcode_rssi,
-    wlan_intf_opcode_msm_end = 0x1fffffff,
-    wlan_intf_opcode_security_start = 0x20010000,
-    wlan_intf_opcode_security_end = 0x2fffffff,
-    wlan_intf_opcode_ihv_start = 0x30000000,
-    wlan_intf_opcode_ihv_end = 0x3fffffff
-};
-
-enum WLAN_OPCODE_VALUE_TYPE {
-    wlan_opcode_value_type_query_only = 0,
-    wlan_opcode_value_type_set_by_group_policy,
-    wlan_opcode_value_type_set_by_user,
-    wlan_opcode_value_type_invalid
-};
-
-enum WLAN_CONNECTION_MODE {
-    wlan_connection_mode_profile = 0,
-    wlan_connection_mode_temporary_profile,
-    wlan_connection_mode_discovery_secure,
-    wlan_connection_mode_discovery_unsecure,
-    wlan_connection_mode_auto,
-    wlan_connection_mode_invalid
-};
-
-struct WLAN_CONNECTION_PARAMETERS {
-    WLAN_CONNECTION_MODE wlanConnectionMode;
-    LPCWSTR strProfile;
-    DOT11_SSID *pDot11Ssid;
-    DOT11_BSSID_LIST *pDesiredBssidList;
-    DOT11_BSS_TYPE dot11BssType;
-    DWORD dwFlags;
-};
-
-struct WLAN_RAW_DATA {
-    DWORD dwDataSize;
-    BYTE DataBlob[1];
-};
-
-enum WLAN_NOTIFICATION_ACM {
-    wlan_notification_acm_start = 0,
-    wlan_notification_acm_autoconf_enabled,
-    wlan_notification_acm_autoconf_disabled,
-    wlan_notification_acm_background_scan_enabled,
-    wlan_notification_acm_background_scan_disabled,
-    wlan_notification_acm_bss_type_change,
-    wlan_notification_acm_power_setting_change,
-    wlan_notification_acm_scan_complete,
-    wlan_notification_acm_scan_fail,
-    wlan_notification_acm_connection_start,
-    wlan_notification_acm_connection_complete,
-    wlan_notification_acm_connection_attempt_fail,
-    wlan_notification_acm_filter_list_change,
-    wlan_notification_acm_interface_arrival,
-    wlan_notification_acm_interface_removal,
-    wlan_notification_acm_profile_change,
-    wlan_notification_acm_profile_name_change,
-    wlan_notification_acm_profiles_exhausted,
-    wlan_notification_acm_network_not_available,
-    wlan_notification_acm_network_available,
-    wlan_notification_acm_disconnecting,
-    wlan_notification_acm_disconnected,
-    wlan_notification_acm_adhoc_network_state_change,
-    wlan_notification_acm_end
-};
-
-struct WLAN_ASSOCIATION_ATTRIBUTES {
-    DOT11_SSID dot11Ssid;
-    DOT11_BSS_TYPE dot11BssType;
-    DOT11_MAC_ADDRESS dot11Bssid;
-    DOT11_PHY_TYPE dot11PhyType;
-    ULONG uDot11PhyIndex;
-    ULONG wlanSignalQuality;
-    ULONG ulRxRate;
-    ULONG ulTxRate;
-};
-
-struct WLAN_SECURITY_ATTRIBUTES {
-    BOOL bSecurityEnabled;
-    BOOL bOneXEnabled;
-    DOT11_AUTH_ALGORITHM dot11AuthAlgorithm;
-    DOT11_CIPHER_ALGORITHM dot11CipherAlgorithm;
-};
-
-struct WLAN_CONNECTION_ATTRIBUTES {
-    WLAN_INTERFACE_STATE isState;
-    WLAN_CONNECTION_MODE wlanConnectionMode;
-    WCHAR strProfileName[WLAN_MAX_NAME_LENGTH];
-    WLAN_ASSOCIATION_ATTRIBUTES wlanAssociationAttributes;
-    WLAN_SECURITY_ATTRIBUTES wlanSecurityAttributes;
-};
-
-typedef void (WINAPI *WLAN_NOTIFICATION_CALLBACK)(WLAN_NOTIFICATION_DATA *, PVOID);
-
-typedef DWORD (WINAPI *WlanOpenHandleProto)
-    (DWORD dwClientVersion, PVOID pReserved, PDWORD pdwNegotiatedVersion, PHANDLE phClientHandle);
-typedef DWORD (WINAPI *WlanRegisterNotificationProto)
-    (HANDLE hClientHandle, DWORD dwNotifSource, BOOL bIgnoreDuplicate,
-     WLAN_NOTIFICATION_CALLBACK funcCallback, PVOID pCallbackContext,
-     PVOID pReserved, PDWORD pdwPrevNotifSource);
-typedef DWORD (WINAPI *WlanEnumInterfacesProto)
-    (HANDLE hClientHandle, PVOID pReserved, WLAN_INTERFACE_INFO_LIST **ppInterfaceList);
-typedef DWORD (WINAPI *WlanGetAvailableNetworkListProto)
-    (HANDLE hClientHandle, const GUID* pInterfaceGuid, DWORD dwFlags, PVOID pReserved,
-     WLAN_AVAILABLE_NETWORK_LIST **ppAvailableNetworkList);
-typedef DWORD (WINAPI *WlanQueryInterfaceProto)
-    (HANDLE hClientHandle, const GUID *pInterfaceGuid, WLAN_INTF_OPCODE OpCode, PVOID pReserved,
-     PDWORD pdwDataSize, PVOID *ppData, WLAN_OPCODE_VALUE_TYPE *pWlanOpcodeValueType);
-typedef DWORD (WINAPI *WlanConnectProto)
-    (HANDLE hClientHandle, const GUID *pInterfaceGuid,
-     const WLAN_CONNECTION_PARAMETERS *pConnectionParameters, PVOID pReserved);
-typedef DWORD (WINAPI *WlanDisconnectProto)
-    (HANDLE hClientHandle, const GUID *pInterfaceGuid, PVOID pReserved);
-typedef DWORD (WINAPI *WlanScanProto)
-    (HANDLE hClientHandle, const GUID *pInterfaceGuid, const DOT11_SSID *pDot11Ssid,
-     const WLAN_RAW_DATA *pIeData, PVOID pReserved);
-typedef VOID (WINAPI *WlanFreeMemoryProto)(PVOID pMemory);
-typedef DWORD (WINAPI *WlanCloseHandleProto)(HANDLE hClientHandle, PVOID pReserved);
-
-extern WlanOpenHandleProto local_WlanOpenHandle;
-extern WlanRegisterNotificationProto local_WlanRegisterNotification;
-extern WlanEnumInterfacesProto local_WlanEnumInterfaces;
-extern WlanGetAvailableNetworkListProto local_WlanGetAvailableNetworkList;
-extern WlanQueryInterfaceProto local_WlanQueryInterface;
-extern WlanConnectProto local_WlanConnect;
-extern WlanDisconnectProto local_WlanDisconnect;
-extern WlanScanProto local_WlanScan;
-extern WlanFreeMemoryProto local_WlanFreeMemory;
-extern WlanCloseHandleProto local_WlanCloseHandle;
-
-QT_END_NAMESPACE
-
-#endif // PLATFORMDEFS_H
diff --git a/src/plugins/bearer/nativewifi/qnativewifiemain.cpp b/src/plugins/bearer/nativewifi/qnativewifiemain.cpp
deleted file mode 100644 (file)
index 2ad4663..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qnativewifiengine.h"
-#include "platformdefs.h"
-
-#include <QtCore/qsystemlibrary_p.h>
-
-#include <QtNetwork/qbearerplugin_p.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-static void resolveLibrary()
-{
-    static bool triedResolve = false;
-    if (!triedResolve) {
-        QSystemLibrary wlanapi(QLatin1String("wlanapi"));
-        if (wlanapi.load()) {
-            local_WlanOpenHandle = (WlanOpenHandleProto)
-                wlanapi.resolve("WlanOpenHandle");
-            local_WlanRegisterNotification = (WlanRegisterNotificationProto)
-                wlanapi.resolve("WlanRegisterNotification");
-            local_WlanEnumInterfaces = (WlanEnumInterfacesProto)
-                wlanapi.resolve("WlanEnumInterfaces");
-            local_WlanGetAvailableNetworkList = (WlanGetAvailableNetworkListProto)
-                wlanapi.resolve("WlanGetAvailableNetworkList");
-            local_WlanQueryInterface = (WlanQueryInterfaceProto)
-                wlanapi.resolve("WlanQueryInterface");
-            local_WlanConnect = (WlanConnectProto)
-                wlanapi.resolve("WlanConnect");
-            local_WlanDisconnect = (WlanDisconnectProto)
-                wlanapi.resolve("WlanDisconnect");
-            local_WlanScan = (WlanScanProto)
-                wlanapi.resolve("WlanScan");
-            local_WlanFreeMemory = (WlanFreeMemoryProto)
-                wlanapi.resolve("WlanFreeMemory");
-            local_WlanCloseHandle = (WlanCloseHandleProto)
-                wlanapi.resolve("WlanCloseHandle");
-        }
-        triedResolve = true;
-    }
-}
-
-class QNativeWifiEnginePlugin : public QBearerEnginePlugin
-{
-public:
-    QNativeWifiEnginePlugin();
-    ~QNativeWifiEnginePlugin();
-
-    QStringList keys() const;
-    QBearerEngine *create(const QString &key) const;
-};
-
-QNativeWifiEnginePlugin::QNativeWifiEnginePlugin()
-{
-}
-
-QNativeWifiEnginePlugin::~QNativeWifiEnginePlugin()
-{
-}
-
-QStringList QNativeWifiEnginePlugin::keys() const
-{
-    return QStringList() << QLatin1String("nativewifi");
-}
-
-QBearerEngine *QNativeWifiEnginePlugin::create(const QString &key) const
-{
-    if (key != QLatin1String("nativewifi"))
-        return 0;
-
-    resolveLibrary();
-
-    // native wifi dll not available
-    if (!local_WlanOpenHandle)
-        return 0;
-
-    QNativeWifiEngine *engine = new QNativeWifiEngine;
-
-    // could not initialise subsystem
-    if (engine && !engine->available()) {
-        delete engine;
-        return 0;
-    }
-
-    return engine;
-}
-
-Q_EXPORT_STATIC_PLUGIN(QNativeWifiEnginePlugin)
-Q_EXPORT_PLUGIN2(qnativewifibearer, QNativeWifiEnginePlugin)
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
diff --git a/src/plugins/bearer/nativewifi/qnativewifiengine.cpp b/src/plugins/bearer/nativewifi/qnativewifiengine.cpp
deleted file mode 100644 (file)
index bd01f9a..0000000
+++ /dev/null
@@ -1,623 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qnativewifiengine.h"
-#include "platformdefs.h"
-#include "../qnetworksession_impl.h"
-
-#include <QtNetwork/qnetworkconfiguration_p.h>
-
-#include <QtCore/qstringlist.h>
-#include <QtCore/qcoreapplication.h>
-
-#include <QtCore/qdebug.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-WlanOpenHandleProto local_WlanOpenHandle = 0;
-WlanRegisterNotificationProto local_WlanRegisterNotification = 0;
-WlanEnumInterfacesProto local_WlanEnumInterfaces = 0;
-WlanGetAvailableNetworkListProto local_WlanGetAvailableNetworkList = 0;
-WlanQueryInterfaceProto local_WlanQueryInterface = 0;
-WlanConnectProto local_WlanConnect = 0;
-WlanDisconnectProto local_WlanDisconnect = 0;
-WlanScanProto local_WlanScan = 0;
-WlanFreeMemoryProto local_WlanFreeMemory = 0;
-WlanCloseHandleProto local_WlanCloseHandle = 0;
-
-void qNotificationCallback(WLAN_NOTIFICATION_DATA *data, QNativeWifiEngine *d)
-{
-    Q_UNUSED(d);
-
-    if (data->NotificationSource == WLAN_NOTIFICATION_SOURCE_ACM) {
-        switch (data->NotificationCode) {
-        case wlan_notification_acm_connection_complete:
-        case wlan_notification_acm_disconnected:
-        case wlan_notification_acm_scan_complete:
-        case wlan_notification_acm_scan_fail:
-            QMetaObject::invokeMethod(d, "scanComplete", Qt::QueuedConnection);
-            break;
-        default:
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug() << "wlan acm notification" << (int)data->NotificationCode;
-#endif
-            break;
-        }
-    } else {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug() << "wlan notification source" << (int)data->NotificationSource << "code" << (int)data->NotificationCode;
-#endif
-    }
-}
-
-QNativeWifiEngine::QNativeWifiEngine(QObject *parent)
-:   QBearerEngineImpl(parent), handle(INVALID_HANDLE_VALUE)
-{
-    connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(closeHandle()));
-}
-
-QNativeWifiEngine::~QNativeWifiEngine()
-{
-    closeHandle();
-}
-
-void QNativeWifiEngine::scanComplete()
-{
-    QMutexLocker locker(&mutex);
-
-    if (!available()) {
-        locker.unlock();
-        emit updateCompleted();
-        return;
-    }
-
-    // enumerate interfaces
-    WLAN_INTERFACE_INFO_LIST *interfaceList;
-    DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList);
-    if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result);
-#endif
-
-        locker.unlock();
-        emit updateCompleted();
-
-        return;
-    }
-
-    QStringList previous = accessPointConfigurations.keys();
-
-    for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) {
-        const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i];
-
-        WLAN_AVAILABLE_NETWORK_LIST *networkList;
-        result = local_WlanGetAvailableNetworkList(handle, &interface.InterfaceGuid,
-                                                   3, 0, &networkList);
-        if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("%s: WlanGetAvailableNetworkList failed with error %ld\n",
-                   __FUNCTION__, result);
-#endif
-            continue;
-        }
-
-        QStringList seenNetworks;
-
-        for (unsigned int j = 0; j < networkList->dwNumberOfItems; ++j) {
-            WLAN_AVAILABLE_NETWORK &network = networkList->Network[j];
-
-            QString networkName;
-
-            if (network.strProfileName[0] != 0) {
-                networkName = QString::fromWCharArray(network.strProfileName);
-            } else {
-                networkName = QString::fromLatin1(reinterpret_cast<char *>(network.dot11Ssid.ucSSID));
-            }
-
-            const QString id = QString::number(qHash(QLatin1String("WLAN:") + networkName));
-
-            previous.removeAll(id);
-
-            QNetworkConfiguration::StateFlags state = QNetworkConfiguration::Undefined;
-
-            if (!(network.dwFlags & WLAN_AVAILABLE_NETWORK_HAS_PROFILE))
-                state = QNetworkConfiguration::Undefined;
-
-            if (network.strProfileName[0] != 0) {
-                if (network.bNetworkConnectable) {
-                    if (network.dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED)
-                        state = QNetworkConfiguration::Active;
-                    else
-                        state = QNetworkConfiguration::Discovered;
-                } else {
-                    state = QNetworkConfiguration::Defined;
-                }
-            }
-
-            if (seenNetworks.contains(networkName))
-                continue;
-            else
-                seenNetworks.append(networkName);
-
-            if (accessPointConfigurations.contains(id)) {
-                QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-                bool changed = false;
-
-                ptr->mutex.lock();
-
-                if (!ptr->isValid) {
-                    ptr->isValid = true;
-                    changed = true;
-                }
-
-                if (ptr->name != networkName) {
-                    ptr->name = networkName;
-                    changed = true;
-                }
-
-                if (ptr->state != state) {
-                    ptr->state = state;
-                    changed = true;
-                }
-
-                ptr->mutex.unlock();
-
-                if (changed) {
-                    locker.unlock();
-                    emit configurationChanged(ptr);
-                    locker.relock();
-                }
-            } else {
-                QNetworkConfigurationPrivatePointer ptr(new QNetworkConfigurationPrivate);
-
-                ptr->name = networkName;
-                ptr->isValid = true;
-                ptr->id = id;
-                ptr->state = state;
-                ptr->type = QNetworkConfiguration::InternetAccessPoint;
-                ptr->bearerType = QNetworkConfiguration::BearerWLAN;
-
-                accessPointConfigurations.insert(id, ptr);
-
-                locker.unlock();
-                emit configurationAdded(ptr);
-                locker.relock();
-            }
-        }
-
-        local_WlanFreeMemory(networkList);
-    }
-
-    local_WlanFreeMemory(interfaceList);
-
-    while (!previous.isEmpty()) {
-        QNetworkConfigurationPrivatePointer ptr =
-            accessPointConfigurations.take(previous.takeFirst());
-
-        locker.unlock();
-        emit configurationRemoved(ptr);
-        locker.relock();
-    }
-
-    locker.unlock();
-    emit updateCompleted();
-}
-
-QString QNativeWifiEngine::getInterfaceFromId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    if (!available())
-        return QString();
-
-    // enumerate interfaces
-    WLAN_INTERFACE_INFO_LIST *interfaceList;
-    DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList);
-    if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result);
-#endif
-        return QString();
-    }
-
-    for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) {
-        const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i];
-
-        DWORD dataSize;
-        WLAN_CONNECTION_ATTRIBUTES *connectionAttributes;
-        result = local_WlanQueryInterface(handle, &interface.InterfaceGuid,
-                                          wlan_intf_opcode_current_connection, 0, &dataSize,
-                                          reinterpret_cast<PVOID *>(&connectionAttributes), 0);
-        if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            if (result != ERROR_INVALID_STATE)
-                qDebug("%s: WlanQueryInterface failed with error %ld\n", __FUNCTION__, result);
-#endif
-
-            continue;
-        }
-
-        if (qHash(QLatin1String("WLAN:") +
-                  QString::fromWCharArray(connectionAttributes->strProfileName)) == id.toUInt()) {
-            QString guid(QLatin1String("{%1-%2-%3-%4%5-%6%7%8%9%10%11}"));
-
-            guid = guid.arg(interface.InterfaceGuid.Data1, 8, 16, QLatin1Char('0'));
-            guid = guid.arg(interface.InterfaceGuid.Data2, 4, 16, QLatin1Char('0'));
-            guid = guid.arg(interface.InterfaceGuid.Data3, 4, 16, QLatin1Char('0'));
-            for (int i = 0; i < 8; ++i)
-                guid = guid.arg(interface.InterfaceGuid.Data4[i], 2, 16, QLatin1Char('0'));
-
-            local_WlanFreeMemory(connectionAttributes);
-            local_WlanFreeMemory(interfaceList);
-
-            return guid.toUpper();
-        }
-
-        local_WlanFreeMemory(connectionAttributes);
-    }
-
-    local_WlanFreeMemory(interfaceList);
-
-    return QString();
-}
-
-bool QNativeWifiEngine::hasIdentifier(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    if (!available())
-        return false;
-
-    // enumerate interfaces
-    WLAN_INTERFACE_INFO_LIST *interfaceList;
-    DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList);
-    if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result);
-#endif
-        return false;
-    }
-
-    for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) {
-        const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i];
-
-        WLAN_AVAILABLE_NETWORK_LIST *networkList;
-        result = local_WlanGetAvailableNetworkList(handle, &interface.InterfaceGuid,
-                                                   3, 0, &networkList);
-        if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("%s: WlanGetAvailableNetworkList failed with error %ld\n",
-                   __FUNCTION__, result);
-#endif
-            continue;
-        }
-
-        for (unsigned int j = 0; j < networkList->dwNumberOfItems; ++j) {
-            WLAN_AVAILABLE_NETWORK &network = networkList->Network[j];
-
-            QString networkName;
-
-            if (network.strProfileName[0] != 0) {
-                networkName = QString::fromWCharArray(network.strProfileName);
-            } else {
-                networkName = QString::fromLatin1(reinterpret_cast<char *>(network.dot11Ssid.ucSSID));
-            }
-
-            if (qHash(QLatin1String("WLAN:") + networkName) == id.toUInt()) {
-                local_WlanFreeMemory(networkList);
-                local_WlanFreeMemory(interfaceList);
-                return true;
-            }
-        }
-
-        local_WlanFreeMemory(networkList);
-    }
-
-    local_WlanFreeMemory(interfaceList);
-
-    return false;
-}
-
-void QNativeWifiEngine::connectToId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    if (!available()) {
-        locker.unlock();
-        emit connectionError(id, InterfaceLookupError);
-        return;
-    }
-
-    WLAN_INTERFACE_INFO_LIST *interfaceList;
-    DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList);
-    if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result);
-#endif
-        locker.unlock();
-        emit connectionError(id, InterfaceLookupError);
-        return;
-    }
-
-    QString profile;
-
-    for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) {
-        const WLAN_INTERFACE_INFO &interface = interfaceList->InterfaceInfo[i];
-
-        WLAN_AVAILABLE_NETWORK_LIST *networkList;
-        result = local_WlanGetAvailableNetworkList(handle, &interface.InterfaceGuid,
-                                                   3, 0, &networkList);
-        if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("%s: WlanGetAvailableNetworkList failed with error %ld\n",
-                   __FUNCTION__, result);
-#endif
-            continue;
-        }
-
-        for (unsigned int j = 0; j < networkList->dwNumberOfItems; ++j) {
-            WLAN_AVAILABLE_NETWORK &network = networkList->Network[j];
-
-            profile = QString::fromWCharArray(network.strProfileName);
-
-            if (qHash(QLatin1String("WLAN:") + profile) == id.toUInt())
-                break;
-            else
-                profile.clear();
-        }
-
-        local_WlanFreeMemory(networkList);
-
-        if (!profile.isEmpty()) {
-            WLAN_CONNECTION_PARAMETERS parameters;
-            parameters.wlanConnectionMode = wlan_connection_mode_profile;
-            parameters.strProfile = reinterpret_cast<LPCWSTR>(profile.utf16());
-            parameters.pDot11Ssid = 0;
-            parameters.pDesiredBssidList = 0;
-            parameters.dot11BssType = dot11_BSS_type_any;
-            parameters.dwFlags = 0;
-
-            DWORD result = local_WlanConnect(handle, &interface.InterfaceGuid, &parameters, 0);
-            if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-                qDebug("%s: WlanConnect failed with error %ld\n", __FUNCTION__, result);
-#endif
-                locker.unlock();
-                emit connectionError(id, ConnectError);
-                locker.relock();
-                break;
-            }
-
-            break;
-        }
-    }
-
-    local_WlanFreeMemory(interfaceList);
-
-    if (profile.isEmpty()) {
-        locker.unlock();
-        emit connectionError(id, InterfaceLookupError);
-    }
-}
-
-void QNativeWifiEngine::disconnectFromId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    if (!available()) {
-        locker.unlock();
-        emit connectionError(id, InterfaceLookupError);
-        return;
-    }
-
-    QString interface = getInterfaceFromId(id);
-
-    if (interface.isEmpty()) {
-        locker.unlock();
-        emit connectionError(id, InterfaceLookupError);
-        return;
-    }
-
-    QStringList split = interface.mid(1, interface.length() - 2).split(QLatin1Char('-'));
-
-    GUID guid;
-    guid.Data1 = split.at(0).toUInt(0, 16);
-    guid.Data2 = split.at(1).toUShort(0, 16);
-    guid.Data3 = split.at(2).toUShort(0, 16);
-    guid.Data4[0] = split.at(3).left(2).toUShort(0, 16);
-    guid.Data4[1] = split.at(3).right(2).toUShort(0, 16);
-    for (int i = 0; i < 6; ++i)
-        guid.Data4[i + 2] = split.at(4).mid(i*2, 2).toUShort(0, 16);
-
-    DWORD result = local_WlanDisconnect(handle, &guid, 0);
-    if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: WlanDisconnect failed with error %ld\n", __FUNCTION__, result);
-#endif
-        locker.unlock();
-        emit connectionError(id, DisconnectionError);
-        return;
-    }
-}
-
-void QNativeWifiEngine::initialize()
-{
-    scanComplete();
-}
-
-void QNativeWifiEngine::requestUpdate()
-{
-    QMutexLocker locker(&mutex);
-
-    if (!available()) {
-        locker.unlock();
-        emit updateCompleted();
-        return;
-    }
-
-    // enumerate interfaces
-    WLAN_INTERFACE_INFO_LIST *interfaceList;
-    DWORD result = local_WlanEnumInterfaces(handle, 0, &interfaceList);
-    if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: WlanEnumInterfaces failed with error %ld\n", __FUNCTION__, result);
-#endif
-
-        locker.unlock();
-        emit updateCompleted();
-
-        return;
-    }
-
-    bool requested = false;
-    for (unsigned int i = 0; i < interfaceList->dwNumberOfItems; ++i) {
-        result = local_WlanScan(handle, &interfaceList->InterfaceInfo[i].InterfaceGuid, 0, 0, 0);
-        if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("%s: WlanScan failed with error %ld\n", __FUNCTION__, result);
-#endif
-        } else {
-            requested = true;
-        }
-    }
-
-    local_WlanFreeMemory(interfaceList);
-
-    if (!requested) {
-        locker.unlock();
-        emit updateCompleted();
-    }
-}
-
-QNetworkSession::State QNativeWifiEngine::sessionStateForId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-    if (!ptr)
-        return QNetworkSession::Invalid;
-
-    if (!ptr->isValid) {
-        return QNetworkSession::Invalid;
-    } else if ((ptr->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
-        return QNetworkSession::Connected;
-    } else if ((ptr->state & QNetworkConfiguration::Discovered) ==
-                QNetworkConfiguration::Discovered) {
-        return QNetworkSession::Disconnected;
-    } else if ((ptr->state & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) {
-        return QNetworkSession::NotAvailable;
-    } else if ((ptr->state & QNetworkConfiguration::Undefined) ==
-                QNetworkConfiguration::Undefined) {
-        return QNetworkSession::NotAvailable;
-    }
-
-    return QNetworkSession::Invalid;
-}
-
-QNetworkConfigurationManager::Capabilities QNativeWifiEngine::capabilities() const
-{
-    return QNetworkConfigurationManager::ForcedRoaming |
-            QNetworkConfigurationManager::CanStartAndStopInterfaces;
-}
-
-QNetworkSessionPrivate *QNativeWifiEngine::createSessionBackend()
-{
-    return new QNetworkSessionPrivateImpl;
-}
-
-QNetworkConfigurationPrivatePointer QNativeWifiEngine::defaultConfiguration()
-{
-    return QNetworkConfigurationPrivatePointer();
-}
-
-bool QNativeWifiEngine::available()
-{
-    if (handle != INVALID_HANDLE_VALUE)
-        return true;
-
-    DWORD clientVersion;
-
-    DWORD result = local_WlanOpenHandle(1, 0, &clientVersion, &handle);
-    if (result != ERROR_SUCCESS) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        if (result != ERROR_SERVICE_NOT_ACTIVE)
-            qDebug("%s: WlanOpenHandle failed with error %ld\n", __FUNCTION__, result);
-#endif
-
-        return false;
-    }
-
-    result = local_WlanRegisterNotification(handle, WLAN_NOTIFICATION_SOURCE_ALL, true,
-                                            WLAN_NOTIFICATION_CALLBACK(qNotificationCallback),
-                                            this, 0, 0);
-#ifdef BEARER_MANAGEMENT_DEBUG
-    if (result != ERROR_SUCCESS)
-        qDebug("%s: WlanRegisterNotification failed with error %ld\n", __FUNCTION__, result);
-#endif
-
-    return handle != INVALID_HANDLE_VALUE;
-}
-
-void QNativeWifiEngine::closeHandle()
-{
-    if (handle != INVALID_HANDLE_VALUE) {
-        local_WlanCloseHandle(handle, 0);
-        handle = INVALID_HANDLE_VALUE;
-    }
-}
-
-bool QNativeWifiEngine::requiresPolling() const
-{
-    // On Windows XP SP2 and SP3 only connection and disconnection notifications are available.
-    // We need to poll for changes in available wireless networks.
-    return true;
-}
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
-
-#include "moc_qnativewifiengine.h"
-#include "moc_qbearerengine_impl.h"
diff --git a/src/plugins/bearer/nativewifi/qnativewifiengine.h b/src/plugins/bearer/nativewifi/qnativewifiengine.h
deleted file mode 100644 (file)
index f883709..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QNATIVEWIFIENGINE_P_H
-#define QNATIVEWIFIENGINE_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 "../qbearerengine_impl.h"
-
-#include <QtCore/qtimer.h>
-
-#ifndef QT_NO_BEARERMANAGEMENT
-
-QT_BEGIN_NAMESPACE
-
-class QNetworkConfigurationPrivate;
-struct WLAN_NOTIFICATION_DATA;
-
-class QNativeWifiEngine : public QBearerEngineImpl
-{
-    Q_OBJECT
-
-public:
-    QNativeWifiEngine(QObject *parent = 0);
-    ~QNativeWifiEngine();
-
-    QString getInterfaceFromId(const QString &id);
-    bool hasIdentifier(const QString &id);
-
-    void connectToId(const QString &id);
-    void disconnectFromId(const QString &id);
-
-    Q_INVOKABLE void initialize();
-    Q_INVOKABLE void requestUpdate();
-
-    QNetworkSession::State sessionStateForId(const QString &id);
-
-    QNetworkConfigurationManager::Capabilities capabilities() const;
-
-    QNetworkSessionPrivate *createSessionBackend();
-
-    QNetworkConfigurationPrivatePointer defaultConfiguration();
-
-    bool available();
-
-    bool requiresPolling() const;
-
-private Q_SLOTS:
-    void scanComplete();
-    void closeHandle();
-
-private:
-    Qt::HANDLE handle;
-};
-
-QT_END_NAMESPACE
-
-#endif // QT_NO_BEARERMANAGEMENT
-
-#endif
diff --git a/src/plugins/bearer/nla/main.cpp b/src/plugins/bearer/nla/main.cpp
deleted file mode 100644 (file)
index 7ec3fc9..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qnlaengine.h"
-
-#include <QtNetwork/qbearerplugin_p.h>
-
-#include <QtCore/qdebug.h>
-
-QT_BEGIN_NAMESPACE
-
-class QNlaEnginePlugin : public QBearerEnginePlugin
-{
-public:
-    QNlaEnginePlugin();
-    ~QNlaEnginePlugin();
-
-    QStringList keys() const;
-    QBearerEngine *create(const QString &key) const;
-};
-
-QNlaEnginePlugin::QNlaEnginePlugin()
-{
-}
-
-QNlaEnginePlugin::~QNlaEnginePlugin()
-{
-}
-
-QStringList QNlaEnginePlugin::keys() const
-{
-    return QStringList() << QLatin1String("nla");
-}
-
-QBearerEngine *QNlaEnginePlugin::create(const QString &key) const
-{
-    if (key == QLatin1String("nla"))
-        return new QNlaEngine;
-    else
-        return 0;
-}
-
-Q_EXPORT_STATIC_PLUGIN(QNlaEnginePlugin)
-Q_EXPORT_PLUGIN2(qnlabearer, QNlaEnginePlugin)
-
-QT_END_NAMESPACE
diff --git a/src/plugins/bearer/nla/nla.pro b/src/plugins/bearer/nla/nla.pro
deleted file mode 100644 (file)
index 5dfb6d7..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-TARGET = qnlabearer
-include(../../qpluginbase.pri)
-
-QT = core network
-
-!wince* {
-    LIBS += -lWs2_32
-} else {
-    LIBS += -lWs2
-}
-
-HEADERS += qnlaengine.h \
-           ../platformdefs_win.h \
-           ../qnetworksession_impl.h \
-           ../qbearerengine_impl.h
-
-SOURCES += main.cpp \
-           qnlaengine.cpp \
-           ../qnetworksession_impl.cpp
-
-QTDIR_build:DESTDIR = $$QT_BUILD_TREE/plugins/bearer
-target.path += $$[QT_INSTALL_PLUGINS]/bearer
-INSTALLS += target
diff --git a/src/plugins/bearer/nla/qnlaengine.cpp b/src/plugins/bearer/nla/qnlaengine.cpp
deleted file mode 100644 (file)
index 6d471ec..0000000
+++ /dev/null
@@ -1,651 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qnlaengine.h"
-#include "../qnetworksession_impl.h"
-
-#include <QtNetwork/qnetworkconfiguration_p.h>
-
-#include <QtCore/qthread.h>
-#include <QtCore/qmutex.h>
-#include <QtCore/qcoreapplication.h>
-#include <QtCore/qstringlist.h>
-
-#include <QtCore/qdebug.h>
-
-#include "../platformdefs_win.h"
-
-QT_BEGIN_NAMESPACE
-
-QWindowsSockInit2::QWindowsSockInit2()
-:   version(0)
-{
-    //### should we try for 2.2 on all platforms ??
-    WSAData wsadata;
-
-    // IPv6 requires Winsock v2.0 or better.
-    if (WSAStartup(MAKEWORD(2,0), &wsadata) != 0) {
-        qWarning("QBearerManagementAPI: WinSock v2.0 initialization failed.");
-    } else {
-        version = 0x20;
-    }
-}
-
-QWindowsSockInit2::~QWindowsSockInit2()
-{
-    WSACleanup();
-}
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-static void printBlob(NLA_BLOB *blob)
-{
-    qDebug() << "==== BEGIN NLA_BLOB ====";
-
-    qDebug() << "type:" << blob->header.type;
-    qDebug() << "size:" << blob->header.dwSize;
-    qDebug() << "next offset:" << blob->header.nextOffset;
-
-    switch (blob->header.type) {
-    case NLA_RAW_DATA:
-        qDebug() << "Raw Data";
-        qDebug() << '\t' << blob->data.rawData;
-        break;
-    case NLA_INTERFACE:
-        qDebug() << "Interface";
-        qDebug() << "\ttype:" << blob->data.interfaceData.dwType;
-        qDebug() << "\tspeed:" << blob->data.interfaceData.dwSpeed;
-        qDebug() << "\tadapter:" << blob->data.interfaceData.adapterName;
-        break;
-    case NLA_802_1X_LOCATION:
-        qDebug() << "802.1x Location";
-        qDebug() << '\t' << blob->data.locationData.information;
-        break;
-    case NLA_CONNECTIVITY:
-        qDebug() << "Connectivity";
-        qDebug() << "\ttype:" << blob->data.connectivity.type;
-        qDebug() << "\tinternet:" << blob->data.connectivity.internet;
-        break;
-    case NLA_ICS:
-        qDebug() << "ICS";
-        qDebug() << "\tspeed:" << blob->data.ICS.remote.speed;
-        qDebug() << "\ttype:" << blob->data.ICS.remote.type;
-        qDebug() << "\tstate:" << blob->data.ICS.remote.state;
-        qDebug() << "\tmachine name:" << blob->data.ICS.remote.machineName;
-        qDebug() << "\tshared adapter name:" << blob->data.ICS.remote.sharedAdapterName;
-        break;
-    default:
-        qDebug() << "UNKNOWN BLOB TYPE";
-    }
-
-    qDebug() << "===== END NLA_BLOB =====";
-}
-#endif
-
-static QNetworkConfiguration::BearerType qGetInterfaceType(const QString &interface)
-{
-#ifdef Q_OS_WINCE
-    Q_UNUSED(interface)
-#else
-    unsigned long oid;
-    DWORD bytesWritten;
-
-    NDIS_MEDIUM medium;
-    NDIS_PHYSICAL_MEDIUM physicalMedium;
-
-    HANDLE handle = CreateFile((TCHAR *)QString::fromLatin1("\\\\.\\%1").arg(interface).utf16(), 0,
-                               FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
-    if (handle == INVALID_HANDLE_VALUE)
-        return QNetworkConfiguration::BearerUnknown;
-
-    oid = OID_GEN_MEDIA_SUPPORTED;
-    bytesWritten = 0;
-    bool result = DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS, &oid, sizeof(oid),
-                                  &medium, sizeof(medium), &bytesWritten, 0);
-    if (!result) {
-        CloseHandle(handle);
-        return QNetworkConfiguration::BearerUnknown;
-    }
-
-    oid = OID_GEN_PHYSICAL_MEDIUM;
-    bytesWritten = 0;
-    result = DeviceIoControl(handle, IOCTL_NDIS_QUERY_GLOBAL_STATS, &oid, sizeof(oid),
-                             &physicalMedium, sizeof(physicalMedium), &bytesWritten, 0);
-    if (!result) {
-        CloseHandle(handle);
-
-        if (medium == NdisMedium802_3)
-            return QNetworkConfiguration::BearerEthernet;
-        else
-            return QNetworkConfiguration::BearerUnknown;
-    }
-
-    CloseHandle(handle);
-
-    if (medium == NdisMedium802_3) {
-        switch (physicalMedium) {
-        case NdisPhysicalMediumWirelessLan:
-            return QNetworkConfiguration::BearerWLAN;
-        case NdisPhysicalMediumBluetooth:
-            return QNetworkConfiguration::BearerBluetooth;
-        case NdisPhysicalMediumWiMax:
-            return QNetworkConfiguration::BearerWiMAX;
-        default:
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug() << "Physical Medium" << physicalMedium;
-#endif
-            return QNetworkConfiguration::BearerEthernet;
-        }
-    }
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-    qDebug() << medium << physicalMedium;
-#endif
-
-#endif
-
-    return QNetworkConfiguration::BearerUnknown;
-}
-
-class QNlaThread : public QThread
-{
-    Q_OBJECT
-
-public:
-    QNlaThread(QNlaEngine *parent = 0);
-    ~QNlaThread();
-
-    QList<QNetworkConfigurationPrivate *> getConfigurations();
-
-    void forceUpdate();
-
-protected:
-    virtual void run();
-
-private:
-    void updateConfigurations(QList<QNetworkConfigurationPrivate *> &configs);
-    DWORD parseBlob(NLA_BLOB *blob, QNetworkConfigurationPrivate *cpPriv) const;
-    QNetworkConfigurationPrivate *parseQuerySet(const WSAQUERYSET *querySet) const;
-    void fetchConfigurations();
-
-signals:
-    void networksChanged();
-
-private:
-    QMutex mutex;
-    HANDLE handle;
-    bool done;
-    QList<QNetworkConfigurationPrivate *> fetchedConfigurations;
-};
-
-QNlaThread::QNlaThread(QNlaEngine *parent)
-:   QThread(parent), handle(0), done(false)
-{
-}
-
-QNlaThread::~QNlaThread()
-{
-    mutex.lock();
-
-    done = true;
-
-    if (handle) {
-        /* cancel completion event */
-        if (WSALookupServiceEnd(handle) == SOCKET_ERROR) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("WSALookupServiceEnd error %d", WSAGetLastError());
-#endif
-        }
-    }
-    mutex.unlock();
-
-    wait();
-}
-
-QList<QNetworkConfigurationPrivate *> QNlaThread::getConfigurations()
-{
-    QMutexLocker locker(&mutex);
-
-    QList<QNetworkConfigurationPrivate *> foundConfigurations = fetchedConfigurations;
-    fetchedConfigurations.clear();
-
-    return foundConfigurations;
-}
-
-void QNlaThread::forceUpdate()
-{
-    mutex.lock();
-
-    if (handle) {
-        /* cancel completion event */
-        if (WSALookupServiceEnd(handle) == SOCKET_ERROR) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("WSALookupServiceEnd error %d", WSAGetLastError());
-#endif
-        }
-        handle = 0;
-    }
-    mutex.unlock();
-}
-
-void QNlaThread::run()
-{
-    WSAEVENT changeEvent = WSACreateEvent();
-    if (changeEvent == WSA_INVALID_EVENT)
-        return;
-
-    while (true) {
-        fetchConfigurations();
-
-        WSAQUERYSET qsRestrictions;
-
-        memset(&qsRestrictions, 0, sizeof(qsRestrictions));
-        qsRestrictions.dwSize = sizeof(qsRestrictions);
-        qsRestrictions.dwNameSpace = NS_NLA;
-
-        mutex.lock();
-        if (done) {
-            mutex.unlock();
-            break;
-        }
-        int result = WSALookupServiceBegin(&qsRestrictions, LUP_RETURN_ALL, &handle);
-        mutex.unlock();
-
-        if (result == SOCKET_ERROR)
-            break;
-
-        WSACOMPLETION completion;
-        WSAOVERLAPPED overlapped;
-
-        memset(&overlapped, 0, sizeof(overlapped));
-        overlapped.hEvent = changeEvent;
-
-        memset(&completion, 0, sizeof(completion));
-        completion.Type = NSP_NOTIFY_EVENT;
-        completion.Parameters.Event.lpOverlapped = &overlapped;
-
-        DWORD bytesReturned = 0;
-        result = WSANSPIoctl(handle, SIO_NSP_NOTIFY_CHANGE, 0, 0, 0, 0,
-                             &bytesReturned, &completion);
-        if (result == SOCKET_ERROR) {
-            if (WSAGetLastError() != WSA_IO_PENDING)
-                break;
-        }
-
-#ifndef Q_OS_WINCE
-        // Not interested in unrelated IO completion events
-        // although we also don't want to block them
-        while (WaitForSingleObjectEx(changeEvent, WSA_INFINITE, true) != WAIT_IO_COMPLETION &&
-               handle)
-        {
-        }
-#else
-        WaitForSingleObject(changeEvent, WSA_INFINITE);
-#endif
-
-        mutex.lock();
-        if (handle) {
-            result = WSALookupServiceEnd(handle);
-            if (result == SOCKET_ERROR) {
-                mutex.unlock();
-                break;
-            }
-            handle = 0;
-        }
-        mutex.unlock();
-    }
-
-    WSACloseEvent(changeEvent);
-}
-
-void QNlaThread::updateConfigurations(QList<QNetworkConfigurationPrivate *> &configs)
-{
-    mutex.lock();
-
-    while (!fetchedConfigurations.isEmpty())
-        delete fetchedConfigurations.takeFirst();
-
-    fetchedConfigurations = configs;
-
-    mutex.unlock();
-
-    emit networksChanged();
-}
-
-DWORD QNlaThread::parseBlob(NLA_BLOB *blob, QNetworkConfigurationPrivate *cpPriv) const
-{
-#ifdef BEARER_MANAGEMENT_DEBUG
-    printBlob(blob);
-#endif
-
-    switch (blob->header.type) {
-    case NLA_RAW_DATA:
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: unhandled header type NLA_RAW_DATA", __FUNCTION__);
-#endif
-        break;
-    case NLA_INTERFACE:
-        cpPriv->state = QNetworkConfiguration::Active;
-        if (QNlaEngine *engine = qobject_cast<QNlaEngine *>(parent())) {
-            engine->configurationInterface[cpPriv->id.toUInt()] =
-                QString::fromLatin1(blob->data.interfaceData.adapterName);
-        }
-        break;
-    case NLA_802_1X_LOCATION:
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: unhandled header type NLA_802_1X_LOCATION", __FUNCTION__);
-#endif
-        break;
-    case NLA_CONNECTIVITY:
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: unhandled header type NLA_CONNECTIVITY", __FUNCTION__);
-#endif
-        break;
-    case NLA_ICS:
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: unhandled header type NLA_ICS", __FUNCTION__);
-#endif
-        break;
-    default:
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug("%s: unhandled header type %d", __FUNCTION__, blob->header.type);
-#endif
-        ;
-    }
-
-    return blob->header.nextOffset;
-}
-
-QNetworkConfigurationPrivate *QNlaThread::parseQuerySet(const WSAQUERYSET *querySet) const
-{
-    QNetworkConfigurationPrivate *cpPriv = new QNetworkConfigurationPrivate;
-
-    cpPriv->name = QString::fromWCharArray(querySet->lpszServiceInstanceName);
-    cpPriv->isValid = true;
-    cpPriv->id = QString::number(qHash(QLatin1String("NLA:") + cpPriv->name));
-    cpPriv->state = QNetworkConfiguration::Defined;
-    cpPriv->type = QNetworkConfiguration::InternetAccessPoint;
-
-#ifdef BEARER_MANAGEMENT_DEBUG
-    qDebug() << "size:" << querySet->dwSize;
-    qDebug() << "service instance name:" << QString::fromUtf16(querySet->lpszServiceInstanceName);
-    qDebug() << "service class id:" << querySet->lpServiceClassId;
-    qDebug() << "version:" << querySet->lpVersion;
-    qDebug() << "comment:" << QString::fromUtf16(querySet->lpszComment);
-    qDebug() << "namespace:" << querySet->dwNameSpace;
-    qDebug() << "namespace provider id:" << querySet->lpNSProviderId;
-    qDebug() << "context:" << QString::fromUtf16(querySet->lpszContext);
-    qDebug() << "number of protocols:" << querySet->dwNumberOfProtocols;
-    qDebug() << "protocols:" << querySet->lpafpProtocols;
-    qDebug() << "query string:" << QString::fromUtf16(querySet->lpszQueryString);
-    qDebug() << "number of cs addresses:" << querySet->dwNumberOfCsAddrs;
-    qDebug() << "cs addresses:" << querySet->lpcsaBuffer;
-    qDebug() << "output flags:" << querySet->dwOutputFlags;
-#endif
-
-    if (querySet->lpBlob) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-        qDebug() << "blob size:" << querySet->lpBlob->cbSize;
-        qDebug() << "blob data:" << querySet->lpBlob->pBlobData;
-#endif
-
-        DWORD offset = 0;
-        do {
-            NLA_BLOB *blob = reinterpret_cast<NLA_BLOB *>(querySet->lpBlob->pBlobData + offset);
-            DWORD nextOffset = parseBlob(blob, cpPriv);
-            if (nextOffset == offset)
-                break;
-            else
-                offset = nextOffset;
-        } while (offset != 0 && offset < querySet->lpBlob->cbSize);
-    }
-
-    if (QNlaEngine *engine = qobject_cast<QNlaEngine *>(parent())) {
-        const QString interface = engine->getInterfaceFromId(cpPriv->id);
-        cpPriv->bearerType = qGetInterfaceType(interface);
-    }
-
-    return cpPriv;
-}
-
-void QNlaThread::fetchConfigurations()
-{
-    QList<QNetworkConfigurationPrivate *> foundConfigurations;
-
-    WSAQUERYSET qsRestrictions;
-    HANDLE hLookup = 0;
-
-    memset(&qsRestrictions, 0, sizeof(qsRestrictions));
-    qsRestrictions.dwSize = sizeof(qsRestrictions);
-    qsRestrictions.dwNameSpace = NS_NLA;
-
-    int result = WSALookupServiceBegin(&qsRestrictions, LUP_RETURN_ALL | LUP_DEEP, &hLookup);
-    if (result == SOCKET_ERROR) {
-        mutex.lock();
-        fetchedConfigurations.clear();
-        mutex.unlock();
-    }
-
-    char buffer[0x10000];
-    while (result == 0) {
-        DWORD bufferLength = sizeof(buffer);
-        result = WSALookupServiceNext(hLookup, LUP_RETURN_ALL,
-                                      &bufferLength, reinterpret_cast<WSAQUERYSET *>(buffer));
-
-        if (result == SOCKET_ERROR)
-            break;
-
-        QNetworkConfigurationPrivate *cpPriv =
-            parseQuerySet(reinterpret_cast<WSAQUERYSET *>(buffer));
-
-        foundConfigurations.append(cpPriv);
-    }
-
-    if (hLookup) {
-        result = WSALookupServiceEnd(hLookup);
-        if (result == SOCKET_ERROR) {
-#ifdef BEARER_MANAGEMENT_DEBUG
-            qDebug("WSALookupServiceEnd error %d", WSAGetLastError());
-#endif
-        }
-    }
-
-    updateConfigurations(foundConfigurations);
-}
-
-QNlaEngine::QNlaEngine(QObject *parent)
-:   QBearerEngineImpl(parent), nlaThread(0)
-{
-    nlaThread = new QNlaThread(this);
-    connect(nlaThread, SIGNAL(networksChanged()),
-            this, SLOT(networksChanged()));
-    nlaThread->start();
-
-    qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
-}
-
-QNlaEngine::~QNlaEngine()
-{
-    delete nlaThread;
-}
-
-void QNlaEngine::networksChanged()
-{
-    QMutexLocker locker(&mutex);
-
-    QStringList previous = accessPointConfigurations.keys();
-
-    QList<QNetworkConfigurationPrivate *> foundConfigurations = nlaThread->getConfigurations();
-    while (!foundConfigurations.isEmpty()) {
-        QNetworkConfigurationPrivate *cpPriv = foundConfigurations.takeFirst();
-
-        previous.removeAll(cpPriv->id);
-
-        if (accessPointConfigurations.contains(cpPriv->id)) {
-            QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(cpPriv->id);
-
-            bool changed = false;
-
-            ptr->mutex.lock();
-
-            if (ptr->isValid != cpPriv->isValid) {
-                ptr->isValid = cpPriv->isValid;
-                changed = true;
-            }
-
-            if (ptr->name != cpPriv->name) {
-                ptr->name = cpPriv->name;
-                changed = true;
-            }
-
-            if (ptr->state != cpPriv->state) {
-                ptr->state = cpPriv->state;
-                changed = true;
-            }
-
-            ptr->mutex.unlock();
-
-            if (changed) {
-                locker.unlock();
-                emit configurationChanged(ptr);
-                locker.relock();
-            }
-
-            delete cpPriv;
-        } else {
-            QNetworkConfigurationPrivatePointer ptr(cpPriv);
-
-            accessPointConfigurations.insert(ptr->id, ptr);
-
-            locker.unlock();
-            emit configurationAdded(ptr);
-            locker.relock();
-        }
-    }
-
-    while (!previous.isEmpty()) {
-        QNetworkConfigurationPrivatePointer ptr =
-            accessPointConfigurations.take(previous.takeFirst());
-
-        locker.unlock();
-        emit configurationRemoved(ptr);
-        locker.relock();
-    }
-
-    locker.unlock();
-    emit updateCompleted();
-}
-
-QString QNlaEngine::getInterfaceFromId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    return configurationInterface.value(id.toUInt());
-}
-
-bool QNlaEngine::hasIdentifier(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    return configurationInterface.contains(id.toUInt());
-}
-
-void QNlaEngine::connectToId(const QString &id)
-{
-    emit connectionError(id, OperationNotSupported);
-}
-
-void QNlaEngine::disconnectFromId(const QString &id)
-{
-    emit connectionError(id, OperationNotSupported);
-}
-
-void QNlaEngine::requestUpdate()
-{
-    QMutexLocker locker(&mutex);
-
-    nlaThread->forceUpdate();
-}
-
-QNetworkSession::State QNlaEngine::sessionStateForId(const QString &id)
-{
-    QMutexLocker locker(&mutex);
-
-    QNetworkConfigurationPrivatePointer ptr = accessPointConfigurations.value(id);
-
-    if (!ptr)
-        return QNetworkSession::Invalid;
-
-    if (!ptr->isValid) {
-        return QNetworkSession::Invalid;
-    } else if ((ptr->state & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
-        return QNetworkSession::Connected;
-    } else if ((ptr->state & QNetworkConfiguration::Discovered) ==
-                QNetworkConfiguration::Discovered) {
-        return QNetworkSession::Disconnected;
-    } else if ((ptr->state & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) {
-        return QNetworkSession::NotAvailable;
-    } else if ((ptr->state & QNetworkConfiguration::Undefined) ==
-                QNetworkConfiguration::Undefined) {
-        return QNetworkSession::NotAvailable;
-    }
-
-    return QNetworkSession::Invalid;
-}
-
-QNetworkConfigurationManager::Capabilities QNlaEngine::capabilities() const
-{
-    return QNetworkConfigurationManager::ForcedRoaming;
-}
-
-QNetworkSessionPrivate *QNlaEngine::createSessionBackend()
-{
-    return new QNetworkSessionPrivateImpl;
-}
-
-QNetworkConfigurationPrivatePointer QNlaEngine::defaultConfiguration()
-{
-    return QNetworkConfigurationPrivatePointer();
-}
-
-#include "qnlaengine.moc"
-QT_END_NAMESPACE
-
-#include "moc_qnlaengine.h"
diff --git a/src/plugins/bearer/nla/qnlaengine.h b/src/plugins/bearer/nla/qnlaengine.h
deleted file mode 100644 (file)
index ac9e2ac..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QNLAENGINE_P_H
-#define QNLAENGINE_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 "../qbearerengine_impl.h"
-
-#include <QtNetwork/qnativesocketengine_p.h>
-
-#include <QMap>
-
-QT_BEGIN_NAMESPACE
-
-class QNetworkConfigurationPrivate;
-class QNlaThread;
-
-class QWindowsSockInit2
-{
-public:
-    QWindowsSockInit2();
-    ~QWindowsSockInit2();
-    int version;
-};
-
-class QNlaEngine : public QBearerEngineImpl
-{
-    Q_OBJECT
-
-    friend class QNlaThread;
-
-public:
-    QNlaEngine(QObject *parent = 0);
-    ~QNlaEngine();
-
-    QString getInterfaceFromId(const QString &id);
-    bool hasIdentifier(const QString &id);
-
-    void connectToId(const QString &id);
-    void disconnectFromId(const QString &id);
-
-    Q_INVOKABLE void requestUpdate();
-
-    QNetworkSession::State sessionStateForId(const QString &id);
-
-    QNetworkConfigurationManager::Capabilities capabilities() const;
-
-    QNetworkSessionPrivate *createSessionBackend();
-
-    QNetworkConfigurationPrivatePointer defaultConfiguration();
-
-private Q_SLOTS:
-    void networksChanged();
-
-private:
-    QWindowsSockInit2 winSock;
-    QNlaThread *nlaThread;
-    QMap<uint, QString> configurationInterface;
-};
-
-QT_END_NAMESPACE
-
-#endif
diff --git a/src/plugins/bearer/platformdefs_win.h b/src/plugins/bearer/platformdefs_win.h
deleted file mode 100644 (file)
index c0c332b..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef QPLATFORMDEFS_WIN_H
-#define QPLATFORMDEFS_WIN_H
-
-#include <winsock2.h>
-#include <mswsock.h>
-#undef interface
-#include <winioctl.h>
-
-QT_BEGIN_NAMESPACE
-
-#ifndef NS_NLA
-
-#define NS_NLA 15
-
-#ifndef NLA_NAMESPACE_GUID
-enum NLA_BLOB_DATA_TYPE {
-    NLA_RAW_DATA = 0,
-    NLA_INTERFACE = 1,
-    NLA_802_1X_LOCATION = 2,
-    NLA_CONNECTIVITY = 3,
-    NLA_ICS = 4
-};
-
-enum NLA_CONNECTIVITY_TYPE {
-    NLA_NETWORK_AD_HOC = 0,
-    NLA_NETWORK_MANAGED = 1,
-    NLA_NETWORK_UNMANAGED = 2,
-    NLA_NETWORK_UNKNOWN = 3
-};
-
-enum NLA_INTERNET {
-    NLA_INTERNET_UNKNOWN = 0,
-    NLA_INTERNET_NO = 1,
-    NLA_INTERNET_YES = 2
-};
-
-struct NLA_BLOB {
-    struct {
-        NLA_BLOB_DATA_TYPE type;
-        DWORD dwSize;
-        DWORD nextOffset;
-    } header;
-
-    union {
-        // NLA_RAW_DATA
-        CHAR rawData[1];
-
-        // NLA_INTERFACE
-        struct {
-            DWORD dwType;
-            DWORD dwSpeed;
-            CHAR adapterName[1];
-        } interfaceData;
-
-        // NLA_802_1X_LOCATION
-        struct {
-            CHAR information[1];
-        } locationData;
-
-        // NLA_CONNECTIVITY
-        struct {
-            NLA_CONNECTIVITY_TYPE type;
-            NLA_INTERNET internet;
-        } connectivity;
-
-        // NLA_ICS
-        struct {
-            struct {
-                DWORD speed;
-                DWORD type;
-                DWORD state;
-                WCHAR machineName[256];
-                WCHAR sharedAdapterName[256];
-            } remote;
-        } ICS;
-    } data;
-};
-#endif // NLA_NAMESPACE_GUID
-
-#endif
-
-enum NDIS_MEDIUM {
-    NdisMedium802_3 = 0,
-};
-
-enum NDIS_PHYSICAL_MEDIUM {
-    NdisPhysicalMediumWirelessLan = 1,
-    NdisPhysicalMediumBluetooth = 10,
-    NdisPhysicalMediumWiMax = 12,
-};
-
-#define OID_GEN_MEDIA_SUPPORTED 0x00010103
-#define OID_GEN_PHYSICAL_MEDIUM 0x00010202
-
-#define IOCTL_NDIS_QUERY_GLOBAL_STATS \
-    CTL_CODE(FILE_DEVICE_PHYSICAL_NETCARD, 0, METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
-
-QT_END_NAMESPACE
-
-#endif // QPLATFORMDEFS_WIN_H
diff --git a/src/plugins/graphicssystems/meego/dithering.cpp b/src/plugins/graphicssystems/meego/dithering.cpp
deleted file mode 100644 (file)
index bb7eab2..0000000
+++ /dev/null
@@ -1,266 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-// Implements two dithering methods:
-//
-//  * convertRGBA32_to_RGB565
-//
-// This is implemented using Ordered Bayer Dithering. The code has been adapted
-// from QX11PixmapData::fromImage. This method was originally implemented using
-// Floyd-Steinberg dithering but was later changed to Ordered Dithering because
-// of the better quality of the results.
-//
-//  * convertRGBA32_to_RGBA4444
-//
-// This is implemented using Floyd-Steinberg dithering.
-//
-// The alghorithm used here is not the fastest possible but it's prolly fast enough:
-// uses look-up tables, integer-only arthmetics and works in one pass on two lines
-// at a time. It's a high-quality dithering using 1/8 diffusion precission.
-// Each channel (RGBA) is diffused independently and alpha is dithered too.
-
-#include <string.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <math.h>
-#include <QVarLengthArray>
-
-// Gets a component (red = 1, green = 2...) from a RGBA data structure.
-// data is unsigned char. stride is the number of bytes per line.
-#define GET_RGBA_COMPONENT(data, x, y, stride, c) (data[(y * stride) + (x << 2) + c])
-
-// Writes a new pixel with r, g, b to data in 565 16bit format. Data is a short.
-#define PUT_565(data, x, y, width, r, g, b) (data[(y * width) + x] = (r << 11) | (g << 5) | b)
-
-// Writes a new pixel with r, g, b, a to data in 4444 RGBA 16bit format. Data is a short.
-#define PUT_4444(data, x, y, width, r, g, b, a) (data[(y * width) + x] = (r << 12) | (g << 8) | (b << 4) | a)
-
-// Writes(ads) a new value to the diffusion accumulator. accumulator is a short.
-// x, y is a position in the accumulation buffer. y can be 0 or 1 -- we operate on two lines at time.
-#define ACCUMULATE(accumulator, x, y, width, v) if (x < width && x >= 0) accumulator[(y * width) + x] += v
-
-// Clamps a value to be in 0..255 range.
-#define CLAMP_256(v) if (v > 255) v = 255; if (v < 0) v = 0;
-
-// Converts incoming RGB32 (QImage::Format_RGB32) to RGB565. Returns the newly allocated data.
-unsigned short* convertRGB32_to_RGB565(const unsigned char *in, int width, int height, int stride)
-{
-    static bool thresholdMapInitialized = false;
-    static int thresholdMap[16][16];
-
-    if (!thresholdMapInitialized) {
-        int i;
-        int j;
-        int n;
-
-        thresholdMap[0][0] = 0;
-        thresholdMap[1][0] = 2;
-        thresholdMap[0][1] = 3;
-        thresholdMap[1][1] = 1;
-
-        for (n=2; n<16; n*=2) {
-            for (i=0; i<n; i++) {
-                for (j=0; j<n; j++) {
-                    thresholdMap[i][j]    *= 4;
-                    thresholdMap[i+n][j]   = thresholdMap[i][j] + 2;
-                    thresholdMap[i][j+n]   = thresholdMap[i][j] + 3;
-                    thresholdMap[i+n][j+n] = thresholdMap[i][j] + 1;
-                }
-            }
-        }
-
-        thresholdMapInitialized = true;
-    }
-
-    // Output line stride. Aligned to 4 bytes.
-    int alignedWidth = width;
-    if (alignedWidth % 2 > 0)
-        alignedWidth++;
-
-    // Will store output
-    unsigned short *out = (unsigned short *)malloc (alignedWidth * height * 2);
-
-    int x;
-    int y;
-    int threshold;
-
-    // For each line...
-    for (y = 0; y < height; y++) {
-
-        // For each column....
-        for (x = 0; x < width; x++) {
-
-            int r = GET_RGBA_COMPONENT(in, x, y, stride, 0);
-            int g = GET_RGBA_COMPONENT(in, x, y, stride, 1);
-            int b = GET_RGBA_COMPONENT(in, x, y, stride, 2);
-
-            threshold = thresholdMap[x%16][y%16];
-
-            if (r <= (255-(1<<3)) && ((r<<5) & 255) > threshold) r += (1<<3);
-            if (g <= (255-(1<<2)) && ((g<<6) & 255) > threshold) g += (1<<2);
-            if (b <= (255-(1<<3)) && ((b<<5) & 255) > threshold) b += (1<<3);
-
-            // Write the newly produced pixel
-            PUT_565(out, x, y, alignedWidth, ((b >> 3) & 0x1f), ((g >> 2) & 0x3f), ((r >> 3) & 0x1f));
-        }
-    }
-
-    return out;
-}
-
-// Converts incoming RGBA32 (QImage::Format_ARGB32_Premultiplied) to RGB565. Returns the newly allocated data.
-// This function is similar (yet different) to the _565 variant but it makes sense to duplicate it here for simplicity.
-// The output has each scan line aligned to 4 bytes (as expected by GL by default).
-unsigned short* convertARGB32_to_RGBA4444(const unsigned char *in, int width, int height, int stride)
-{
-    // Output line stride. Aligned to 4 bytes.
-    int alignedWidth = width;
-    if (alignedWidth % 2 > 0)
-        alignedWidth++;
-
-    // Will store output
-    unsigned short *out = (unsigned short *) malloc(alignedWidth * 2 * height);
-
-    // Lookup tables for the 8bit => 4bit conversion
-    unsigned char lookup_8bit_to_4bit[256];
-    short lookup_8bit_to_4bit_diff[256];
-
-    // Macros for the conversion using the lookup table.
-    #define CONVERT_8BIT_TO_4BIT(v) (lookup_8bit_to_4bit[v])
-    #define DIFF_8BIT_TO_4BIT(v) (lookup_8bit_to_4bit_diff[v])
-
-    int i;
-    int x, y, c; // Pixel we're processing. c is component number (0, 1, 2, 3 for r, b, b, a)
-    short component[4]; // Stores the new components (r, g, b, a) for pixel produced during conversion
-    short diff; // The difference between the converted value and the original one. To be accumulated.
-    QVarLengthArray <short> accumulatorData(4 * width * 2); // Data for three acumulators for r, g, b. Each accumulator is two lines.
-    short *accumulator[4]; // Helper for accessing the accumulator on a per-channel basis more easily.
-    accumulator[0] = accumulatorData.data();
-    accumulator[1] = accumulatorData.data() + width;
-    accumulator[2] = accumulatorData.data() + (width * 2);
-    accumulator[3] = accumulatorData.data() + (width * 3);
-
-    // Produce the conversion lookup tables.
-    for (i = 0; i < 256; i++) {
-        lookup_8bit_to_4bit[i] = round(i / 16.0);
-        // Before bitshifts: (i * 8) - (... * 16 * 8)
-        lookup_8bit_to_4bit_diff[i] = (i << 3) - (lookup_8bit_to_4bit[i] << 7);
-
-        if (lookup_8bit_to_4bit[i] > 15)
-            lookup_8bit_to_4bit[i] = 15;
-    }
-
-    // Clear the accumulators
-    memset(accumulator[0], 0, width * 4);
-    memset(accumulator[1], 0, width * 4);
-    memset(accumulator[2], 0, width * 4);
-    memset(accumulator[3], 0, width * 4);
-
-    // For each line...
-    for (y = 0; y < height; y++) {
-
-        // For each component (r, g, b, a)...
-        memcpy(accumulator[0], accumulator[0] + width, width * 2);
-        memset(accumulator[0] + width, 0, width * 2);
-
-        memcpy(accumulator[1], accumulator[1] + width, width * 2);
-        memset(accumulator[1] + width, 0, width * 2);
-
-        memcpy(accumulator[2], accumulator[2] + width, width * 2);
-        memset(accumulator[2] + width, 0, width * 2);
-
-        memcpy(accumulator[3], accumulator[3] + width, width * 2);
-        memset(accumulator[3] + width, 0, width * 2);
-
-        // For each column....
-        for (x = 0; x < width; x++) {
-
-            // For each component (r, g, b, a)...
-            for (c = 0; c < 4; c++) {
-
-                // Get the 8bit value from the original image
-                component[c] = GET_RGBA_COMPONENT(in, x, y, stride, c);
-
-                // Add the diffusion for this pixel we stored in the accumulator.
-                // >> 7 because the values in accumulator are stored * 128
-                component[c] += accumulator[c][x] >> 7;
-
-                // Make sure we're not over the boundaries.
-                CLAMP_256(component[c]);
-
-                // Store the difference from converting 8bit => 4bit and the orig pixel.
-                // Convert 8bit => 4bit.
-                diff = DIFF_8BIT_TO_4BIT(component[c]);
-                component[c] = CONVERT_8BIT_TO_4BIT(component[c]);
-
-                // Distribute the difference according to the matrix in the
-                // accumulation bufffer.
-                ACCUMULATE(accumulator[c], x + 1, 0, width, diff * 7);
-                ACCUMULATE(accumulator[c], x - 1, 1, width, diff * 3);
-                ACCUMULATE(accumulator[c], x, 1, width, diff * 5);
-                ACCUMULATE(accumulator[c], x + 1, 1, width, diff * 1);
-            }
-
-            // Write the newly produced pixel
-            PUT_4444(out, x, y, alignedWidth, component[0], component[1], component[2], component[3]);
-        }
-    }
-
-    return out;
-}
-
-unsigned char* convertBGRA32_to_RGBA32(const unsigned char *in, int width, int height, int stride)
-{
-    unsigned char *out = (unsigned char *) malloc(stride * height);
-
-    // For each line...
-    for (int y = 0; y < height; y++) {
-        // For each column
-        for (int x = 0; x < width; x++) {
-            out[(stride * y) + (x * 4) + 0] = in[(stride * y) + (x * 4) + 2];
-            out[(stride * y) + (x * 4) + 1] = in[(stride * y) + (x * 4) + 1];
-            out[(stride * y) + (x * 4) + 2] = in[(stride * y) + (x * 4) + 0];
-            out[(stride * y) + (x * 4) + 3] = in[(stride * y) + (x * 4) + 3];
-        }
-    }
-
-    return out;
-}
diff --git a/src/plugins/graphicssystems/meego/qmeegoextensions.cpp b/src/plugins/graphicssystems/meego/qmeegoextensions.cpp
deleted file mode 100644 (file)
index a2c0f60..0000000
+++ /dev/null
@@ -1,213 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmeegoextensions.h"
-#include <qeglcontext_p.h>
-#include <qpixmapdata_gl_p.h>
-
-bool QMeeGoExtensions::initialized = false;
-bool QMeeGoExtensions::hasImageShared = false;
-bool QMeeGoExtensions::hasSurfaceScaling = false;
-bool QMeeGoExtensions::hasLockSurface = false;
-bool QMeeGoExtensions::hasFenceSync = false;
-
-/* Extension funcs */
-
-typedef EGLBoolean (EGLAPIENTRY *eglQueryImageNOKFunc)(EGLDisplay, EGLImageKHR, EGLint, EGLint*);
-typedef EGLNativeSharedImageTypeNOK (EGLAPIENTRY *eglCreateSharedImageNOKFunc)(EGLDisplay, EGLImageKHR, EGLint*);
-typedef EGLBoolean (EGLAPIENTRY *eglDestroySharedImageNOKFunc)(EGLDisplay, EGLNativeSharedImageTypeNOK);
-typedef EGLBoolean (EGLAPIENTRY *eglSetSurfaceScalingNOKFunc)(EGLDisplay, EGLSurface, EGLint, EGLint, EGLint, EGLint);
-typedef EGLBoolean (EGLAPIENTRY *eglLockSurfaceKHRFunc)(EGLDisplay, EGLSurface, const EGLint*);
-typedef EGLBoolean (EGLAPIENTRY *eglUnlockSurfaceKHRFunc)(EGLDisplay, EGLSurface);
-typedef EGLSyncKHR (EGLAPIENTRY *eglCreateSyncKHRFunc)(EGLDisplay, EGLenum, const EGLint*);
-typedef EGLBoolean (EGLAPIENTRY *eglDestroySyncKHRFunc)(EGLDisplay, EGLSyncKHR);
-typedef EGLint (EGLAPIENTRY *eglClientWaitSyncKHRFunc)(EGLDisplay, EGLSyncKHR, EGLint, EGLTimeKHR);
-typedef EGLBoolean (EGLAPIENTRY *eglGetSyncAttribKHRFunc)(EGLDisplay, EGLSyncKHR, EGLint, EGLint*);
-
-static eglQueryImageNOKFunc _eglQueryImageNOK = 0;
-static eglCreateSharedImageNOKFunc _eglCreateSharedImageNOK = 0;
-static eglDestroySharedImageNOKFunc _eglDestroySharedImageNOK = 0;
-static eglSetSurfaceScalingNOKFunc _eglSetSurfaceScalingNOK = 0;
-static eglLockSurfaceKHRFunc _eglLockSurfaceKHR = 0;
-static eglUnlockSurfaceKHRFunc _eglUnlockSurfaceKHR = 0;
-static eglCreateSyncKHRFunc _eglCreateSyncKHR = 0;
-static eglDestroySyncKHRFunc _eglDestroySyncKHR = 0;
-static eglClientWaitSyncKHRFunc _eglClientWaitSyncKHR = 0;
-static eglGetSyncAttribKHRFunc _eglGetSyncAttribKHR = 0;
-
-/* Public */
-
-void QMeeGoExtensions::ensureInitialized()
-{
-    if (!initialized)
-        initialize();
-
-    initialized = true;
-}
-
-EGLNativeSharedImageTypeNOK QMeeGoExtensions::eglCreateSharedImageNOK(EGLDisplay dpy, EGLImageKHR image, EGLint *props)
-{
-    if (!hasImageShared)
-        qFatal("EGL_NOK_image_shared not found but trying to use capability!");
-
-    return _eglCreateSharedImageNOK(dpy, image, props);
-}
-
-bool QMeeGoExtensions::eglQueryImageNOK(EGLDisplay dpy, EGLImageKHR image, EGLint prop, EGLint *v)
-{
-    if (!hasImageShared)
-        qFatal("EGL_NOK_image_shared not found but trying to use capability!");
-
-    return _eglQueryImageNOK(dpy, image, prop, v);
-}
-
-bool QMeeGoExtensions::eglDestroySharedImageNOK(EGLDisplay dpy, EGLNativeSharedImageTypeNOK img)
-{
-    if (!hasImageShared)
-        qFatal("EGL_NOK_image_shared not found but trying to use capability!");
-
-    return _eglDestroySharedImageNOK(dpy, img);
-}
-
-bool QMeeGoExtensions::eglSetSurfaceScalingNOK(EGLDisplay dpy, EGLSurface surface, int x, int y, int width, int height)
-{
-    if (!hasSurfaceScaling)
-        qFatal("EGL_NOK_surface_scaling not found but trying to use capability!");
-
-   return _eglSetSurfaceScalingNOK(dpy, surface, x, y, width, height);
-}
-
-bool QMeeGoExtensions::eglLockSurfaceKHR(EGLDisplay display, EGLSurface surface, const EGLint *attrib_list)
-{
-    if (!hasLockSurface)
-        qFatal("EGL_KHR_lock_surface2 not found but trying to use capability!");
-
-    return _eglLockSurfaceKHR(display, surface, attrib_list);
-}
-
-bool QMeeGoExtensions::eglUnlockSurfaceKHR(EGLDisplay display, EGLSurface surface)
-{
-    if (!hasLockSurface)
-        qFatal("EGL_KHR_lock_surface2 not found but trying to use capability!");
-
-    return _eglUnlockSurfaceKHR(display, surface);
-}
-
-EGLSyncKHR QMeeGoExtensions::eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list)
-{
-    if (!hasFenceSync)
-        qFatal("EGL_KHR_fence_sync not found but trying to use capability!");
-
-    return _eglCreateSyncKHR(dpy, type, attrib_list);
-}
-
-bool QMeeGoExtensions::eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync)
-{
-    if (!hasFenceSync)
-        qFatal("EGL_KHR_fence_sync not found but trying to use capability!");
-
-    return _eglDestroySyncKHR(dpy, sync);
-}
-
-EGLint QMeeGoExtensions::eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout)
-{
-    if (!hasFenceSync)
-        qFatal("EGL_KHR_fence_sync not found but trying to use capability!");
-
-    return _eglClientWaitSyncKHR(dpy, sync, flags, timeout);
-}
-
-EGLBoolean QMeeGoExtensions::eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value)
-{
-    if (!hasFenceSync)
-        qFatal("EGL_KHR_fence_sync not found but trying to use capability!");
-
-    return _eglGetSyncAttribKHR(dpy, sync, attribute, value);
-}
-
-/* Private */
-
-void QMeeGoExtensions::initialize()
-{
-    QGLContext *ctx = (QGLContext *) QGLContext::currentContext();
-    qt_resolve_eglimage_gl_extensions(ctx);
-
-    if (QEgl::hasExtension("EGL_NOK_image_shared")) {
-        qDebug("MeegoGraphics: found EGL_NOK_image_shared");
-        _eglQueryImageNOK = (eglQueryImageNOKFunc) eglGetProcAddress("eglQueryImageNOK");
-        _eglCreateSharedImageNOK = (eglCreateSharedImageNOKFunc) eglGetProcAddress("eglCreateSharedImageNOK");
-        _eglDestroySharedImageNOK = (eglDestroySharedImageNOKFunc) eglGetProcAddress("eglDestroySharedImageNOK");
-        _eglLockSurfaceKHR = (eglLockSurfaceKHRFunc) eglGetProcAddress("eglLockSurfaceKHR");
-        _eglUnlockSurfaceKHR = (eglUnlockSurfaceKHRFunc) eglGetProcAddress("eglUnlockSurfaceKHR");
-
-        Q_ASSERT(_eglQueryImageNOK && _eglCreateSharedImageNOK && _eglDestroySharedImageNOK);
-        hasImageShared = true;
-    }
-
-    if (QEgl::hasExtension("EGL_NOK_surface_scaling")) {
-        qDebug("MeegoGraphics: found EGL_NOK_surface_scaling");
-        _eglSetSurfaceScalingNOK = (eglSetSurfaceScalingNOKFunc) eglGetProcAddress("eglSetSurfaceScalingNOK");
-
-        Q_ASSERT(_eglSetSurfaceScalingNOK);
-        hasSurfaceScaling = true;
-    }
-
-    if (QEgl::hasExtension("EGL_KHR_lock_surface2")) {
-        qDebug("MeegoGraphics: found EGL_KHR_lock_surface2");
-        _eglLockSurfaceKHR = (eglLockSurfaceKHRFunc) eglGetProcAddress("eglLockSurfaceKHR");
-        _eglUnlockSurfaceKHR = (eglUnlockSurfaceKHRFunc) eglGetProcAddress("eglUnlockSurfaceKHR");
-
-        Q_ASSERT(_eglLockSurfaceKHR && _eglUnlockSurfaceKHR);
-        hasLockSurface = true;
-    }
-
-    if (QEgl::hasExtension("EGL_KHR_fence_sync")) {
-        qDebug("MeegoGraphics: found EGL_KHR_fence_sync");
-        _eglCreateSyncKHR = (eglCreateSyncKHRFunc) eglGetProcAddress("eglCreateSyncKHR");
-        _eglDestroySyncKHR = (eglDestroySyncKHRFunc) eglGetProcAddress("eglDestroySyncKHR");
-        _eglClientWaitSyncKHR = (eglClientWaitSyncKHRFunc) eglGetProcAddress("eglClientWaitSyncKHR");
-        _eglGetSyncAttribKHR = (eglGetSyncAttribKHRFunc) eglGetProcAddress("eglGetSyncAttribKHR");
-
-        Q_ASSERT(_eglCreateSyncKHR && _eglDestroySyncKHR && _eglClientWaitSyncKHR && _eglGetSyncAttribKHR);
-        hasFenceSync = true;
-    }
-}
-
diff --git a/src/plugins/graphicssystems/meego/qmeegoextensions.h b/src/plugins/graphicssystems/meego/qmeegoextensions.h
deleted file mode 100644 (file)
index 3e65e15..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MEXTENSIONS_H
-#define MEXTENSIONS_H
-
-#include <qgl_p.h>
-#include <qeglcontext_p.h>
-#include <qpixmapdata_gl_p.h>
-#include <EGL/egl.h>
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-/* Extensions decls */
-
-#ifndef EGL_SHARED_IMAGE_NOK
-#define EGL_SHARED_IMAGE_NOK 0x30DA
-typedef void* EGLNativeSharedImageTypeNOK;
-#endif
-
-#ifndef EGL_GL_TEXTURE_2D_KHR
-#define EGL_GL_TEXTURE_2D_KHR 0x30B1
-#endif
-
-#ifndef EGL_FIXED_WIDTH_NOK
-#define EGL_FIXED_WIDTH_NOK 0x30DB
-#define EGL_FIXED_HEIGHT_NOK 0x30DC
-#endif
-
-#ifndef EGL_BITMAP_POINTER_KHR
-#define EGL_BITMAP_POINTER_KHR 0x30C6
-#define EGL_BITMAP_PITCH_KHR 0x30C7
-#endif
-
-#ifndef EGL_MAP_PRESERVE_PIXELS_KHR
-#define EGL_MAP_PRESERVE_PIXELS_KHR 0x30C4
-#define EGL_LOCK_USAGE_HINT_KHR 0x30C5
-#define EGL_READ_SURFACE_BIT_KHR 0x0001
-#define EGL_WRITE_SURFACE_BIT_KHR 0x0002
-#endif
-
-#ifndef EGL_SYNC_FENCE_KHR
-#define EGL_SYNC_FENCE_KHR 0x30F9
-#define EGL_SYNC_TYPE_KHR 0x30F7
-#define EGL_SYNC_STATUS_KHR 0x30F1
-#define EGL_SYNC_CONDITION_KHR 0x30F8
-#define EGL_SIGNALED_KHR 0x30F2
-#define EGL_UNSIGNALED_KHR 0x30F3
-#define EGL_SYNC_PRIOR_COMMANDS_COMPLETE_KHR 0x30F0
-#define EGL_SYNC_FLUSH_COMMANDS_BIT_KHR 0x0001
-#define EGL_FOREVER_KHR 0xFFFFFFFFFFFFFFFFull
-#define EGL_TIMEOUT_EXPIRED_KHR 0x30F5
-#define EGL_CONDITION_SATISFIED_KHR 0x30F6
-#define EGL_NO_SYNC_KHR ((EGLSyncKHR)0)
-typedef void* EGLSyncKHR;
-typedef khronos_utime_nanoseconds_t EGLTimeKHR;
-#endif
-
-/* Class */
-
-class QMeeGoExtensions
-{
-public:
-    static void ensureInitialized();
-
-    static EGLNativeSharedImageTypeNOK eglCreateSharedImageNOK(EGLDisplay dpy, EGLImageKHR image, EGLint *props);
-    static bool eglQueryImageNOK(EGLDisplay dpy, EGLImageKHR image, EGLint prop, EGLint *v);
-    static bool eglDestroySharedImageNOK(EGLDisplay dpy, EGLNativeSharedImageTypeNOK img);
-    static bool eglSetSurfaceScalingNOK(EGLDisplay dpy, EGLSurface surface, int x, int y, int width, int height);
-    static bool eglLockSurfaceKHR(EGLDisplay display, EGLSurface surface, const EGLint *attrib_list);
-    static bool eglUnlockSurfaceKHR(EGLDisplay display, EGLSurface surface);
-    static EGLSyncKHR eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
-    static bool eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync);
-    static EGLint eglClientWaitSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout);
-    static EGLBoolean eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value);
-
-private:
-    static void initialize();
-
-    static bool initialized;
-    static bool hasImageShared;
-    static bool hasSurfaceScaling;
-    static bool hasLockSurface;
-    static bool hasFenceSync;
-};
-
-#endif
diff --git a/src/plugins/graphicssystems/meego/qmeegographicssystem.cpp b/src/plugins/graphicssystems/meego/qmeegographicssystem.cpp
deleted file mode 100644 (file)
index 3bdfbf1..0000000
+++ /dev/null
@@ -1,527 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QDebug>
-#include <qpixmap_raster_p.h>
-#include <qwindowsurface_gl_p.h>
-#include <qwindowsurface_raster_p.h>
-#include <qegl_p.h>
-#include <qglextensions_p.h>
-#include <qgl_p.h>
-#include <qimagepixmapcleanuphooks_p.h>
-#include <qapplication_p.h>
-#include <qimage_p.h>
-#include <qeglproperties_p.h>
-#include <qeglcontext_p.h>
-#include <qpixmap_x11_p.h>
-
-#include "qmeegopixmapdata.h"
-#include "qmeegolivepixmapdata.h"
-#include "qmeegographicssystem.h"
-#include "qmeegoextensions.h"
-
-#include <QTimer>
-
-bool QMeeGoGraphicsSystem::surfaceWasCreated = false;
-
-QHash <Qt::HANDLE, QPixmap*> QMeeGoGraphicsSystem::liveTexturePixmaps;
-
-QList<QMeeGoSwitchCallback> QMeeGoGraphicsSystem::switchCallbacks;
-
-QMeeGoGraphicsSystem::SwitchPolicy QMeeGoGraphicsSystem::switchPolicy = QMeeGoGraphicsSystem::AutomaticSwitch;
-
-QMeeGoGraphicsSystem::QMeeGoGraphicsSystem()
-{
-    qDebug("Using the meego graphics system");
-}
-
-QMeeGoGraphicsSystem::~QMeeGoGraphicsSystem()
-{
-    qDebug("Meego graphics system destroyed");
-    qt_destroy_gl_share_widget();
-}
-
-class QMeeGoGraphicsSystemSwitchHandler : public QObject
-{
-    Q_OBJECT
-public:
-    QMeeGoGraphicsSystemSwitchHandler();
-
-    void addWidget(QWidget *widget);
-    bool eventFilter(QObject *, QEvent *);
-
-    void handleMapNotify();
-
-private slots:
-    void removeWidget(QObject *object);
-    void switchToRaster();
-    void switchToMeeGo();
-
-private:
-    int visibleWidgets() const;
-
-private:
-    QList<QWidget *> m_widgets;
-};
-
-typedef bool(*QX11FilterFunction)(XEvent *event);
-Q_GUI_EXPORT void qt_installX11EventFilter(QX11FilterFunction func);
-
-static bool x11EventFilter(XEvent *event);
-
-QMeeGoGraphicsSystemSwitchHandler::QMeeGoGraphicsSystemSwitchHandler()
-{
-    qt_installX11EventFilter(x11EventFilter);
-}
-
-void QMeeGoGraphicsSystemSwitchHandler::addWidget(QWidget *widget)
-{
-    if (widget != qt_gl_share_widget() && !m_widgets.contains(widget)) {
-        widget->installEventFilter(this);
-        connect(widget, SIGNAL(destroyed(QObject*)), this, SLOT(removeWidget(QObject*)));
-        m_widgets << widget;
-    }
-}
-
-void QMeeGoGraphicsSystemSwitchHandler::handleMapNotify()
-{
-    if (QMeeGoGraphicsSystem::switchPolicy == QMeeGoGraphicsSystem::AutomaticSwitch && visibleWidgets() == 0)
-        QTimer::singleShot(0, this, SLOT(switchToMeeGo()));
-}
-
-void QMeeGoGraphicsSystemSwitchHandler::removeWidget(QObject *object)
-{
-    m_widgets.removeOne(static_cast<QWidget *>(object));
-    if (QMeeGoGraphicsSystem::switchPolicy == QMeeGoGraphicsSystem::AutomaticSwitch && visibleWidgets() == 0)
-        QTimer::singleShot(0, this, SLOT(switchToRaster()));
-}
-
-void QMeeGoGraphicsSystemSwitchHandler::switchToRaster()
-{
-    QMeeGoGraphicsSystem::switchToRaster();
-}
-
-void QMeeGoGraphicsSystemSwitchHandler::switchToMeeGo()
-{
-    QMeeGoGraphicsSystem::switchToMeeGo();
-}
-
-int QMeeGoGraphicsSystemSwitchHandler::visibleWidgets() const
-{
-    int count = 0;
-    for (int i = 0; i < m_widgets.size(); ++i)
-        count += m_widgets.at(i)->isVisible() && !(m_widgets.at(i)->windowState() & Qt::WindowMinimized);
-    return count;
-}
-
-bool QMeeGoGraphicsSystemSwitchHandler::eventFilter(QObject *object, QEvent *event)
-{
-    if (event->type() == QEvent::WindowStateChange
-        && QMeeGoGraphicsSystem::switchPolicy == QMeeGoGraphicsSystem::AutomaticSwitch)
-    {
-        QWindowStateChangeEvent *change = static_cast<QWindowStateChangeEvent *>(event);
-        QWidget *widget = static_cast<QWidget *>(object);
-
-        Qt::WindowStates current = widget->windowState();
-        Qt::WindowStates old = change->oldState();
-
-        // did minimized flag change?
-        if ((current ^ old) & Qt::WindowMinimized) {
-            if (current & Qt::WindowMinimized) {
-                if (visibleWidgets() == 0)
-                    QMeeGoGraphicsSystem::switchToRaster();
-            } else {
-                if (visibleWidgets() > 0)
-                    QMeeGoGraphicsSystem::switchToMeeGo();
-            }
-        }
-    } else if (event->type() == QEvent::Show
-               && QMeeGoGraphicsSystem::switchPolicy == QMeeGoGraphicsSystem::AutomaticSwitch) {
-        if (visibleWidgets() > 0)
-            QMeeGoGraphicsSystem::switchToMeeGo();
-    } else if (event->type() == QEvent::Hide
-               && QMeeGoGraphicsSystem::switchPolicy == QMeeGoGraphicsSystem::AutomaticSwitch) {
-        if (visibleWidgets() == 0)
-            QMeeGoGraphicsSystem::switchToRaster();
-    }
-
-    // resume processing of event
-    return false;
-}
-
-Q_GLOBAL_STATIC(QMeeGoGraphicsSystemSwitchHandler, switch_handler)
-
-bool x11EventFilter(XEvent *event)
-{
-    if (event->type == MapNotify)
-        switch_handler()->handleMapNotify();
-    return false;
-}
-
-QWindowSurface* QMeeGoGraphicsSystem::createWindowSurface(QWidget *widget) const
-{
-    QGLWidget *shareWidget = qt_gl_share_widget();
-
-    if (!shareWidget)
-        return new QRasterWindowSurface(widget);
-
-    QGLShareContextScope ctx(shareWidget->context());
-
-    if (QApplicationPrivate::instance()->graphics_system_name == QLatin1String("runtime"))
-        switch_handler()->addWidget(widget);
-
-    QMeeGoGraphicsSystem::surfaceWasCreated = true;
-    QWindowSurface *surface = new QGLWindowSurface(widget);
-    return surface;
-}
-
-QPixmapData *QMeeGoGraphicsSystem::createPixmapData(QPixmapData::PixelType type) const
-{
-    return new QRasterPixmapData(type);
-}
-
-QPixmapData *QMeeGoGraphicsSystem::createPixmapData(QPixmapData *origin)
-{
-    // If the pixmap is a raster type...
-    // and if the pixmap pointer matches our mapping...
-    // create a shared image instead with the given handle.
-
-    if (!origin->isNull() && origin->classId() == QPixmapData::RasterClass) {
-        QRasterPixmapData *rasterClass = static_cast <QRasterPixmapData *> (origin);
-        void *rawResource = static_cast <void *> (rasterClass->buffer()->data_ptr()->data);
-
-        if (QMeeGoPixmapData::sharedImagesMap.contains(rawResource))
-            return new QMeeGoPixmapData();
-    }
-
-    return new QRasterPixmapData(origin->pixelType());
-}
-
-void QMeeGoGraphicsSystem::setSurfaceFixedSize(int /*width*/, int /*height*/)
-{
-    if (QMeeGoGraphicsSystem::surfaceWasCreated) {
-        qWarning("Trying to set surface fixed size but surface already created!");
-        return;
-    }
-
-#ifdef QT_WAS_PATCHED
-    QEglProperties *properties = new QEglProperties();
-    properties->setValue(EGL_FIXED_WIDTH_NOK, width);
-    properties->setValue(EGL_FIXED_HEIGHT_NOK, height);
-    QGLContextPrivate::setExtraWindowSurfaceCreationProps(properties);
-#endif
-}
-
-void QMeeGoGraphicsSystem::setSurfaceScaling(int x, int y, int width, int height)
-{
-    QMeeGoExtensions::ensureInitialized();
-    QMeeGoExtensions::eglSetSurfaceScalingNOK(QEgl::display(), QEglContext::currentContext(QEgl::OpenGL)->currentSurface, x, y, width, height);
-}
-
-void QMeeGoGraphicsSystem::setTranslucent(bool translucent)
-{
-    if (QMeeGoGraphicsSystem::surfaceWasCreated) {
-        qWarning("Trying to set translucency but surface already created!");
-        return;
-    }
-
-    QGLWindowSurface::surfaceFormat.setSampleBuffers(false);
-    QGLWindowSurface::surfaceFormat.setSamples(0);
-    QGLWindowSurface::surfaceFormat.setAlpha(translucent);
-}
-
-QPixmapData *QMeeGoGraphicsSystem::pixmapDataFromEGLSharedImage(Qt::HANDLE handle, const QImage &softImage)
-{
-    if (softImage.format() != QImage::Format_ARGB32_Premultiplied &&
-        softImage.format() != QImage::Format_RGB32) {
-        qFatal("For egl shared images, the soft image has to be ARGB32_Premultiplied or RGB32");
-        return NULL;
-    }
-
-    if (QMeeGoGraphicsSystem::meeGoRunning()) {
-        QMeeGoPixmapData *pmd = new QMeeGoPixmapData;
-        pmd->fromEGLSharedImage(handle, softImage);
-        return pmd;
-    } else {
-        QRasterPixmapData *pmd = new QRasterPixmapData(QPixmapData::PixmapType);
-        pmd->fromImage(softImage, Qt::NoFormatConversion);
-
-        // Make sure that the image was not converted in any way
-        if (pmd->buffer()->data_ptr()->data !=
-            const_cast<QImage &>(softImage).data_ptr()->data)
-            qFatal("Iternal misalignment of raster data detected. Prolly a QImage copy fail.");
-
-        QMeeGoPixmapData::registerSharedImage(handle, softImage);
-        return pmd;
-    }
-}
-
-void QMeeGoGraphicsSystem::updateEGLSharedImagePixmap(QPixmap *pixmap)
-{
-    QMeeGoPixmapData *pmd = (QMeeGoPixmapData *) pixmap->pixmapData();
-
-    // Basic sanity check to make sure this is really a QMeeGoPixmapData...
-    if (pmd->classId() != QPixmapData::OpenGLClass)
-        qFatal("Trying to updated EGLSharedImage pixmap but it's not really a shared image pixmap!");
-
-    pmd->updateFromSoftImage();
-}
-
-QPixmapData *QMeeGoGraphicsSystem::pixmapDataWithGLTexture(int w, int h)
-{
-    QGLPixmapData *pmd = new QGLPixmapData(QPixmapData::PixmapType);
-    pmd->resize(w, h);
-    return pmd;
-}
-
-bool QMeeGoGraphicsSystem::meeGoRunning()
-{
-    return runningGraphicsSystemName() == "meego";
-}
-
-QPixmapData* QMeeGoGraphicsSystem::pixmapDataWithNewLiveTexture(int w, int h, QImage::Format format)
-{
-    return new QMeeGoLivePixmapData(w, h, format);
-}
-
-QPixmapData* QMeeGoGraphicsSystem::pixmapDataFromLiveTextureHandle(Qt::HANDLE handle)
-{
-    return new QMeeGoLivePixmapData(handle);
-}
-
-QImage* QMeeGoGraphicsSystem::lockLiveTexture(QPixmap* pixmap, void* fenceSync)
-{
-    QMeeGoLivePixmapData *pixmapData = static_cast<QMeeGoLivePixmapData*>(pixmap->data_ptr().data());
-    return pixmapData->lock(fenceSync);
-}
-
-bool QMeeGoGraphicsSystem::releaseLiveTexture(QPixmap *pixmap, QImage *image)
-{
-    QMeeGoLivePixmapData *pixmapData = static_cast<QMeeGoLivePixmapData*>(pixmap->data_ptr().data());
-    return pixmapData->release(image);
-}
-
-Qt::HANDLE QMeeGoGraphicsSystem::getLiveTextureHandle(QPixmap *pixmap)
-{
-    QMeeGoLivePixmapData *pixmapData = static_cast<QMeeGoLivePixmapData*>(pixmap->data_ptr().data());
-    return pixmapData->handle();
-}
-
-void* QMeeGoGraphicsSystem::createFenceSync()
-{
-    QGLShareContextScope ctx(qt_gl_share_widget()->context());
-    QMeeGoExtensions::ensureInitialized();
-    return QMeeGoExtensions::eglCreateSyncKHR(QEgl::display(), EGL_SYNC_FENCE_KHR, NULL);
-}
-
-void QMeeGoGraphicsSystem::destroyFenceSync(void *fenceSync)
-{
-    QGLShareContextScope ctx(qt_gl_share_widget()->context());
-    QMeeGoExtensions::ensureInitialized();
-    QMeeGoExtensions::eglDestroySyncKHR(QEgl::display(), fenceSync);
-}
-
-QString QMeeGoGraphicsSystem::runningGraphicsSystemName()
-{
-    if (!QApplicationPrivate::instance()) {
-        qWarning("Querying graphics system but application not running yet!");
-        return QString();
-    }
-
-    QString name = QApplicationPrivate::instance()->graphics_system_name;
-    if (name == QLatin1String("runtime")) {
-        QRuntimeGraphicsSystem *rsystem = (QRuntimeGraphicsSystem *) QApplicationPrivate::instance()->graphics_system;
-        name = rsystem->graphicsSystemName();
-    }
-
-    return name;
-}
-
-void QMeeGoGraphicsSystem::switchToMeeGo()
-{
-    if (switchPolicy == NoSwitch || meeGoRunning())
-        return;
-
-    if (QApplicationPrivate::instance()->graphics_system_name != QLatin1String("runtime"))
-        qWarning("Can't switch to meego - switching only supported with 'runtime' graphics system.");
-    else {
-        triggerSwitchCallbacks(0, "meego");
-
-        QApplication *app = static_cast<QApplication *>(QCoreApplication::instance());
-        app->setGraphicsSystem(QLatin1String("meego"));
-
-        triggerSwitchCallbacks(1, "meego");
-    }
-}
-
-void QMeeGoGraphicsSystem::switchToRaster()
-{
-    if (switchPolicy == NoSwitch || runningGraphicsSystemName() == QLatin1String("raster"))
-        return;
-
-    if (QApplicationPrivate::instance()->graphics_system_name != QLatin1String("runtime"))
-        qWarning("Can't switch to raster - switching only supported with 'runtime' graphics system.");
-    else {
-        triggerSwitchCallbacks(0, "raster");
-
-        QApplication *app = static_cast<QApplication *>(QCoreApplication::instance());
-        app->setGraphicsSystem(QLatin1String("raster"));
-
-        QMeeGoLivePixmapData::invalidateSurfaces();
-
-        triggerSwitchCallbacks(1, "raster");
-    }
-}
-
-void QMeeGoGraphicsSystem::registerSwitchCallback(QMeeGoSwitchCallback callback)
-{
-    switchCallbacks << callback;
-}
-
-void QMeeGoGraphicsSystem::triggerSwitchCallbacks(int type, const char *name)
-{
-    for (int i = 0; i < switchCallbacks.size(); ++i)
-        switchCallbacks.at(i)(type, name);
-}
-
-/* C API */
-
-int qt_meego_image_to_egl_shared_image(const QImage &image)
-{
-    return QMeeGoPixmapData::imageToEGLSharedImage(image);
-}
-
-QPixmapData* qt_meego_pixmapdata_from_egl_shared_image(Qt::HANDLE handle, const QImage &softImage)
-{
-    return QMeeGoGraphicsSystem::pixmapDataFromEGLSharedImage(handle, softImage);
-}
-
-QPixmapData* qt_meego_pixmapdata_with_gl_texture(int w, int h)
-{
-    return QMeeGoGraphicsSystem::pixmapDataWithGLTexture(w, h);
-}
-
-bool qt_meego_destroy_egl_shared_image(Qt::HANDLE handle)
-{
-    return QMeeGoPixmapData::destroyEGLSharedImage(handle);
-}
-
-void qt_meego_set_surface_fixed_size(int width, int height)
-{
-    QMeeGoGraphicsSystem::setSurfaceFixedSize(width, height);
-}
-
-void qt_meego_set_surface_scaling(int x, int y, int width, int height)
-{
-    QMeeGoGraphicsSystem::setSurfaceScaling(x, y, width, height);
-}
-
-void qt_meego_set_translucent(bool translucent)
-{
-    QMeeGoGraphicsSystem::setTranslucent(translucent);
-}
-
-void qt_meego_update_egl_shared_image_pixmap(QPixmap *pixmap)
-{
-    QMeeGoGraphicsSystem::updateEGLSharedImagePixmap(pixmap);
-}
-
-QPixmapData* qt_meego_pixmapdata_with_new_live_texture(int w, int h, QImage::Format format)
-{
-    return QMeeGoGraphicsSystem::pixmapDataWithNewLiveTexture(w, h, format);
-}
-
-QPixmapData* qt_meego_pixmapdata_from_live_texture_handle(Qt::HANDLE handle)
-{
-    return QMeeGoGraphicsSystem::pixmapDataFromLiveTextureHandle(handle);
-}
-
-QImage* qt_meego_live_texture_lock(QPixmap *pixmap, void *fenceSync)
-{
-    return QMeeGoGraphicsSystem::lockLiveTexture(pixmap, fenceSync);
-}
-
-bool qt_meego_live_texture_release(QPixmap *pixmap, QImage *image)
-{
-    return QMeeGoGraphicsSystem::releaseLiveTexture(pixmap, image);
-}
-
-Qt::HANDLE qt_meego_live_texture_get_handle(QPixmap *pixmap)
-{
-    return QMeeGoGraphicsSystem::getLiveTextureHandle(pixmap);
-}
-
-void* qt_meego_create_fence_sync(void)
-{
-    return QMeeGoGraphicsSystem::createFenceSync();
-}
-
-void qt_meego_destroy_fence_sync(void* fs)
-{
-    return QMeeGoGraphicsSystem::destroyFenceSync(fs);
-}
-
-void qt_meego_invalidate_live_surfaces(void)
-{
-    return QMeeGoLivePixmapData::invalidateSurfaces();
-}
-
-void qt_meego_switch_to_raster(void)
-{
-    QMeeGoGraphicsSystem::switchToRaster();
-}
-
-void qt_meego_switch_to_meego(void)
-{
-    QMeeGoGraphicsSystem::switchToMeeGo();
-}
-
-void qt_meego_register_switch_callback(QMeeGoSwitchCallback callback)
-{
-    QMeeGoGraphicsSystem::registerSwitchCallback(callback);
-}
-
-void qt_meego_set_switch_policy(int policy)
-{
-    QMeeGoGraphicsSystem::switchPolicy = QMeeGoGraphicsSystem::SwitchPolicy(policy);
-}
-
-#include "qmeegographicssystem.moc"
diff --git a/src/plugins/graphicssystems/meego/qmeegographicssystem.h b/src/plugins/graphicssystems/meego/qmeegographicssystem.h
deleted file mode 100644 (file)
index 6aebde8..0000000
+++ /dev/null
@@ -1,126 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MGRAPHICSSYSTEM_H
-#define MGRAPHICSSYSTEM_H
-
-#include <qgraphicssystem_p.h>
-#include <EGL/egl.h>
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-extern "C" typedef void (*QMeeGoSwitchCallback)(int type, const char *name);
-
-class QMeeGoGraphicsSystem : public QGraphicsSystem
-{
-public:
-    enum SwitchPolicy { AutomaticSwitch, ManualSwitch, NoSwitch };
-
-    QMeeGoGraphicsSystem();
-    ~QMeeGoGraphicsSystem();
-
-    virtual QWindowSurface *createWindowSurface(QWidget *widget) const;
-    virtual QPixmapData *createPixmapData(QPixmapData::PixelType) const;
-    virtual QPixmapData *createPixmapData(QPixmapData *origin);
-
-    static void setSurfaceFixedSize(int width, int height);
-    static void setSurfaceScaling(int x, int y, int width, int height);
-    static void setTranslucent(bool translucent);
-
-    static QPixmapData *pixmapDataFromEGLSharedImage(Qt::HANDLE handle, const QImage &softImage);
-    static QPixmapData *pixmapDataFromEGLImage(Qt::HANDLE handle);
-    static QPixmapData *pixmapDataWithGLTexture(int w, int h);
-    static void updateEGLSharedImagePixmap(QPixmap *pixmap);
-
-    static QPixmapData *pixmapDataWithNewLiveTexture(int w, int h, QImage::Format format);
-    static QPixmapData *pixmapDataFromLiveTextureHandle(Qt::HANDLE handle);
-    static QImage *lockLiveTexture(QPixmap* pixmap, void* fenceSync);
-    static bool releaseLiveTexture(QPixmap *pixmap, QImage *image);
-    static Qt::HANDLE getLiveTextureHandle(QPixmap *pixmap);
-
-    static void* createFenceSync();
-    static void destroyFenceSync(void* fenceSync);
-
-    static void switchToRaster();
-    static void switchToMeeGo();
-    static QString runningGraphicsSystemName();
-
-    static void registerSwitchCallback(QMeeGoSwitchCallback callback);
-
-    static SwitchPolicy switchPolicy;
-
-private:
-    static bool meeGoRunning();
-    static EGLSurface getSurfaceForLiveTexturePixmap(QPixmap *pixmap);
-    static void destroySurfaceForLiveTexturePixmap(QPixmapData* pmd);
-    static void triggerSwitchCallbacks(int type, const char *name);
-
-    static bool surfaceWasCreated;
-    static QHash<Qt::HANDLE, QPixmap*> liveTexturePixmaps;
-    static QList<QMeeGoSwitchCallback> switchCallbacks;
-};
-
-/* C api */
-
-extern "C" {
-    Q_DECL_EXPORT int qt_meego_image_to_egl_shared_image(const QImage &image);
-    Q_DECL_EXPORT QPixmapData* qt_meego_pixmapdata_from_egl_shared_image(Qt::HANDLE handle, const QImage &softImage);
-    Q_DECL_EXPORT QPixmapData* qt_meego_pixmapdata_with_gl_texture(int w, int h);
-    Q_DECL_EXPORT void qt_meego_update_egl_shared_image_pixmap(QPixmap *pixmap);
-    Q_DECL_EXPORT bool qt_meego_destroy_egl_shared_image(Qt::HANDLE handle);
-    Q_DECL_EXPORT void qt_meego_set_surface_fixed_size(int width, int height);
-    Q_DECL_EXPORT void qt_meego_set_surface_scaling(int x, int y, int width, int height);
-    Q_DECL_EXPORT void qt_meego_set_translucent(bool translucent);
-    Q_DECL_EXPORT QPixmapData* qt_meego_pixmapdata_with_new_live_texture(int w, int h, QImage::Format format);
-    Q_DECL_EXPORT QPixmapData* qt_meego_pixmapdata_from_live_texture_handle(Qt::HANDLE handle);
-    Q_DECL_EXPORT QImage* qt_meego_live_texture_lock(QPixmap *pixmap, void *fenceSync);
-    Q_DECL_EXPORT bool qt_meego_live_texture_release(QPixmap *pixmap, QImage *image);
-    Q_DECL_EXPORT Qt::HANDLE qt_meego_live_texture_get_handle(QPixmap *pixmap);
-    Q_DECL_EXPORT void* qt_meego_create_fence_sync(void);
-    Q_DECL_EXPORT void qt_meego_destroy_fence_sync(void* fs);
-    Q_DECL_EXPORT void qt_meego_invalidate_live_surfaces(void);
-    Q_DECL_EXPORT void qt_meego_switch_to_raster(void);
-    Q_DECL_EXPORT void qt_meego_switch_to_meego(void);
-    Q_DECL_EXPORT void qt_meego_register_switch_callback(QMeeGoSwitchCallback callback);
-    Q_DECL_EXPORT void qt_meego_set_switch_policy(int policy);
-}
-
-#endif 
diff --git a/src/plugins/graphicssystems/meego/qmeegographicssystemplugin.cpp b/src/plugins/graphicssystems/meego/qmeegographicssystemplugin.cpp
deleted file mode 100644 (file)
index 06606c6..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QDebug>
-#include "qmeegographicssystemplugin.h"
-#include "qmeegographicssystem.h"
-
-QStringList QMeeGoGraphicsSystemPlugin::keys() const
-{
-    QStringList list;
-    list << "meego";
-    return list;
-}
-
-QGraphicsSystem *QMeeGoGraphicsSystemPlugin::create(const QString&)
-{
-    return new QMeeGoGraphicsSystem;
-}
-
-Q_EXPORT_PLUGIN2(meego, QMeeGoGraphicsSystemPlugin)
diff --git a/src/plugins/graphicssystems/meego/qmeegographicssystemplugin.h b/src/plugins/graphicssystems/meego/qmeegographicssystemplugin.h
deleted file mode 100644 (file)
index da08dd7..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MGRAPHICSSYSTEMPLUGIN_H
-#define MGRAPHICSSYSTEMPLUGIN_H
-
-#include <qgraphicssystemplugin_p.h>
-
-class QMeeGoGraphicsSystemPlugin : public QGraphicsSystemPlugin
-{
-public:
-    virtual QStringList keys() const;
-    virtual QGraphicsSystem *create(const QString&);
-};
-
-#endif
diff --git a/src/plugins/graphicssystems/meego/qmeegolivepixmapdata.cpp b/src/plugins/graphicssystems/meego/qmeegolivepixmapdata.cpp
deleted file mode 100644 (file)
index b67348c..0000000
+++ /dev/null
@@ -1,322 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmeegolivepixmapdata.h"
-#include "qmeegorasterpixmapdata.h"
-#include <qimage_p.h>
-#include <qwindowsurface_gl_p.h>
-#include <qeglcontext_p.h>
-#include <qapplication_p.h>
-#include <qpixmap_x11_p.h>
-#include <stdio.h>
-
-static QMeeGoLivePixmapDataList all_live_pixmaps;
-
-static EGLint lock_attribs[] = {
-    EGL_MAP_PRESERVE_PIXELS_KHR, EGL_TRUE,
-    EGL_LOCK_USAGE_HINT_KHR, EGL_READ_SURFACE_BIT_KHR | EGL_WRITE_SURFACE_BIT_KHR,
-    EGL_NONE
-};
-
-static EGLint preserved_attribs[] = {
-    EGL_IMAGE_PRESERVED_KHR, EGL_TRUE,
-    EGL_NONE
-};
-
-// as copied from qwindowsurface.cpp
-void qt_scrollRectInImage(QImage &img, const QRect &rect, const QPoint &offset)
-{
-    // make sure we don't detach
-    uchar *mem = const_cast<uchar*>(const_cast<const QImage &>(img).bits());
-
-    int lineskip = img.bytesPerLine();
-    int depth = img.depth() >> 3;
-
-    const QRect imageRect(0, 0, img.width(), img.height());
-    const QRect r = rect & imageRect & imageRect.translated(-offset);
-    const QPoint p = rect.topLeft() + offset;
-
-    if (r.isEmpty())
-        return;
-
-    const uchar *src;
-    uchar *dest;
-
-    if (r.top() < p.y()) {
-        src = mem + r.bottom() * lineskip + r.left() * depth;
-        dest = mem + (p.y() + r.height() - 1) * lineskip + p.x() * depth;
-        lineskip = -lineskip;
-    } else {
-        src = mem + r.top() * lineskip + r.left() * depth;
-        dest = mem + p.y() * lineskip + p.x() * depth;
-    }
-
-    const int w = r.width();
-    int h = r.height();
-    const int bytes = w * depth;
-
-    // overlapping segments?
-    if (offset.y() == 0 && qAbs(offset.x()) < w) {
-        do {
-            ::memmove(dest, src, bytes);
-            dest += lineskip;
-            src += lineskip;
-        } while (--h);
-    } else {
-        do {
-            ::memcpy(dest, src, bytes);
-            dest += lineskip;
-            src += lineskip;
-        } while (--h);
-    }
-}
-
-/* Public */
-
-QMeeGoLivePixmapData::QMeeGoLivePixmapData(int w, int h, QImage::Format format) : QGLPixmapData(QPixmapData::PixmapType)
-{
-    QImage image(w, h, format);
-    QX11PixmapData *pmd = new QX11PixmapData(QPixmapData::PixmapType);
-    pmd->fromImage(image, Qt::NoOpaqueDetection);
-    backingX11Pixmap = new QPixmap(pmd);
-
-    initializeThroughEGLImage();
-
-    pos = all_live_pixmaps.insert(all_live_pixmaps.begin(), this);
-}
-
-QMeeGoLivePixmapData::QMeeGoLivePixmapData(Qt::HANDLE h) : QGLPixmapData(QPixmapData::PixmapType)
-{
-    backingX11Pixmap = new QPixmap(QPixmap::fromX11Pixmap(h));
-    initializeThroughEGLImage();
-
-    pos = all_live_pixmaps.insert(all_live_pixmaps.begin(), this);
-}
-
-QMeeGoLivePixmapData::~QMeeGoLivePixmapData()
-{
-    delete backingX11Pixmap;
-    all_live_pixmaps.erase(pos);
-}
-
-void QMeeGoLivePixmapData::initializeThroughEGLImage()
-{
-    if (texture()->id != 0)
-        return;
-
-    QGLShareContextScope ctx(qt_gl_share_widget()->context());
-    QMeeGoExtensions::ensureInitialized();
-
-    EGLImageKHR eglImage = EGL_NO_IMAGE_KHR;
-    GLuint newTextureId = 0;
-
-    eglImage = QEgl::eglCreateImageKHR(QEgl::display(), EGL_NO_CONTEXT, EGL_NATIVE_PIXMAP_KHR,
-                                       (EGLClientBuffer) backingX11Pixmap->handle(), preserved_attribs);
-
-    if (eglImage == EGL_NO_IMAGE_KHR) {
-        qWarning("eglCreateImageKHR failed (live texture)!");
-        return;
-    }
-
-    glGenTextures(1, &newTextureId);
-    glBindTexture(GL_TEXTURE_2D, newTextureId);
-
-    glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (EGLImageKHR) eglImage);
-    if (glGetError() == GL_NO_ERROR) {
-        resize(backingX11Pixmap->width(), backingX11Pixmap->height());
-        texture()->id = newTextureId;
-        texture()->options &= ~QGLContext::InvertedYBindOption;
-        m_hasAlpha = backingX11Pixmap->hasAlphaChannel();
-    } else {
-        qWarning("Failed to create a texture from an egl image (live texture)!");
-        glDeleteTextures(1, &newTextureId);
-    }
-
-    QEgl::eglDestroyImageKHR(QEgl::display(), eglImage);
-}
-
-QPixmapData *QMeeGoLivePixmapData::createCompatiblePixmapData() const
-{
-    qWarning("Create compatible called on live pixmap! Expect fail soon...");
-    return new QMeeGoRasterPixmapData(pixelType());
-}
-
-QImage* QMeeGoLivePixmapData::lock(EGLSyncKHR fenceSync)
-{
-    QGLShareContextScope ctx(qt_gl_share_widget()->context());
-    QMeeGoExtensions::ensureInitialized();
-
-    if (fenceSync) {
-        QMeeGoExtensions::eglClientWaitSyncKHR(QEgl::display(),
-                                               fenceSync,
-                                               EGL_SYNC_FLUSH_COMMANDS_BIT_KHR,
-                                               EGL_FOREVER_KHR);
-    }
-
-    void *data = 0;
-    int pitch = 0;
-    int surfaceWidth = 0;
-    int surfaceHeight = 0;
-    EGLSurface surface = 0;
-    QImage::Format format;
-    lockedImage = QImage();
-
-    surface = getSurfaceForBackingPixmap();
-    if (! QMeeGoExtensions::eglLockSurfaceKHR(QEgl::display(), surface, lock_attribs)) {
-        qWarning("Failed to lock surface (live texture)!");
-        return &lockedImage;
-    }
-
-    eglQuerySurface(QEgl::display(), surface, EGL_BITMAP_POINTER_KHR, (EGLint*) &data);
-    eglQuerySurface(QEgl::display(), surface, EGL_BITMAP_PITCH_KHR, (EGLint*) &pitch);
-    eglQuerySurface(QEgl::display(), surface, EGL_WIDTH, (EGLint*) &surfaceWidth);
-    eglQuerySurface(QEgl::display(), surface, EGL_HEIGHT, (EGLint*) &surfaceHeight);
-
-    // Ok, here we know we just support those two formats. Real solution would be:
-    // query also the format.
-    if (backingX11Pixmap->depth() > 16)
-        format = QImage::Format_ARGB32_Premultiplied;
-    else
-        format = QImage::Format_RGB16;
-
-    if (data == NULL || pitch == 0) {
-        qWarning("Failed to query the live texture!");
-        return &lockedImage;
-    }
-
-    if (width() != surfaceWidth || height() != surfaceHeight) {
-        qWarning("Live texture dimensions don't match!");
-        QMeeGoExtensions::eglUnlockSurfaceKHR(QEgl::display(), surface);
-        return &lockedImage;
-    }
-
-    lockedImage = QImage((uchar *) data, width(), height(), pitch, format);
-    return &lockedImage;
-}
-
-bool QMeeGoLivePixmapData::release(QImage* /*img*/)
-{
-    QGLShareContextScope ctx(qt_gl_share_widget()->context());
-    QMeeGoExtensions::ensureInitialized();
-
-    if (QMeeGoExtensions::eglUnlockSurfaceKHR(QEgl::display(), getSurfaceForBackingPixmap())) {
-        lockedImage = QImage();
-        return true;
-    } else {
-        lockedImage = QImage();
-        return false;
-    }
-}
-
-Qt::HANDLE QMeeGoLivePixmapData::handle()
-{
-    return backingX11Pixmap->handle();
-}
-
-bool QMeeGoLivePixmapData::scroll(int dx, int dy, const QRect &rect)
-{
-    lock(NULL);
-
-    if (!lockedImage.isNull())
-        qt_scrollRectInImage(lockedImage, rect, QPoint(dx, dy));
-
-    release(&lockedImage);
-    return true;
-}
-
-EGLSurface QMeeGoLivePixmapData::getSurfaceForBackingPixmap()
-{
-    initializeThroughEGLImage();
-
-    // This code is a crative remix of the stuff that can be found in the
-    // Qt's TFP implementation in /src/opengl/qgl_x11egl.cpp ::bindiTextureFromNativePixmap
-    QX11PixmapData *pixmapData = static_cast<QX11PixmapData*>(backingX11Pixmap->data_ptr().data());
-    Q_ASSERT(pixmapData->classId() == QPixmapData::X11Class);
-    bool hasAlpha = pixmapData->hasAlphaChannel();
-
-    if (pixmapData->gl_surface &&
-        hasAlpha == (pixmapData->flags & QX11PixmapData::GlSurfaceCreatedWithAlpha))
-        return pixmapData->gl_surface;
-
-    // Check to see if the surface is still valid
-    if (pixmapData->gl_surface &&
-        hasAlpha != ((pixmapData->flags & QX11PixmapData::GlSurfaceCreatedWithAlpha) > 0)) {
-        // Surface is invalid!
-        destroySurfaceForPixmapData(pixmapData);
-    }
-
-    if (pixmapData->gl_surface == 0) {
-        EGLConfig config = QEgl::defaultConfig(QInternal::Pixmap,
-                                               QEgl::OpenGL,
-                                               hasAlpha ? QEgl::Translucent : QEgl::NoOptions);
-
-        pixmapData->gl_surface = (void*)QEgl::createSurface(backingX11Pixmap, config);
-
-        if (hasAlpha)
-            pixmapData->flags |= QX11PixmapData::GlSurfaceCreatedWithAlpha;
-        else
-            pixmapData->flags &= ~QX11PixmapData::GlSurfaceCreatedWithAlpha;
-
-        if (pixmapData->gl_surface == (void*)EGL_NO_SURFACE)
-            return NULL;
-    }
-
-    return pixmapData->gl_surface;
-}
-
-void QMeeGoLivePixmapData::destroySurfaceForPixmapData(QPixmapData* pmd)
-{
-    Q_ASSERT(pmd->classId() == QPixmapData::X11Class);
-    QX11PixmapData *pixmapData = static_cast<QX11PixmapData*>(pmd);
-    if (pixmapData->gl_surface) {
-        eglDestroySurface(QEgl::display(), (EGLSurface)pixmapData->gl_surface);
-        pixmapData->gl_surface = 0;
-    }
-}
-
-void QMeeGoLivePixmapData::invalidateSurfaces()
-{
-    foreach (QMeeGoLivePixmapData *data, all_live_pixmaps) {
-        QX11PixmapData *pixmapData = static_cast<QX11PixmapData*>(data->backingX11Pixmap->data_ptr().data());
-        *data->texture() = QGLTexture();
-        pixmapData->gl_surface = 0;
-    }
-}
diff --git a/src/plugins/graphicssystems/meego/qmeegolivepixmapdata.h b/src/plugins/graphicssystems/meego/qmeegolivepixmapdata.h
deleted file mode 100644 (file)
index 5317417..0000000
+++ /dev/null
@@ -1,78 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MLIVEPIXMAPDATA_H
-#define MLIVEPIXMAPDATA_H
-
-#include <QLinkedList>
-#include <qpixmapdata_gl_p.h>
-#include "qmeegoextensions.h"
-
-class QMeeGoLivePixmapData;
-typedef QLinkedList<QMeeGoLivePixmapData *> QMeeGoLivePixmapDataList;
-
-class QMeeGoLivePixmapData : public QGLPixmapData
-{
-public:
-    QMeeGoLivePixmapData(int w, int h, QImage::Format format);
-    QMeeGoLivePixmapData(Qt::HANDLE h);
-    ~QMeeGoLivePixmapData();
-
-    QPixmapData *createCompatiblePixmapData() const;
-    bool scroll(int dx, int dy, const QRect &rect);
-
-    void initializeThroughEGLImage();
-
-    QImage* lock(EGLSyncKHR fenceSync);
-    bool release(QImage *img);
-    Qt::HANDLE handle();
-
-    EGLSurface getSurfaceForBackingPixmap();
-    void destroySurfaceForPixmapData(QPixmapData* pmd);
-
-    QPixmap *backingX11Pixmap;
-    QImage lockedImage;
-    QMeeGoLivePixmapDataList::Iterator pos;
-
-    static void invalidateSurfaces();
-};
-
-#endif
diff --git a/src/plugins/graphicssystems/meego/qmeegopixmapdata.cpp b/src/plugins/graphicssystems/meego/qmeegopixmapdata.cpp
deleted file mode 100644 (file)
index 9286f23..0000000
+++ /dev/null
@@ -1,225 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmeegopixmapdata.h"
-#include "qmeegoextensions.h"
-#include "qmeegorasterpixmapdata.h"
-#include <qimage_p.h>
-#include <qwindowsurface_gl_p.h>
-#include <qeglcontext_p.h>
-#include <qapplication_p.h>
-
-// from dithering.cpp
-extern unsigned short* convertRGB32_to_RGB565(const unsigned char *in, int width, int height, int stride);
-extern unsigned short* convertARGB32_to_RGBA4444(const unsigned char *in, int width, int height, int stride);
-extern unsigned char* convertBGRA32_to_RGBA32(const unsigned char *in, int width, int height, int stride);
-
-static EGLint preserved_image_attribs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE };
-
-QHash <void*, QMeeGoImageInfo*> QMeeGoPixmapData::sharedImagesMap;
-
-/* Public */
-
-QMeeGoPixmapData::QMeeGoPixmapData() : QGLPixmapData(QPixmapData::PixmapType)
-{
-}
-
-void QMeeGoPixmapData::fromTexture(GLuint textureId, int w, int h, bool alpha)
-{
-    resize(w, h); 
-    texture()->id = textureId;
-    m_hasAlpha = alpha;
-    softImage = QImage();
-}
-
-QImage QMeeGoPixmapData::toImage() const
-{
-    return softImage;
-}
-
-void QMeeGoPixmapData::fromImage(const QImage &image,
-                                 Qt::ImageConversionFlags flags)
-{
-    void *rawResource = static_cast <void *> (((QImage &) image).data_ptr()->data);
-
-    if (sharedImagesMap.contains(rawResource)) {
-        QMeeGoImageInfo *info = sharedImagesMap.value(rawResource);
-        fromEGLSharedImage(info->handle, image);
-    } else {
-        // This should *never* happen since the graphics system should never
-        // create a QMeeGoPixmapData for an origin that doesn't contain a raster
-        // image we know about. But...
-        qWarning("QMeeGoPixmapData::fromImage called on non-know resource. Falling back...");
-        QGLPixmapData::fromImage(image, flags);
-    }
-}
-
-void QMeeGoPixmapData::fromEGLSharedImage(Qt::HANDLE handle, const QImage &si)
-{
-    if (si.isNull())
-        qFatal("Trying to build pixmap with an empty/null softimage!");
-        
-    QGLShareContextScope ctx(qt_gl_share_widget()->context());
-   
-    QMeeGoExtensions::ensureInitialized();
-    bool textureIsBound = false;
-    GLuint newTextureId;
-    GLint newWidth, newHeight;
-
-    glGenTextures(1, &newTextureId);
-    glBindTexture(GL_TEXTURE_2D, newTextureId);
-    
-    EGLImageKHR image = QEgl::eglCreateImageKHR(QEgl::display(), EGL_NO_CONTEXT, EGL_SHARED_IMAGE_NOK,
-                                                (EGLClientBuffer)handle, preserved_image_attribs);
-
-    if (image != EGL_NO_IMAGE_KHR) {
-        glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image);
-        GLint err = glGetError();
-        if (err == GL_NO_ERROR)
-            textureIsBound = true;
-        
-        QMeeGoExtensions::eglQueryImageNOK(QEgl::display(), image, EGL_WIDTH, &newWidth);
-        QMeeGoExtensions::eglQueryImageNOK(QEgl::display(), image, EGL_HEIGHT, &newHeight);
-          
-        QEgl::eglDestroyImageKHR(QEgl::display(), image);
-    }
-        
-    if (textureIsBound) {
-        fromTexture(newTextureId, newWidth, newHeight, 
-                    (si.hasAlphaChannel() && const_cast<QImage &>(si).data_ptr()->checkForAlphaPixels()));
-        texture()->options &= ~QGLContext::InvertedYBindOption;
-        softImage = si;
-        QMeeGoPixmapData::registerSharedImage(handle, softImage);
-    } else {
-        qWarning("Failed to create a texture from a shared image!");
-        glDeleteTextures(1, &newTextureId);
-    }
-}
-
-Qt::HANDLE QMeeGoPixmapData::imageToEGLSharedImage(const QImage &image)
-{
-    QGLShareContextScope ctx(qt_gl_share_widget()->context());
-
-    QMeeGoExtensions::ensureInitialized();
-
-    GLuint textureId;
-
-    glGenTextures(1, &textureId);
-    glBindTexture(GL_TEXTURE_2D, textureId);
-    if (image.hasAlphaChannel() && const_cast<QImage &>(image).data_ptr()->checkForAlphaPixels()) {
-        void *converted = convertBGRA32_to_RGBA32(image.bits(), image.width(), image.height(), image.bytesPerLine());
-        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, converted);
-        free(converted);
-    } else {
-        void *converted = convertRGB32_to_RGB565(image.bits(), image.width(), image.height(), image.bytesPerLine());
-        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width(), image.height(), 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, converted);
-        free(converted);
-    }
-
-    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
-    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_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);
-
-    EGLImageKHR eglimage = QEgl::eglCreateImageKHR(QEgl::display(), QEglContext::currentContext(QEgl::OpenGL)->context(),
-                                                                                                EGL_GL_TEXTURE_2D_KHR,
-                                                                                                (EGLClientBuffer) textureId,
-                                                                                                preserved_image_attribs);
-    glDeleteTextures(1, &textureId);
-    if (eglimage) {
-        EGLNativeSharedImageTypeNOK handle = QMeeGoExtensions::eglCreateSharedImageNOK(QEgl::display(), eglimage, NULL);
-        QEgl::eglDestroyImageKHR(QEgl::display(), eglimage);
-        return (Qt::HANDLE) handle;
-    } else {
-        qWarning("Failed to create shared image from pixmap/texture!");
-        return 0;
-    }
-}
-
-void QMeeGoPixmapData::updateFromSoftImage()
-{
-    // FIXME That's broken with recent 16bit textures changes.
-    m_dirty = true;
-    m_source = softImage;
-    ensureCreated();
-    
-    if (softImage.width() != w || softImage.height() != h)
-        qWarning("Ooops, looks like softImage changed dimensions since last updated! Corruption ahead?!");
-}
-
-bool QMeeGoPixmapData::destroyEGLSharedImage(Qt::HANDLE h)
-{
-    QGLShareContextScope ctx(qt_gl_share_widget()->context());   
-    QMeeGoExtensions::ensureInitialized();
-
-    QMutableHashIterator <void*, QMeeGoImageInfo*> i(sharedImagesMap);
-    while (i.hasNext()) {
-        i.next();
-        if (i.value()->handle == h)
-            i.remove();
-    }
-
-    return QMeeGoExtensions::eglDestroySharedImageNOK(QEgl::display(), (EGLNativeSharedImageTypeNOK) h);
-}
-
-void QMeeGoPixmapData::registerSharedImage(Qt::HANDLE handle, const QImage &si)
-{
-    void *raw = static_cast <void *> (((QImage) si).data_ptr()->data);
-    QMeeGoImageInfo *info;
-    
-    if (! sharedImagesMap.contains(raw)) {
-        info = new QMeeGoImageInfo;
-        info->handle = handle;
-        info->rawFormat = si.format();
-        sharedImagesMap.insert(raw, info);
-    } else {
-        info = sharedImagesMap.value(raw);
-        if (info->handle != handle || info->rawFormat != si.format())
-            qWarning("Inconsistency detected: overwriting entry in sharedImagesMap but handle/format different");
-    }
-}
-
-QPixmapData *QMeeGoPixmapData::createCompatiblePixmapData() const
-{
-    return new QMeeGoRasterPixmapData(pixelType());
-}
diff --git a/src/plugins/graphicssystems/meego/qmeegopixmapdata.h b/src/plugins/graphicssystems/meego/qmeegopixmapdata.h
deleted file mode 100644 (file)
index a685f2b..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MPIXMAPDATA_H
-#define MPIXMAPDATA_H
-
-#include <qpixmapdata_gl_p.h>
-
-struct QMeeGoImageInfo
-{
-    Qt::HANDLE handle;
-    QImage::Format rawFormat;
-};
-
-class QMeeGoPixmapData : public QGLPixmapData
-{
-public:
-    QMeeGoPixmapData();
-    void fromTexture(GLuint textureId, int w, int h, bool alpha);
-    QPixmapData *createCompatiblePixmapData() const;
-
-    virtual void fromEGLSharedImage(Qt::HANDLE handle, const QImage &softImage);
-    virtual void fromImage (const QImage &image, Qt::ImageConversionFlags flags);
-    virtual QImage toImage() const;
-    virtual void updateFromSoftImage();
-
-    QImage softImage;
-
-    static QHash <void*, QMeeGoImageInfo*> sharedImagesMap;
-
-    static Qt::HANDLE imageToEGLSharedImage(const QImage &image);
-    static bool destroyEGLSharedImage(Qt::HANDLE h);
-    static void registerSharedImage(Qt::HANDLE handle, const QImage &si);
-};
-
-#endif
diff --git a/src/plugins/graphicssystems/meego/qmeegorasterpixmapdata.cpp b/src/plugins/graphicssystems/meego/qmeegorasterpixmapdata.cpp
deleted file mode 100644 (file)
index 4c2d19b..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qmeegorasterpixmapdata.h"
-
-/* Public */
-
-QMeeGoRasterPixmapData::QMeeGoRasterPixmapData() : QRasterPixmapData(QPixmapData::PixmapType)
-{
-}
-
-QMeeGoRasterPixmapData::QMeeGoRasterPixmapData(QPixmapData::PixelType t) : QRasterPixmapData(t)
-{
-}
-
-void QMeeGoRasterPixmapData::copy(const QPixmapData *data, const QRect &rect)
-{
-    if (data->classId() == QPixmapData::OpenGLClass)
-        fromImage(data->toImage(rect).copy(), Qt::NoOpaqueDetection);
-    else
-        QRasterPixmapData::copy(data, rect);
-}
diff --git a/src/plugins/graphicssystems/meego/qmeegorasterpixmapdata.h b/src/plugins/graphicssystems/meego/qmeegorasterpixmapdata.h
deleted file mode 100644 (file)
index ce734e5..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MRASTERPIXMAPDATA_H
-#define MRASTERPIXMAPDATA_H
-
-#include <qpixmap_raster_p.h>
-
-class QMeeGoRasterPixmapData : public QRasterPixmapData
-{
-public:
-    QMeeGoRasterPixmapData();
-    QMeeGoRasterPixmapData(QPixmapData::PixelType t);
-    void copy(const QPixmapData *data, const QRect &rect);
-};
-
-#endif
diff --git a/src/tools/designer/Info_mac.plist b/src/tools/designer/Info_mac.plist
deleted file mode 100644 (file)
index b354932..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
-<plist version="0.9">
-<dict>
-        <key>CFBundleIconFile</key>
-        <string>@ICON@</string>
-        <key>CFBundlePackageType</key>
-        <string>APPL</string>
-        <key>CFBundleGetInfoString</key>
-        <string>Created by Qt/QMake</string>
-        <key>CFBundleIdentifier</key>
-        <string>com.trolltech.Designer</string>
-        <key>CFBundleSignature</key>
-        <string>ttxt</string>
-        <key>CFBundleExecutable</key>
-        <string>@EXECUTABLE@</string>
-        <key>CFBundleDocumentTypes</key>
-        <array>
-                <dict>
-                        <key>CFBundleTypeExtensions</key>
-                        <array>
-                                <string>ui</string>
-                        </array>
-                        <key>CFBundleTypeIconFile</key>
-                        <string>uifile.icns</string>
-                        <key>CFBundleTypeRole</key>
-                        <string>Editor</string>
-                        <key>LSIsAppleDefaultForType</key>
-                        <true/>
-                </dict>
-        </array>
-        <key>NOTE</key>
-        <string>Qt/Designer by The Qt Company Ltd</string>
-</dict>
-</plist>
diff --git a/src/tools/designer/designer.pro b/src/tools/designer/designer.pro
deleted file mode 100644 (file)
index 9c59b67..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-win32 {
-   RC_FILE      = designer.rc
-}
-
-mac {
-    ICON = designer.icns
-    QMAKE_INFO_PLIST = Info_mac.plist
-    TARGET = Designer
-    FILETYPES.files = uifile.icns
-    FILETYPES.path = Contents/Resources
-    QMAKE_BUNDLE_DATA += FILETYPES
-}
-
diff --git a/src/tools/designer/designer.rc b/src/tools/designer/designer.rc
deleted file mode 100644 (file)
index e43943a..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-#include "winver.h"
-
-IDI_ICON1               ICON    DISCARDABLE     "designer.ico"
-
-VS_VERSION_INFO VERSIONINFO
- FILEVERSION 1,0,0,0
- PRODUCTVERSION 1,0,0,0
- FILEFLAGS 0x0L
- FILEFLAGSMASK 0x3fL
- FILEOS 0x00040004L
- FILETYPE 0x1L
- FILESUBTYPE 0x0L
-BEGIN
-    BLOCK "StringFileInfo"
-    BEGIN
-        BLOCK "000004b0"
-        BEGIN
-            VALUE "CompanyName", "The Qt Company Ltd"
-            VALUE "FileDescription", "Qt Designer"
-            VALUE "FileVersion", "1.0.0.0"
-            VALUE "LegalCopyright", "Copyright (C) 2015 The Qt Company Ltd."
-            VALUE "InternalName", "designer"
-            VALUE "OriginalFilename", "designer.exe"
-            VALUE "ProductName", "Qt Designer"
-            VALUE "ProductVersion", "1.0.0.0"
-        END
-    END
-    BLOCK "VarFileInfo"
-    BEGIN
-        VALUE "Translation", 0x0, 1200
-    END
-END
diff --git a/src/tools/idc/main.cpp b/src/tools/idc/main.cpp
deleted file mode 100644 (file)
index fd9ebf5..0000000
+++ /dev/null
@@ -1,385 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the tools applications 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include <QFile>
-#include <QDir>
-#include <QScopedArrayPointer>
-#include <qt_windows.h>
-#include <io.h>
-
-QT_BEGIN_NAMESPACE
-
-static QString quotePath(const QString &s)
-{
-    if (!s.startsWith(QLatin1Char('\"')) && s.contains(QLatin1Char(' ')))
-        return QLatin1Char('\"') + s + QLatin1Char('\"');
-    return s;
-}
-
-// Prepend the Qt binary directory to PATH.
-static bool prependPath()
-{
-    enum { maxEnvironmentSize = 32767 };
-    wchar_t buffer[maxEnvironmentSize];
-    if (!GetModuleFileName(NULL, buffer, maxEnvironmentSize))
-        return false;
-    wchar_t *ptr = wcsrchr(buffer, L'\\');
-    if (!ptr)
-        return false;
-    *ptr++ = L';';
-    const wchar_t pathVariable[] = L"PATH";
-    if (!GetEnvironmentVariable(pathVariable, ptr, maxEnvironmentSize - (ptr - buffer))
-        || !SetEnvironmentVariable(pathVariable, buffer)) {
-        return false;
-    }
-    return true;
-}
-
-static QString errorString(DWORD errorCode)
-{
-    wchar_t *resultW = 0;
-    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
-                  NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                  (LPWSTR)&resultW, 0, NULL);
-    const QString result = QString::fromWCharArray(resultW);
-    LocalFree((HLOCAL)resultW);
-    return result;
-}
-
-static bool runWithQtInEnvironment(const QString &cmd)
-{
-    enum { timeOutMs = 30000 };
-    static const bool pathSet = prependPath();
-    if (!pathSet)
-        return false;
-
-    STARTUPINFO si;
-    ZeroMemory(&si, sizeof(si));
-    si.cb = sizeof(si);
-
-    STARTUPINFO myInfo;
-    GetStartupInfo(&myInfo);
-    si.hStdInput = myInfo.hStdInput;
-    si.hStdOutput = myInfo.hStdOutput;
-    si.hStdError = myInfo.hStdError;
-
-    PROCESS_INFORMATION pi;
-    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
-
-    QScopedArrayPointer<wchar_t> commandLineW(new wchar_t[cmd.size() + 1]);
-    cmd.toWCharArray(commandLineW.data());
-    commandLineW[cmd.size()] = 0;
-    if (!CreateProcessW(0, commandLineW.data(), 0, 0, /* InheritHandles */ TRUE, 0, 0, 0, &si, &pi)) {
-        fprintf(stderr, "Unable to execute \"%s\": %s\n", qPrintable(cmd),
-                qPrintable(errorString(GetLastError())));
-        return false;
-    }
-
-    DWORD exitCode = 1;
-    switch (WaitForSingleObject(pi.hProcess, timeOutMs)) {
-    case WAIT_OBJECT_0:
-        GetExitCodeProcess(pi.hProcess, &exitCode);
-        break;
-    case WAIT_TIMEOUT:
-        fprintf(stderr, "Timed out after %d ms out waiting for \"%s\".\n",
-                int(timeOutMs), qPrintable(cmd));
-        TerminateProcess(pi.hProcess, 1);
-        break;
-    default:
-        fprintf(stderr, "Error waiting for \"%s\": %s\n",
-                qPrintable(cmd), qPrintable(errorString(GetLastError())));
-        TerminateProcess(pi.hProcess, 1);
-        break;
-    }
-    CloseHandle(pi.hThread);
-    CloseHandle(pi.hProcess);
-    return exitCode == 0;
-}
-
-static bool attachTypeLibrary(const QString &applicationName, int resource, const QByteArray &data, QString *errorMessage)
-{
-    HANDLE hExe = BeginUpdateResource((const wchar_t *)applicationName.utf16(), false);
-    if (hExe == 0) {
-        if (errorMessage)
-            *errorMessage = QString::fromLatin1("Failed to attach type library to binary %1 - could not open file.").arg(applicationName);
-        return false;
-    }
-    if (!UpdateResource(hExe, L"TYPELIB", MAKEINTRESOURCE(resource), 0, (void*)data.data(), data.count())) {
-        EndUpdateResource(hExe, true);
-        if (errorMessage)
-            *errorMessage = QString::fromLatin1("Failed to attach type library to binary %1 - could not update file.").arg(applicationName);
-        return false;
-    }
-
-    if (!EndUpdateResource(hExe,false)) {
-        if (errorMessage)
-            *errorMessage = QString::fromLatin1("Failed to attach type library to binary %1 - could not write file.").arg(applicationName);
-        return false;
-    }
-    
-    if (errorMessage)
-        *errorMessage = QString::fromLatin1("Type library attached to %1.").arg(applicationName);
-    return true;
-}
-
-static bool registerServer(const QString &input)
-{
-    bool ok = false;    
-    if (input.endsWith(QLatin1String(".exe"))) {
-        ok = runWithQtInEnvironment(quotePath(input) + QLatin1String(" -regserver"));
-    } else {
-        HMODULE hdll = LoadLibrary((const wchar_t *)input.utf16());
-        if (!hdll) {
-            fprintf(stderr, "Couldn't load library file %s\n", (const char*)input.toLocal8Bit().data());
-            return false;
-        }
-        typedef HRESULT(__stdcall* RegServerProc)();
-        RegServerProc DllRegisterServer = (RegServerProc)GetProcAddress(hdll, "DllRegisterServer");
-        if (!DllRegisterServer) {
-            fprintf(stderr, "Library file %s doesn't appear to be a COM library\n", (const char*)input.toLocal8Bit().data());
-            return false;
-        }
-        ok = DllRegisterServer() == S_OK;
-    }
-    return ok;
-}
-
-static bool unregisterServer(const QString &input)
-{
-    bool ok = false;
-    if (input.endsWith(QLatin1String(".exe"))) {        
-        ok = runWithQtInEnvironment(quotePath(input) + QLatin1String(" -unregserver"));
-    } else {
-        HMODULE hdll = LoadLibrary((const wchar_t *)input.utf16());
-        if (!hdll) {
-            fprintf(stderr, "Couldn't load library file %s\n", (const char*)input.toLocal8Bit().data());
-            return false;
-        }
-        typedef HRESULT(__stdcall* RegServerProc)();
-        RegServerProc DllUnregisterServer = (RegServerProc)GetProcAddress(hdll, "DllUnregisterServer");
-        if (!DllUnregisterServer) {
-            fprintf(stderr, "Library file %s doesn't appear to be a COM library\n", (const char*)input.toLocal8Bit().data());
-            return false;
-        }
-        ok = DllUnregisterServer() == S_OK;
-    }
-    return ok;
-}
-
-static HRESULT dumpIdl(const QString &input, const QString &idlfile, const QString &version)
-{
-    HRESULT res = E_FAIL;
-    
-    if (input.endsWith(QLatin1String(".exe"))) {
-        if (runWithQtInEnvironment(quotePath(input) + QLatin1String(" -dumpidl ") + idlfile + QLatin1String(" -version ") + version))
-            res = S_OK;
-    } else {
-        HMODULE hdll = LoadLibrary((const wchar_t *)input.utf16());
-        if (!hdll) {
-            fprintf(stderr, "Couldn't load library file %s\n", (const char*)input.toLocal8Bit().data());
-            return 3;
-        }
-        typedef HRESULT(__stdcall* DumpIDLProc)(const QString&, const QString&);
-        DumpIDLProc DumpIDL = (DumpIDLProc)GetProcAddress(hdll, "DumpIDL");
-        if (!DumpIDL) {
-            fprintf(stderr, "Couldn't resolve 'DumpIDL' symbol in %s\n", (const char*)input.toLocal8Bit().data());
-            return 3;
-        }
-        res = DumpIDL(idlfile, version);
-        FreeLibrary(hdll);
-    }
-    
-    return res;
-}
-
-static void slashify(QString &s)
-{
-    if (!s.contains(QLatin1Char('/')))
-        return;
-    
-    int i = 0;
-    while (i < (int)s.length()) {
-        if (s[i] == QLatin1Char('/'))
-            s[i] = QLatin1Char('\\');
-        ++i;
-    }
-}
-
-int runIdc(int argc, char **argv)
-{
-    QString error;
-    QString tlbfile;
-    QString idlfile;
-    QString input;
-    QString version = QLatin1String("1.0");
-    
-    int i = 1;
-    while (i < argc) {
-        QString p = QString::fromLocal8Bit(argv[i]).toLower();
-        
-        if (p == QLatin1String("/idl") || p == QLatin1String("-idl")) {
-            ++i;
-            if (i > argc) {
-                error = QLatin1String("Missing name for interface definition file!");
-                break;
-            }
-            idlfile = QLatin1String(argv[i]);
-            idlfile = idlfile.trimmed().toLower();            
-        } else if (p == QLatin1String("/version") || p == QLatin1String("-version")) {
-            ++i;
-            if (i > argc)
-                version = QLatin1String("1.0");
-            else
-                version = QLatin1String(argv[i]);
-        } else if (p == QLatin1String("/tlb") || p == QLatin1String("-tlb")) {
-            ++i;
-            if (i > argc) {
-                error = QLatin1String("Missing name for type library file!");
-                break;
-            }
-            tlbfile = QLatin1String(argv[i]);
-            tlbfile = tlbfile.trimmed().toLower();            
-        } else if (p == QLatin1String("/v") || p == QLatin1String("-v")) {
-            fprintf(stdout, "Qt Interface Definition Compiler version 1.0\n");
-            return 0;
-        } else if (p == QLatin1String("/regserver") || p == QLatin1String("-regserver")) {
-            if (!registerServer(input)) {
-                fprintf(stderr, "Failed to register server!\n");
-                return 1;
-            }
-            fprintf(stderr, "Server registered successfully!\n");
-            return 0;
-        } else if (p == QLatin1String("/unregserver") || p == QLatin1String("-unregserver")) {
-            if (!unregisterServer(input)) {
-                fprintf(stderr, "Failed to unregister server!\n");
-                return 1;
-            }
-            fprintf(stderr, "Server unregistered successfully!\n");
-            return 0;
-        } else if (p[0] == QLatin1Char('/') || p[0] == QLatin1Char('-')) {
-            error = QLatin1String("Unknown option \"") + p + QLatin1Char('\"');
-            break;
-        } else {
-            input = QLatin1String(argv[i]);
-            input = input.trimmed().toLower();            
-        }
-        i++;
-    }
-    if (!error.isEmpty()) {
-        fprintf(stderr, "%s", error.toLatin1().data());
-        fprintf(stderr, "\n");
-        return 5;
-    }
-    if (input.isEmpty()) {
-        fprintf(stderr, "No input file specified!\n");
-        return 1;
-    }
-    if (input.endsWith(QLatin1String(".exe")) && tlbfile.isEmpty() && idlfile.isEmpty()) {
-        fprintf(stderr, "No type output file specified!\n");
-        return 2;
-    }
-    if (input.endsWith(QLatin1String(".dll")) && idlfile.isEmpty() && tlbfile.isEmpty()) {
-        fprintf(stderr, "No interface definition file and no type library file specified!\n");
-        return 3;
-    }
-    slashify(input);
-    if (!tlbfile.isEmpty()) {
-        slashify(tlbfile);
-        QFile file(tlbfile);
-        if (!file.open(QIODevice::ReadOnly)) {
-            fprintf(stderr, "Couldn't open %s for read\n", (const char*)tlbfile.toLocal8Bit().data());
-            return 4;
-        }
-        QByteArray data = file.readAll();
-        QString error;
-        bool ok = attachTypeLibrary(input, 1, data, &error);
-        fprintf(stderr, "%s", error.toLatin1().data());
-        fprintf(stderr, "\n");
-        return ok ? 0 : 4;
-    } else if (!idlfile.isEmpty()) {
-        slashify(idlfile);
-        idlfile = quotePath(idlfile);
-        fprintf(stderr, "\n\n%s\n\n", (const char*)idlfile.toLocal8Bit().data());
-        quotePath(input);
-        HRESULT res = dumpIdl(input, idlfile, version);
-        
-        switch(res) {
-        case S_OK:
-            break;
-        case E_FAIL:
-            fprintf(stderr, "IDL generation failed trying to run program %s!\n", (const char*)input.toLocal8Bit().data());
-            return res;
-        case -1:
-            fprintf(stderr, "Couldn't open %s for writing!\n", (const char*)idlfile.toLocal8Bit().data());
-            return res;
-        case 1:
-            fprintf(stderr, "Malformed appID value in %s!\n", (const char*)input.toLocal8Bit().data());
-            return res;
-        case 2:
-            fprintf(stderr, "Malformed typeLibID value in %s!\n", (const char*)input.toLocal8Bit().data());
-            return res;
-        case 3:
-            fprintf(stderr, "Class has no metaobject information (error in %s)!\n", (const char*)input.toLocal8Bit().data());
-            return res;
-        case 4:
-            fprintf(stderr, "Malformed classID value in %s!\n", (const char*)input.toLocal8Bit().data());
-            return res;
-        case 5:
-            fprintf(stderr, "Malformed interfaceID value in %s!\n", (const char*)input.toLocal8Bit().data());
-            return res;
-        case 6:
-            fprintf(stderr, "Malformed eventsID value in %s!\n", (const char*)input.toLocal8Bit().data());
-            return res;
-            
-        default:
-            fprintf(stderr, "Unknown error writing IDL from %s\n", (const char*)input.toLocal8Bit().data());
-            return 7;
-        }
-    }
-    return 0;
-}
-
-QT_END_NAMESPACE
-
-int main(int argc, char **argv)
-{
-    return QT_PREPEND_NAMESPACE(runIdc)(argc, argv);
-}
diff --git a/src/tools/moc/mwerks_mac.cpp b/src/tools/moc/mwerks_mac.cpp
deleted file mode 100644 (file)
index 1e6f14d..0000000
+++ /dev/null
@@ -1,240 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the tools applications 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifdef MOC_MWERKS_PLUGIN
-
-#include "mwerks_mac.h"
-#include "qt_mac.h"
-
-/* compiler headers */
-#include "DropInCompilerLinker.h"
-#include "CompilerMapping.h"
-#include "CWPluginErrors.h"
-
-/* standard headers */
-#include <stdio.h>
-#include <string.h>
-
-QT_BEGIN_NAMESPACE
-
-//qglobal.cpp
-const unsigned char * p_str(const char * c);
-QCString pstring2qstring(const unsigned char *c);
-
-#if CW_USE_PRAGMA_EXPORT
-#pragma export on
-#endif
-
-CWPLUGIN_ENTRY(CWPlugin_GetDropInFlags)(const DropInFlags** flags, long* flagsSize)
-{
-        static const DropInFlags sFlags = {
-                kCurrentDropInFlagsVersion,
-                CWDROPINCOMPILERTYPE,
-                DROPINCOMPILERLINKERAPIVERSION_7,
-                kCompAlwaysReload|kCompRequiresProjectBuildStartedMsg,
-                Lang_C_CPP,
-                DROPINCOMPILERLINKERAPIVERSION
-        };
-        *flags = &sFlags;
-        *flagsSize = sizeof(sFlags);
-        return cwNoErr;
-}
-
-
-
-CWPLUGIN_ENTRY(CWPlugin_GetDropInName)(const char** dropinName)
-{
-        static const char sDropInName[] = "McMoc";
-        *dropinName = sDropInName;
-        return cwNoErr;
-}
-
-CWPLUGIN_ENTRY(CWPlugin_GetDisplayName)(const char** displayName)
-{
-        static const char sDisplayName[] = "McMoc";
-        *displayName = sDisplayName;
-        return cwNoErr;
-}
-
-CWPLUGIN_ENTRY(CWPlugin_GetTargetList)(const CWTargetList** targetList)
-{
-        static CWDataType sCPU = targetCPUAny;
-        static CWDataType sOS = targetOSMacintosh;
-        static CWTargetList sTargetList = {kCurrentCWTargetListVersion, 1, &sCPU, 1, &sOS};
-        *targetList = &sTargetList;
-        return cwNoErr;
-}
-
-CWPLUGIN_ENTRY(CWPlugin_GetDefaultMappingList)(const CWExtMapList** defaultMappingList)
-{
-        static CWExtensionMapping sExtension[] = { {'TEXT', ".mocs", kPrecompile } };
-        static CWExtMapList sExtensionMapList = {kCurrentCWExtMapListVersion, 3, sExtension};
-        *defaultMappingList = &sExtensionMapList;
-        return cwNoErr;
-}
-
-#if CW_USE_PRAGMA_EXPORT
-#pragma export off
-#endif
-typedef short CWFileRef;
-
-static int line_count = 0;
-moc_status do_moc(CWPluginContext, const QCString &, const QCString &, CWFileSpec *, bool);
-
-static CWResult        mocify(CWPluginContext context, const QCString &source)
-{
-    CWDisplayLines(context, line_count++);
-
-    source.stripWhiteSpace();
-
-    CWResult err;
-        bool            dotmoc=false;
-        QCString stem = source, ext;
-        int dotpos = stem.findRev('.');
-    if(dotpos != -1) {
-        ext = stem.right(stem.length() - (dotpos+1));
-        stem = stem.left(dotpos);
-        if(ext == "cpp")
-            dotmoc = true;
-    } else {
-        //whoa!
-    }
-    QCString dest;
-    if(dotmoc)
-        dest = stem + ".moc";
-    else
-        dest = "moc_" + stem + ".cpp";
-
-    //moc it
-    CWFileSpec destSpec;
-        moc_status mocd = do_moc(context, source, dest, &destSpec, dotmoc);
-
-#if 0
-    QCString derr = "Weird";
-    switch(mocd) {
-    case moc_success: derr = "Success"; break;
-    case moc_parse_error: derr = "Parser Error"; break;
-    case moc_no_qobject:derr = "No QOBJECT"; break;
-    case moc_not_time: derr = "Not Time"; break;
-    case moc_no_source: derr = "No Source"; break;
-    case moc_general_error: derr = "General Error"; break;
-    }
-        char        dmsg[200];
-        sprintf(dmsg, "\"%s\" %s", source.data(), derr.data());
-        CWReportMessage(context, NULL, dmsg, NULL, messagetypeError, 0);
-#endif
-
-    //handle project
-    if(mocd == moc_no_qobject) {
-        char        msg[400];
-                sprintf(msg, "\"%s\" No relevant classes found. No output generated.", source.data());
-                CWReportMessage(context, NULL, msg, NULL, messagetypeWarning, 0);
-        } else if ((mocd == moc_success || mocd == moc_not_time) && !dotmoc)
-        {
-                long                        whichFile;
-                CWNewProjectEntryInfo ei;
-                memset(&ei, '\0', sizeof(ei));
-                ei.groupPath = "QtGenerated";
-                    err = CWAddProjectEntry(context, &destSpec, true, &ei, &whichFile);
-                    if (!CWSUCCESS(err))
-                    {
-                            char        msg[200];
-                            sprintf(msg, "\"%s\" not added", dest.data());
-                            CWReportMessage(context, NULL, msg, NULL, messagetypeWarning, 0);
-                    }
-                    if(mocd == moc_success)
-                        CWSetModDate(context, &destSpec, NULL, true);
-        }
-        return cwNoErr;
-}
-
-pascal short main(CWPluginContext context)
-{
-        short                result;
-        long                request;
-
-        if (CWGetPluginRequest(context, &request) != cwNoErr)
-                return cwErrRequestFailed;
-        result = cwErrInvalidParameter;
-
-        /* dispatch on compiler request */
-        switch (request)
-        {
-        case reqInitCompiler:
-        case reqTermCompiler:
-            result = cwNoErr;
-        break;
-
-        case reqCompile:
-        {
-            line_count = 0;
-            const char *files = NULL;
-            long filelen;
-            CWGetMainFileText(context, &files, &filelen);
-            const char *beg = files;
-            for(int x = 0; x < filelen; x++) {
-                if(*(files++) == '\r') {
-                    char file[1024];
-                    memcpy(file, beg, files - beg);
-                    file[(files-beg)-1] = '\0';
-                    mocify(context, file);
-                beg = files;
-            }
-        }
-        if(beg != files) {
-                char file[1024];
-                memcpy(file, beg, files - beg);
-                file[(files-beg)] = '\0';
-                mocify(context, file);
-        }
-
-        result = cwNoErr;
-                break;
-        }
-        }
-
-        /* return result code */
-        return result;
-}
-
-#endif
-
-QT_END_NAMESPACE
diff --git a/src/tools/moc/mwerks_mac.h b/src/tools/moc/mwerks_mac.h
deleted file mode 100644 (file)
index f557530..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the tools applications 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 http://www.qt.io/terms-conditions. For further
-** information use the contact form at http://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 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** As a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3.0 as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL included in the
-** packaging of this file.  Please review the following information to
-** ensure the GNU General Public License version 3.0 requirements will be
-** met: http://www.gnu.org/copyleft/gpl.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#ifndef MWERKS_MAC_H
-#define MWERKS_MAC_H
-
-#include <QtGlobal>
-
-QT_BEGIN_NAMESPACE
-
-#ifdef Q_OS_MAC
-
-#define macintosh
-
-/*make moc a plugin*/
-enum moc_status {
-    moc_success = 1,
-    moc_parse_error = 2,
-    moc_no_qobject = 3,
-    moc_not_time = 4,
-    moc_no_source = 5,
-    moc_general_error = 6
-};
-
-#endif
-
-QT_END_NAMESPACE
-
-#endif // MWERKS_MAC_H
diff --git a/src/tools/qdbusviewer/Info_mac.plist b/src/tools/qdbusviewer/Info_mac.plist
deleted file mode 100644 (file)
index b351409..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
-<plist version="0.9">
-<dict>
-       <key>CFBundleIconFile</key>
-       <string>@ICON@</string>
-       <key>CFBundlePackageType</key>
-       <string>APPL</string>
-        <key>CFBundleGetInfoString</key>
-       <string>Created by Qt/QMake</string>
-       <key>CFBundleSignature</key>
-       <string>????</string>
-       <key>CFBundleIdentifier</key>
-       <string>com.trolltech.dbusviewer</string>
-       <key>CFBundleExecutable</key>
-       <string>@EXECUTABLE@</string>
-</dict>
-</plist>
diff --git a/src/tools/qdbusviewer/qdbusviewer.pro b/src/tools/qdbusviewer/qdbusviewer.pro
deleted file mode 100644 (file)
index 9934660..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-mac {
-    ICON = images/qdbusviewer.icns
-    QMAKE_INFO_PLIST = Info_mac.plist
-}
-
-win32 {
-    RC_FILE = qdbusviewer.rc
-}
diff --git a/src/tools/qdbusviewer/qdbusviewer.rc b/src/tools/qdbusviewer/qdbusviewer.rc
deleted file mode 100644 (file)
index c4b1d60..0000000
+++ /dev/null
@@ -1 +0,0 @@
-IDI_ICON1              ICON            DISCARDABLE     "images/qdbusviewer.ico"
diff --git a/src/winmain/qtmain_win.cpp b/src/winmain/qtmain_win.cpp
deleted file mode 100644 (file)
index 85b808b..0000000
+++ /dev/null
@@ -1,136 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing/
-**
-** This file is part of the Windows main function of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** You may use this file under the terms of the BSD license as follows:
-**
-** "Redistribution and use in source and binary forms, with or without
-** modification, are permitted provided that the following conditions are
-** met:
-**   * Redistributions of source code must retain the above copyright
-**     notice, this list of conditions and the following disclaimer.
-**   * Redistributions in binary form must reproduce the above copyright
-**     notice, this list of conditions and the following disclaimer in
-**     the documentation and/or other materials provided with the
-**     distribution.
-**   * Neither the name of The Qt Company Ltd nor the names of its
-**     contributors may be used to endorse or promote products derived
-**     from this software without specific prior written permission.
-**
-**
-** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-#include "qt_windows.h"
-#include "qbytearray.h"
-#include "qstring.h"
-#include "qvector.h"
-
-/*
-  This file contains the code in the qtmain library for Windows.
-  qtmain contains the Windows startup code and is required for
-  linking to the Qt DLL.
-
-  When a Windows application starts, the WinMain function is
-  invoked. WinMain calls qWinMain in the Qt DLL/library, which
-  initializes Qt.
-*/
-
-QT_BEGIN_NAMESPACE
-
-#if defined(Q_OS_WINCE)
-extern void __cdecl qWinMain(HINSTANCE, HINSTANCE, LPSTR, int, int &, QVector<char *> &);
-#else
-extern void qWinMain(HINSTANCE, HINSTANCE, LPSTR, int, int &, QVector<char *> &);
-#endif
-
-QT_END_NAMESPACE
-
-QT_USE_NAMESPACE
-
-
-#if defined(QT_NEEDS_QMAIN)
-int qMain(int, char **);
-#define main qMain
-#else
-#ifdef Q_OS_WINCE
-extern "C" int __cdecl main(int, char **);
-#else
-extern "C" int main(int, char **);
-#endif
-#endif
-
-/*
-  WinMain() - Initializes Windows and calls user's startup function main().
-  NOTE: WinMain() won't be called if the application was linked as a "console"
-  application.
-*/
-
-#ifdef Q_OS_WINCE
-int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPWSTR /*wCmdParam*/, int cmdShow)
-#else
-extern "C"
-int APIENTRY WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR /*cmdParamarg*/, int cmdShow)
-#endif
-{
-    QByteArray cmdParam = QString::fromWCharArray(GetCommandLine()).toLocal8Bit();
-
-#if defined(Q_OS_WINCE)
-    wchar_t appName[MAX_PATH];
-    GetModuleFileName(0, appName, MAX_PATH);
-    cmdParam.prepend(QString(QLatin1String("\"%1\" ")).arg(QString::fromWCharArray(appName)).toLocal8Bit());
-#endif
-
-    int argc = 0;
-    QVector<char *> argv(8);
-    qWinMain(instance, prevInstance, cmdParam.data(), cmdShow, argc, argv);
-
-#if defined(Q_OS_WINCE)
-    wchar_t uniqueAppID[MAX_PATH];
-    GetModuleFileName(0, uniqueAppID, MAX_PATH);
-    QString uid = QString::fromWCharArray(uniqueAppID).toLower().replace(QLatin1String("\\"), QLatin1String("_"));
-
-    // If there exists an other instance of this application
-    // it will be the owner of a mutex with the unique ID.
-    HANDLE mutex = CreateMutex(NULL, TRUE, (LPCWSTR)uid.utf16());
-    if (mutex && ERROR_ALREADY_EXISTS == GetLastError()) {
-        CloseHandle(mutex);
-
-        // The app is already running, so we use the unique
-        // ID to create a unique messageNo, which is used
-        // as the registered class name for the windows
-        // created. Set the first instance's window to the
-        // foreground, else just terminate.
-        // Use bitwise 0x01 OR to reactivate window state if
-        // it was hidden
-        UINT msgNo = RegisterWindowMessage((LPCWSTR)uid.utf16());
-        HWND aHwnd = FindWindow((LPCWSTR)QString::number(msgNo).utf16(), 0);
-        if (aHwnd)
-            SetForegroundWindow((HWND)(((ULONG)aHwnd) | 0x01));
-        return 0;
-    }
-#endif // Q_OS_WINCE
-
-    int result = main(argc, argv.data());
-#if defined(Q_OS_WINCE)
-    CloseHandle(mutex);
-#endif
-    return result;
-}