diff --git a/config.tests/common/atomic64/atomic64.cpp b/config.tests/common/atomic64/atomic64.cpp
index 8dbea96c8b7017e69025d64b9623c6fd02207323..20fbeca740b6432116109c1066185f94b5fcf977 100644
--- a/config.tests/common/atomic64/atomic64.cpp
+++ b/config.tests/common/atomic64/atomic64.cpp
@@ -3,7 +3,7 @@
 ** Copyright (C) 2015 Intel Corporation.
 ** Contact: http://www.qt.io/licensing/
 **
-** This file is part of the FOO module of the Qt Toolkit.
+** This file is part of the configuration of the Qt Toolkit.
 **
 ** $QT_BEGIN_LICENSE:LGPL21$
 ** Commercial License Usage
diff --git a/config.tests/common/c++11/c++11.cpp b/config.tests/common/c++11/c++11.cpp
index 04a83390af5c381d2859d898eadee1505acf4036..dddb22a9e241a53a9d1eb729f610fc7adb8c8df0 100644
--- a/config.tests/common/c++11/c++11.cpp
+++ b/config.tests/common/c++11/c++11.cpp
@@ -3,7 +3,7 @@
 ** Copyright (C) 2015 The Qt Company Ltd.
 ** Contact: http://www.qt.io/licensing/
 **
-** This file is part of the FOO module of the Qt Toolkit.
+** This file is part of the configuration of the Qt Toolkit.
 **
 ** $QT_BEGIN_LICENSE:LGPL21$
 ** Commercial License Usage
diff --git a/configure b/configure
index a885af0f033433a02c9419c799fc608d1873b709..982743b73100d67ebbd3ee2635c1b085fdd2702a 100755
--- a/configure
+++ b/configure
@@ -126,8 +126,8 @@ shellQuoteLines()
 
 makeabs()
 {
-    local FILE=$1
-    local RES=$FILE
+    local FILE="$1"
+    local RES="$FILE"
     if [ -z "${FILE##/*}" ]; then
         true
     elif [ "$OSTYPE" = "msys" -a -z "${FILE##[a-zA-Z]:[/\\]*}" ]; then
@@ -2619,7 +2619,9 @@ Additional options:
     -l <string> ........ Add an explicit library.
 
     -no-rpath .......... Do not use the library install path as a runtime
-                         library path.
+                         library path. On Apple platforms, this implies using
+                         absolute install names (based in -libdir) for dynamic
+                         libraries and frameworks.
  +  -rpath ............. Link Qt libraries and executables using the library
                          install path as a runtime library path. Equivalent
                          to -R install_libpath
diff --git a/examples/widgets/desktop/systray/doc/src/systray.qdoc b/examples/widgets/desktop/systray/doc/src/systray.qdoc
index fa2dbb27218df56889c121b9c6f47db3ec0627e6..ae6df351bbb2c517e988a7373b9e31d3b276d06c 100644
--- a/examples/widgets/desktop/systray/doc/src/systray.qdoc
+++ b/examples/widgets/desktop/systray/doc/src/systray.qdoc
@@ -28,9 +28,8 @@
 /*!
     \example desktop/systray
     \title System Tray Icon Example
-
-
-    The System Tray Icon example shows how to add an icon with a menu
+    \ingroup examples-widgets
+    \brief The System Tray Icon example shows how to add an icon with a menu
     and popup messages to a desktop environment's system tray.
 
     \image systemtray-example.png Screenshot of the System Tray Icon.
@@ -47,7 +46,7 @@
 
     The editor allows the user to choose the preferred icon as well as
     set the balloon message's type and duration. The user can also
-    edit the message's title and body. Finally, the editor provide a
+    edit the message's title and body. Finally, the editor provides a
     checkbox controlling whether the icon is actually shown in the
     system tray, or not.
 
@@ -65,8 +64,8 @@
     check whether a system tray is present on the user's desktop, call
     the static QSystemTrayIcon::isSystemTrayAvailable()
     function. Associated with the icon, we provide a menu containing
-    the typical \gui minimize, \gui maximize, \gui restore and \gui
-    quit actions. We reimplement the QWidget::setVisible() function to
+    the typical \uicontrol minimize, \uicontrol maximize, \uicontrol restore and
+    \uicontrol quit actions. We reimplement the QWidget::setVisible() function to
     update the tray icon's menu whenever the editor's appearance
     changes, e.g., when maximizing or minimizing the main application
     window.
@@ -74,7 +73,7 @@
     Finally, we reimplement QWidget's \l {QWidget::}{closeEvent()}
     function to be able to inform the user (when closing the editor
     window) that the program will keep running in the system tray
-    until the user chooses the \gui Quit entry in the icon's context
+    until the user chooses the \uicontrol Quit entry in the icon's context
     menu.
 
     \section1 Window Class Implementation
diff --git a/examples/widgets/doc/src/fridgemagnets.qdoc b/examples/widgets/doc/src/fridgemagnets.qdoc
index 5e1052b413ee32d68f5176be33349b06898b3475..bf3343af0ec00c139ddee05e4897e7c633d12ef9 100644
--- a/examples/widgets/doc/src/fridgemagnets.qdoc
+++ b/examples/widgets/doc/src/fridgemagnets.qdoc
@@ -28,6 +28,8 @@
 /*!
     \example draganddrop/fridgemagnets
     \title Fridge Magnets Example
+    \brief The Fridge Magnets example illustrates how to move around several types of
+    MIME-encoded data with drag and drop.
 
     The Fridge Magnets example shows how to supply more than one type
     of MIME-encoded data with a drag and drop operation.
diff --git a/examples/widgets/doc/src/systray.qdoc b/examples/widgets/doc/src/systray.qdoc
deleted file mode 100644
index b05f999dfa5e74b99f4fc74c231de85322574286..0000000000000000000000000000000000000000
--- a/examples/widgets/doc/src/systray.qdoc
+++ /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 documentation of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:FDL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software 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 Free Documentation License Usage
-** Alternatively, this file may be used under the terms of the GNU Free
-** Documentation License version 1.3 as published by the Free Software
-** Foundation and appearing in the file included in the packaging of
-** this file. Please review the following information to ensure
-** the GNU Free Documentation License version 1.3 requirements
-** will be met: http://www.gnu.org/copyleft/fdl.html.
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
-/*!
-    \example desktop/systray
-    \title System Tray Icon Example
-    \ingroup examples-widgets
-    \brief The System Tray Icon example shows how to add an icon with a menu
-    and popup messages to a desktop environment's system tray.
-
-    \image systemtray-example.png Screenshot of the System Tray Icon.
-
-    Modern operating systems usually provide a special area on the
-    desktop, called the system tray or notification area, where
-    long-running applications can display icons and short messages.
-
-    This example consists of one single class, \c Window, providing
-    the main application window (i.e., an editor for the system tray
-    icon) and the associated icon.
-
-    \image systemtray-editor.png
-
-    The editor allows the user to choose the preferred icon as well as
-    set the balloon message's type and duration. The user can also
-    edit the message's title and body. Finally, the editor provides a
-    checkbox controlling whether the icon is actually shown in the
-    system tray, or not.
-
-    \section1 Window Class Definition
-
-    The \c Window class inherits QWidget:
-
-    \snippet desktop/systray/window.h 0
-
-    We implement several private slots to respond to user
-    interaction. The other private functions are only convenience
-    functions provided to simplify the constructor.
-
-    The tray icon is an instance of the QSystemTrayIcon class. To
-    check whether a system tray is present on the user's desktop, call
-    the static QSystemTrayIcon::isSystemTrayAvailable()
-    function. Associated with the icon, we provide a menu containing
-    the typical \uicontrol minimize, \uicontrol maximize, \uicontrol restore and
-    \uicontrol quit actions. We reimplement the QWidget::setVisible() function
-    to update the tray icon's menu whenever the editor's appearance
-    changes, e.g., when maximizing or minimizing the main application
-    window.
-
-    Finally, we reimplement QWidget's \l {QWidget::}{closeEvent()}
-    function to be able to inform the user (when closing the editor
-    window) that the program will keep running in the system tray
-    until the user chooses the \uicontrol Quit entry in the icon's context
-    menu.
-
-    \section1 Window Class Implementation
-
-    When constructing the editor widget, we first create the various
-    editor elements before we create the actual system tray icon:
-
-    \snippet desktop/systray/window.cpp 0
-
-    We ensure that the application responds to user input by
-    connecting most of the editor's input widgets (including the
-    system tray icon) to the application's private slots. But note the
-    visibility checkbox; its \l {QCheckBox::}{toggled()} signal is
-    connected to the \e {icon}'s \l {QSystemTrayIcon::}{setVisible()}
-    function instead.
-
-    \snippet desktop/systray/window.cpp 3
-
-    The \c setIcon() slot is triggered whenever the current index in
-    the icon combobox changes, i.e., whenever the user chooses another
-    icon in the editor. Note that it is also called when the user
-    activates the tray icon with the left mouse button, triggering the
-    icon's \l {QSystemTrayIcon::}{activated()} signal. We will come
-    back to this signal shortly.
-
-    The QSystemTrayIcon::setIcon() function sets the \l
-    {QSystemTrayIcon::}{icon} property that holds the actual system
-    tray icon. On Windows, the system tray icon size is 16x16; on X11,
-    the preferred size is 22x22. The icon will be scaled to the
-    appropriate size as necessary.
-
-    Note that on X11, due to a limitation in the system tray
-    specification, mouse clicks on transparent areas in the icon are
-    propagated to the system tray. If this behavior is unacceptable,
-    we suggest using an icon with no transparency.
-
-    \snippet desktop/systray/window.cpp 4
-
-    Whenever the user activates the system tray icon, it emits its \l
-    {QSystemTrayIcon::}{activated()} signal passing the triggering
-    reason as parameter. QSystemTrayIcon provides the \l
-    {QSystemTrayIcon::}{ActivationReason} enum to describe how the
-    icon was activated.
-
-    In the constructor, we connected our icon's \l
-    {QSystemTrayIcon::}{activated()} signal to our custom \c
-    iconActivated() slot: If the user has clicked the icon using the
-    left mouse button, this function changes the icon image by
-    incrementing the icon combobox's current index, triggering the \c
-    setIcon() slot as mentioned above. If the user activates the icon
-    using the middle mouse button, it calls the custom \c
-    showMessage() slot:
-
-    \snippet desktop/systray/window.cpp 5
-
-    When the \e showMessage() slot is triggered, we first retrieve the
-    message icon depending on the currently chosen message type. The
-    QSystemTrayIcon::MessageIcon enum describes the icon that is shown
-    when a balloon message is displayed. Then we call
-    QSystemTrayIcon's \l {QSystemTrayIcon::}{showMessage()} function
-    to show the message with the title, body, and icon for the time
-    specified in milliseconds.
-
-    QSystemTrayIcon also has the corresponding, \l {QSystemTrayIcon::}
-    {messageClicked()} signal, which is emitted when the user clicks a
-    message displayed by \l {QSystemTrayIcon::}{showMessage()}.
-
-    \snippet desktop/systray/window.cpp 6
-
-    In the constructor, we connected the \l
-    {QSystemTrayIcon::}{messageClicked()} signal to our custom \c
-    messageClicked() slot that simply displays a message using the
-    QMessageBox class.
-
-    QMessageBox provides a modal dialog with a short message, an icon,
-    and buttons laid out depending on the current style. It supports
-    four severity levels: "Question", "Information", "Warning" and
-    "Critical". The easiest way to pop up a message box in Qt is to
-    call one of the associated static functions, e.g.,
-    QMessageBox::information().
-
-    As we mentioned earlier, we reimplement a couple of QWidget's
-    virtual functions:
-
-    \snippet desktop/systray/window.cpp 1
-
-    Our reimplementation of the QWidget::setVisible() function updates
-    the tray icon's menu whenever the editor's appearance changes,
-    e.g., when maximizing or minimizing the main application window,
-    before calling the base class implementation.
-
-    \snippet desktop/systray/window.cpp 2
-
-    We have reimplemented the QWidget::closeEvent() event handler to
-    receive widget close events, showing the above message to the
-    users when they are closing the editor window.
-
-    In addition to the functions and slots discussed above, we have
-    also implemented several convenience functions to simplify the
-    constructor: \c createIconGroupBox(), \c createMessageGroupBox(),
-    \c createActions() and \c createTrayIcon(). See the \l
-    {desktop/systray/window.cpp}{window.cpp} file for details.
-*/
diff --git a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp
index a57dbaa9a0d8bcbf339336d98abfa1df75035f20..02479c1a5ae9523b0c3cbfcb92d27154fe5d88bb 100644
--- a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp
+++ b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp
@@ -389,7 +389,7 @@ void MainWindow::createActions()
 //! [23]
 
     sendBackAction = new QAction(QIcon(":/images/sendtoback.png"), tr("Send to &Back"), this);
-    sendBackAction->setShortcut(tr("Ctrl+B"));
+    sendBackAction->setShortcut(tr("Ctrl+T"));
     sendBackAction->setStatusTip(tr("Send item to back"));
     connect(sendBackAction, SIGNAL(triggered()), this, SLOT(sendToBack()));
 
@@ -421,7 +421,7 @@ void MainWindow::createActions()
     connect(underlineAction, SIGNAL(triggered()), this, SLOT(handleFontChange()));
 
     aboutAction = new QAction(tr("A&bout"), this);
-    aboutAction->setShortcut(tr("Ctrl+B"));
+    aboutAction->setShortcut(tr("F1"));
     connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
 }
 
diff --git a/examples/widgets/tools/codecs/doc/src/codecs.qdoc b/examples/widgets/tools/codecs/doc/src/codecs.qdoc
index b640d95c38380439802fd9f4a74dd1b3b2a8ec7f..69bf1470b16c9c335bda17d683319568939894bd 100644
--- a/examples/widgets/tools/codecs/doc/src/codecs.qdoc
+++ b/examples/widgets/tools/codecs/doc/src/codecs.qdoc
@@ -28,6 +28,7 @@
 /*!
     \example tools/codecs
     \title Text Codecs Example
+    \brief How to import and export text using text codecs.
 
     The Text Codecs example demonstrates the principles behind importing and exporting text
     using codecs to ensure that characters are encoded properly, avoiding loss of data
diff --git a/examples/xml/dombookmarks/doc/src/dombookmarks.qdoc b/examples/xml/dombookmarks/doc/src/dombookmarks.qdoc
index 86d422de8059ba8a9bf6682059624122d67e5738..63e2e93654abace1485cd0fdb59f928c47183533 100644
--- a/examples/xml/dombookmarks/doc/src/dombookmarks.qdoc
+++ b/examples/xml/dombookmarks/doc/src/dombookmarks.qdoc
@@ -29,6 +29,7 @@
     \example dombookmarks
     \title DOM Bookmarks Example
     \ingroup xml-examples
+    \brief Provides a reader for XML Bookmark Exchange Language files
 
     The DOM Bookmarks example provides a reader for XML Bookmark Exchange Language (XBEL)
     files that uses Qt's DOM-based XML API to read and parse the files. The SAX Bookmarks
diff --git a/examples/xml/xmlstreamlint/doc/src/xmlstreamlint.qdoc b/examples/xml/xmlstreamlint/doc/src/xmlstreamlint.qdoc
index 48e6fe07342fc0c84148b70c1842e751334160e0..d13708cb60974e23134df2fb739a7389250a2966 100644
--- a/examples/xml/xmlstreamlint/doc/src/xmlstreamlint.qdoc
+++ b/examples/xml/xmlstreamlint/doc/src/xmlstreamlint.qdoc
@@ -29,6 +29,8 @@
     \example xmlstreamlint
     \title XML Stream Lint Example
     \ingroup xml-examples
+    \brief A commandline tool reading from an input file and writing to
+    the standard output file.
 
     The XML Stream Lint example provides a simple command line utility that
     accepts a file name as its single argument and writes it to the standard
diff --git a/mkspecs/common/winrt_winphone/manifests/10.0/AppxManifest.xml.in b/mkspecs/common/winrt_winphone/manifests/10.0/AppxManifest.xml.in
index d091ea3b82fc6a3c1d649db733e5e53af753cf29..c25d7b77af73ff6d9ff3c4740145590529f7fbc3 100644
--- a/mkspecs/common/winrt_winphone/manifests/10.0/AppxManifest.xml.in
+++ b/mkspecs/common/winrt_winphone/manifests/10.0/AppxManifest.xml.in
@@ -4,7 +4,8 @@
   xmlns=\"http://schemas.microsoft.com/appx/manifest/foundation/windows10\"
   xmlns:mp=\"http://schemas.microsoft.com/appx/2014/phone/manifest\"
   xmlns:uap=\"http://schemas.microsoft.com/appx/manifest/uap/windows10\"
-  IgnorableNamespaces=\"uap mp\">
+  xmlns:mobile=\"http://schemas.microsoft.com/appx/manifest/mobile/windows10\"
+  IgnorableNamespaces=\"uap mp mobile\">
 
   <Identity
     Name=\"$${WINRT_MANIFEST.identity}\"
@@ -21,7 +22,7 @@
   </Properties>
 
   <Dependencies>
-    <TargetDeviceFamily Name=\"Windows.Universal\" MinVersion=\"10.0.10069.0\" MaxVersionTested=\"10.0.10069.0\" />$${WINRT_MANIFEST.dependencies}
+    <TargetDeviceFamily Name=\"Windows.Universal\" MinVersion=\"10.0.10240.0\" MaxVersionTested=\"10.0.10586.0\" />$${WINRT_MANIFEST.dependencies}
   </Dependencies>
 
   <Resources>
diff --git a/mkspecs/devices/common/linux_device_pre.conf b/mkspecs/devices/common/linux_device_pre.conf
index cfbdc23d636cfa97161365afe275076d0562b468..8c6c87d0b79e4fbfeaf0124d0a666eed525ea7e5 100644
--- a/mkspecs/devices/common/linux_device_pre.conf
+++ b/mkspecs/devices/common/linux_device_pre.conf
@@ -25,4 +25,4 @@ QMAKE_NM                = $${CROSS_COMPILE}nm -P
 QMAKE_STRIP             = $${CROSS_COMPILE}strip
 
 contains(DISTRO_OPTS, deb-multi-arch): \
-    PKG_CONFIG = $${CROSS_COMPILE}pkg-config
+    QMAKE_PKG_CONFIG = $${CROSS_COMPILE}pkg-config
diff --git a/mkspecs/features/ctest_testcase_common.prf b/mkspecs/features/ctest_testcase_common.prf
index bdf40541ecc086bfaaf0dbd4dfb3472da103d242..7183ade4dfe27ccd32afa0debfce3e162786902b 100644
--- a/mkspecs/features/ctest_testcase_common.prf
+++ b/mkspecs/features/ctest_testcase_common.prf
@@ -56,6 +56,7 @@ mingw:isEmpty(CROSS_COMPILE):CMAKE_GENERATOR = -G \"MinGW Makefiles\"
 
 BUILD_DIR = $$replace($$list($$OUT_PWD/build), /, $$QMAKE_DIR_SEP)
 
+!qtHaveModule(gui): CMAKE_MODULE_DEFINES += -DNO_GUI=True
 !qtHaveModule(widgets): CMAKE_MODULE_DEFINES += -DNO_WIDGETS=True
 !qtHaveModule(dbus): CMAKE_MODULE_DEFINES += -DNO_DBUS=True
 
diff --git a/mkspecs/features/qt.prf b/mkspecs/features/qt.prf
index 72632a14ee25cd974dbb4dd428c04c8a35e47f65..f62b6bb1399fef3af0ba3b4e3fe3e0f1a37f1c19 100644
--- a/mkspecs/features/qt.prf
+++ b/mkspecs/features/qt.prf
@@ -67,8 +67,10 @@ for(ever) {
     unset(BAD_QT)
     for(QTLIB, FULL_QT$$var_sfx) {
         MODULE_NAME = $$eval(QT.$${QTLIB}.name)
+        MODULE_MODULE = $$eval(QT.$${QTLIB}.module)
         MODULE_INCLUDES = $$eval(QT.$${QTLIB}.includes)
         MODULE_LIBS = $$eval(QT.$${QTLIB}.libs)
+        MODULE_FRAMEWORKS = $$eval(QT.$${QTLIB}.frameworks)
         MODULE_CONFIG = $$eval(QT.$${QTLIB}.module_config)
 
         isEmpty(MODULE_NAME) {
@@ -88,49 +90,55 @@ for(ever) {
         MODULE_LIBS_ADD = $$MODULE_LIBS
         MODULE_LIBS_ADD -= $$QMAKE_DEFAULT_LIBDIRS
 
-        LINKAGE =
-        contains(MODULE_CONFIG, lib_bundle) {
-            FRAMEWORK_INCLUDE = $${MODULE_LIBS}/$${MODULE_NAME}.framework/Headers
-            !qt_no_framework_direct_includes {
-                INCLUDEPATH *= $$FRAMEWORK_INCLUDE
+        !contains(MODULE_CONFIG, v2) {
+            # Backwards compatibility with pre-5.6 module .pri files
+
+            contains(MODULE_CONFIG, lib_bundle) {
+                MODULE_FRAMEWORKS = $$MODULE_LIBS
+                inc = $$MODULE_LIBS/$${MODULE_NAME}.framework/Headers
+                MODULE_INCLUDES = $$inc
+                contains(MODULE_CONFIG, internal_module): \
+                    MODULE_INCLUDES += \
+                        $$inc/$$eval(QT.$${QTLIB}.VERSION) \
+                        $$inc/$$eval(QT.$${QTLIB}.VERSION)/$$MODULE_NAME
+            } else {
+                # Re-insert the major version in the library name (cf qt5LibraryTarget above)
+                MODULE_NAME ~= s,^Qt,Qt$$QT_MAJOR_VERSION,
             }
-            contains(MODULE_CONFIG, internal_module): \
-                INCLUDEPATH += \
-                    $$FRAMEWORK_INCLUDE/$$eval(QT.$${QTLIB}.VERSION) \
-                    $$FRAMEWORK_INCLUDE/$$eval(QT.$${QTLIB}.VERSION)/$$MODULE_NAME
-            QMAKE_FRAMEWORKPATH *= $${MODULE_LIBS}
-            !contains(MODULE_CONFIG, no_link): \
-                LINKAGE += -framework $${MODULE_NAME}$${QT_LIBINFIX}
-        } else {
-            INCLUDEPATH *= $$MODULE_INCLUDES
-        }
-
-        # Only link to this module if a libs directory is set, else this is just a module
-        # to give access to sources or include files, and not for linking.
-        !isEmpty(MODULE_LIBS):!contains(MODULE_CONFIG, no_link) {
 
-            # Re-insert the major version in the library name (cf qt5LibraryTarget above)
-            # unless it's a framework build
-            !contains(MODULE_CONFIG, lib_bundle): \
-                MODULE_NAME ~= s,^Qt,Qt$$QT_MAJOR_VERSION,
+            # Only link to this module if a libs directory is set, else this is just a module
+            # to give access to sources or include files, and not for linking.
+            !isEmpty(MODULE_LIBS):!contains(MODULE_CONFIG, no_link): \
+                MODULE_MODULE = $${MODULE_NAME}$${QT_LIBINFIX}
+        }
 
-            isEmpty(LINKAGE) {
+        # Frameworks shouldn't need include paths, but much code does not use
+        # module-qualified #includes, so by default we add paths which point
+        # directly into the frameworks. Private modules have somewhat convoluted
+        # header paths, so adding them is necessary in every case.
+        !if(contains(MODULE_CONFIG, lib_bundle):qt_no_framework_direct_includes) \
+                |contains(MODULE_CONFIG, internal_module): \
+            INCLUDEPATH *= $$MODULE_INCLUDES
+        QMAKE_FRAMEWORKPATH *= $$MODULE_FRAMEWORKS
+        !isEmpty(MODULE_MODULE) {
+            contains(MODULE_CONFIG, lib_bundle) {
+                LIBS$$var_sfx += -framework $$MODULE_MODULE
+            } else {
                 !isEmpty(MODULE_LIBS_ADD): \
-                    LINKAGE = -L$$MODULE_LIBS_ADD
-                lib = $${MODULE_NAME}$${QT_LIBINFIX}$$qtPlatformTargetSuffix()
-                LINKAGE += -l$$lib
+                    LIBS$$var_sfx += -L$$MODULE_LIBS_ADD
+
+                lib = $$MODULE_MODULE$$qtPlatformTargetSuffix()
+                LIBS$$var_sfx += -l$$lib
 
                 contains(MODULE_CONFIG, staticlib): \
                     PRE_TARGETDEPS *= $$MODULE_LIBS/$${QMAKE_PREFIX_STATICLIB}$${lib}.$${QMAKE_EXTENSION_STATICLIB}
-            }
 
-            LIBS$$var_sfx += $$LINKAGE
-
-            !isEmpty(QMAKE_LSB) {
-                !isEmpty(MODULE_LIBS_ADD): \
-                    QMAKE_LFLAGS *= --lsb-libpath=$$MODULE_LIBS_ADD
-                QMAKE_LFLAGS *= --lsb-shared-libs=$${MODULE_NAME}$${QT_LIBINFIX}
-                QMAKE_LIBDIR *= /opt/lsb/lib
+                !isEmpty(QMAKE_LSB) {
+                    !isEmpty(MODULE_LIBS_ADD): \
+                        QMAKE_LFLAGS *= --lsb-libpath=$$MODULE_LIBS_ADD
+                    QMAKE_LFLAGS *= --lsb-shared-libs=$$lib
+                    QMAKE_LIBDIR *= /opt/lsb/lib
+                }
             }
         }
     }
diff --git a/mkspecs/features/qt_functions.prf b/mkspecs/features/qt_functions.prf
index e239db24548fc3485cac8709e6feb743ff21d2c5..b2c250780719e31ed4817585bf4026510659178f 100644
--- a/mkspecs/features/qt_functions.prf
+++ b/mkspecs/features/qt_functions.prf
@@ -196,7 +196,7 @@ defineTest(qtAddTargetEnv) {
         pluginpath.value =
         ppaths = $$[QT_INSTALL_PLUGINS/get]
         for(qplug, QT_PLUGINS): \
-            contains(ptypes, QT_PLUGIN.$${qplug}.TYPE): \
+            contains(ptypes, $$eval(QT_PLUGIN.$${qplug}.TYPE)): \
                 ppaths += $$eval(QT_PLUGIN.$${qplug}.PATH)
         ppaths = $$unique(ppaths)
         for(qplug, ppaths) {
@@ -215,12 +215,16 @@ defineTest(qtAddTargetEnv) {
 
 defineReplace(pkgConfigExecutable) {
     isEmpty(PKG_CONFIG) {
-        PKG_CONFIG = pkg-config
+        !isEmpty(QMAKE_PKG_CONFIG): \
+            PKG_CONFIG = $$QMAKE_PKG_CONFIG
+        else: \
+            PKG_CONFIG = pkg-config
 
         sysroot.name = PKG_CONFIG_SYSROOT_DIR
         sysroot.value = $$PKG_CONFIG_SYSROOT_DIR
         libdir.name = PKG_CONFIG_LIBDIR
         libdir.value = $$PKG_CONFIG_LIBDIR
+        QT_TOOL_NAME = pkg-config
         qtAddToolEnv(PKG_CONFIG, sysroot libdir, SYS)
     }
 
diff --git a/mkspecs/features/qt_module.prf b/mkspecs/features/qt_module.prf
index fdce486c0021631d9693af8f9aa6b6b1b8a2ceb7..e543ea65e648ecb70008156c0875ed9a64552e92 100644
--- a/mkspecs/features/qt_module.prf
+++ b/mkspecs/features/qt_module.prf
@@ -139,6 +139,8 @@ mac {
 
    contains(QT_CONFIG, rpath): \
        QMAKE_SONAME_PREFIX = @rpath
+   else: \
+       CONFIG += absolute_library_soname
 }
 
 DEFINES += QT_BUILDING_QT
diff --git a/mkspecs/features/qt_module_pris.prf b/mkspecs/features/qt_module_pris.prf
index fdcb9df270506a999c610443dde16a236924021a..5f5639a1cf83aca62a935fe10ed2acb59b585946 100644
--- a/mkspecs/features/qt_module_pris.prf
+++ b/mkspecs/features/qt_module_pris.prf
@@ -46,18 +46,22 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
         module_rundep = "QT.$${MODULE_ID}.run_depends = $$replace(QT_PRIVATE, -private$, _private)"
     else: \
         module_rundep =
+    module_build_type = v2
     static: \
-        module_build_type = staticlib
-    else: lib_bundle: \
-        module_build_type = lib_bundle
-    else: \
-        module_build_type =
-    equals(TEMPLATE, aux): \
-        module_build_type += no_link
+        module_build_type += staticlib
+    lib_bundle {
+        module_build_type += lib_bundle
+        MODULE_FRAMEWORKS = " \$\$QT_MODULE_LIB_BASE"
+    }
     internal_module: \
         module_build_type += internal_module
     ltcg: \
         module_build_type += ltcg
+    module_module =
+    !equals(TEMPLATE, aux) {
+        module_module = $$TARGET$$QT_LIBINFIX
+        !lib_bundle: module_module ~= s,^Qt,Qt$$QT_MAJOR_VERSION,
+    }
     !isEmpty(MODULE_CONFIG): \
         module_config = "QT.$${MODULE_ID}.CONFIG = $$MODULE_CONFIG"
     else: \
@@ -77,9 +81,11 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
         "QT.$${MODULE_ID}.PATCH_VERSION = $$section(VERSION, ., 2, 2)" \
         "" \
         "QT.$${MODULE_ID}.name = $$TARGET" \
+        "QT.$${MODULE_ID}.module = $$module_module" \
         "QT.$${MODULE_ID}.libs = $$module_libs" \
         $$module_master \
-        "QT.$${MODULE_ID}.includes = $$MODULE_INCLUDES"
+        "QT.$${MODULE_ID}.includes = $$MODULE_INCLUDES" \
+        "QT.$${MODULE_ID}.frameworks =$$MODULE_FRAMEWORKS"
     !host_build: MODULE_PRI_CONT += \
         "QT.$${MODULE_ID}.bins = \$\$QT_MODULE_BIN_BASE" \
         "QT.$${MODULE_ID}.libexecs = \$\$QT_MODULE_LIBEXEC_BASE" \
@@ -97,7 +103,11 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
         "QT_MODULES += $$MODULE"
     write_file($$MODULE_PRI, MODULE_PRI_CONT)|error("Aborting.")
     !internal_module:!no_private_module {
-        module_build_type += internal_module no_link
+        module_build_type += internal_module
+        private_deps = $$QT
+        private_deps -= $$MODULE_DEPENDS
+        private_deps += $$MODULE $$QT_FOR_PRIVATE
+        private_deps ~= s,-private$,_private,g
         MODULE_PRIVATE_PRI_CONT = \
             "QT.$${MODULE}_private.VERSION = $${VERSION}" \
             "QT.$${MODULE}_private.MAJOR_VERSION = $$section(VERSION, ., 0, 0)" \
@@ -105,9 +115,11 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
             "QT.$${MODULE}_private.PATCH_VERSION = $$section(VERSION, ., 2, 2)" \
             "" \
             "QT.$${MODULE}_private.name = $${TARGET}" \   # Same name as base module
+            "QT.$${MODULE}_private.module =" \
             "QT.$${MODULE}_private.libs = $$module_libs" \
             "QT.$${MODULE}_private.includes = $$MODULE_PRIVATE_INCLUDES" \
-            "QT.$${MODULE}_private.depends = $$replace($$list($$MODULE $$QT_FOR_PRIVATE), -private$, _private)" \
+            "QT.$${MODULE}_private.frameworks =" \
+            "QT.$${MODULE}_private.depends = $$private_deps" \
             "QT.$${MODULE}_private.module_config =$$join(module_build_type, " ", " ")"
         write_file($$MODULE_PRIVATE_PRI, MODULE_PRIVATE_PRI_CONT)|error("Aborting.")
     }
@@ -169,8 +181,8 @@ MODULE_FWD_PRI = $$mod_work_pfx/qt_lib_$${MODULE_ID}.pri
         include($$mod_work_pfx/qt_lib_$${pri}.pri)
     for(mod, mods_to_load) {
         for(var, $$list(VERSION MAJOR_VERSION MINOR_VERSION PATCH_VERSION \
-                        name depends run_depends plugin_types module_config CONFIG DEFINES \
-                        priority includes bins libs libexecs plugins imports qml \
+                        name module depends run_depends plugin_types module_config CONFIG DEFINES \
+                        priority includes bins libs frameworks libexecs plugins imports qml \
                 )):defined(QT.$${mod}.$$var, var):cache(QT.$${mod}.$$var, transient)
     }
     cache(QT_MODULES, transient)
diff --git a/qmake/generators/mac/pbuilder_pbx.cpp b/qmake/generators/mac/pbuilder_pbx.cpp
index 42dd6c8aeb5075485b6b38fe756e5e5ef47f1779..ef9aa9a2e60f1b77fd83478e736d59fa2577a66a 100644
--- a/qmake/generators/mac/pbuilder_pbx.cpp
+++ b/qmake/generators/mac/pbuilder_pbx.cpp
@@ -498,11 +498,11 @@ static QString xcodeFiletypeForFilename(const QString &filename)
         return QStringLiteral("sourcecode.cpp.objcpp");
     if (filename.endsWith(Option::objc_ext))
         return QStringLiteral("sourcecode.c.objc");
-    if (filename.endsWith(QStringLiteral(".framework")))
+    if (filename.endsWith(QLatin1String(".framework")))
         return QStringLiteral("wrapper.framework");
-    if (filename.endsWith(QStringLiteral(".a")))
+    if (filename.endsWith(QLatin1String(".a")))
         return QStringLiteral("archive.ar");
-    if (filename.endsWith(QStringLiteral(".pro")) || filename.endsWith(QStringLiteral(".qrc")))
+    if (filename.endsWith(QLatin1String(".pro")) || filename.endsWith(QLatin1String(".qrc")))
         return QStringLiteral("text");
 
     return QString();
diff --git a/qmake/generators/makefile.cpp b/qmake/generators/makefile.cpp
index a54083c04d6baafebfbcea2e1629f4b2afdf0276..4dfe69fbde78515658a3c8366dc91d0340da7350 100644
--- a/qmake/generators/makefile.cpp
+++ b/qmake/generators/makefile.cpp
@@ -1212,7 +1212,7 @@ MakefileGenerator::writeInstalls(QTextStream &t, bool noBuild)
         }
 
         bool do_default = true;
-        const QString root = "$(INSTALL_ROOT)";
+        const QString root = installRoot();
         QString dst;
         if (installConfigValues.indexOf("no_path") == -1 &&
             installConfigValues.indexOf("dummy_install") == -1) {
diff --git a/qmake/generators/makefile.h b/qmake/generators/makefile.h
index 97159eaef44c4ff7b72f446b5f9f7bc2f038a51a..19ff5d57a32cfefe094bb59b9f51af4d50b7da48 100644
--- a/qmake/generators/makefile.h
+++ b/qmake/generators/makefile.h
@@ -192,6 +192,7 @@ protected:
 
     //for installs
     virtual QString defaultInstall(const QString &);
+    virtual QString installRoot() const;
 
     //for prl
     QString prlFileName(bool fixify=true);
@@ -277,6 +278,9 @@ inline bool MakefileGenerator::noIO() const
 inline QString MakefileGenerator::defaultInstall(const QString &)
 { return QString(""); }
 
+inline QString MakefileGenerator::installRoot() const
+{ return QStringLiteral("$(INSTALL_ROOT)"); }
+
 inline bool MakefileGenerator::findLibraries(bool, bool)
 { return true; }
 
diff --git a/qmake/generators/unix/unixmake.cpp b/qmake/generators/unix/unixmake.cpp
index 57c0a9722890eb49bf19b6abe02c6a6caf6d0c91..12b9f09edd74c3658a1cd6beeb324f6aec543c89 100644
--- a/qmake/generators/unix/unixmake.cpp
+++ b/qmake/generators/unix/unixmake.cpp
@@ -514,6 +514,20 @@ UnixMakefileGenerator::findLibraries(bool linkPrl, bool mergeLflags)
     return false;
 }
 
+#ifdef Q_OS_WIN // MinGW x-compiling for QNX
+QString UnixMakefileGenerator::installRoot() const
+{
+    /*
+      We include a magic prefix on the path to bypass mingw-make's "helpful"
+      intervention in the environment, recognising variables that look like
+      paths and adding the msys system root as prefix, which we don't want.
+      Once this hack has smuggled INSTALL_ROOT into make's variable space, we
+      can trivially strip the magic prefix back off to get the path we meant.
+     */
+    return QStringLiteral("$(INSTALL_ROOT:@msyshack@%=%)");
+}
+#endif
+
 QString
 UnixMakefileGenerator::defaultInstall(const QString &t)
 {
@@ -522,7 +536,7 @@ UnixMakefileGenerator::defaultInstall(const QString &t)
 
     enum { NoBundle, SolidBundle, SlicedBundle } bundle = NoBundle;
     bool isAux = (project->first("TEMPLATE") == "aux");
-    const QString root = "$(INSTALL_ROOT)";
+    const QString root = installRoot();
     ProStringList &uninst = project->values(ProKey(t + ".uninstall"));
     QString ret, destdir = project->first("DESTDIR").toQString();
     if(!destdir.isEmpty() && destdir.right(1) != Option::dir_sep)
diff --git a/qmake/generators/unix/unixmake.h b/qmake/generators/unix/unixmake.h
index db3f59f517e38619d5d25d158e8d2f608411658d..17270ffce9b2322dd7ee225396c42f79bef3e958 100644
--- a/qmake/generators/unix/unixmake.h
+++ b/qmake/generators/unix/unixmake.h
@@ -52,6 +52,9 @@ public:
 protected:
     virtual bool doPrecompiledHeaders() const { return project->isActiveConfig("precompile_header"); }
     virtual bool doDepends() const { return !Option::mkfile::do_stub_makefile && MakefileGenerator::doDepends(); }
+#ifdef Q_OS_WIN // MinGW x-compiling for QNX
+    virtual QString installRoot() const;
+#endif
     virtual QString defaultInstall(const QString &);
     virtual ProString fixLibFlag(const ProString &lib);
 
diff --git a/qmake/generators/win32/cesdkhandler.cpp b/qmake/generators/win32/cesdkhandler.cpp
index f8235bae279680d1be062037f8e2548adfb0fb74..4550cc8aeddb35dfacfc56b489a2ec75d877efa3 100644
--- a/qmake/generators/win32/cesdkhandler.cpp
+++ b/qmake/generators/win32/cesdkhandler.cpp
@@ -63,8 +63,8 @@ struct ContainsPathKey
 {
     bool operator()(const QString &val) const
     {
-        return !(val.endsWith(QStringLiteral("MSBuildToolsPath"))
-                 || val.endsWith(QStringLiteral("MSBuildToolsRoot")));
+        return !(val.endsWith(QLatin1String("MSBuildToolsPath"))
+                 || val.endsWith(QLatin1String("MSBuildToolsRoot")));
     }
 };
 
@@ -141,7 +141,7 @@ bool CeSdkHandler::parseMsBuildFile(QFile *file, CeSdkInfo *info)
     if (success) {
         const QString startPattern = QStringLiteral("$(Registry:");
         const int startIndex = sdkRootPath.indexOf(startPattern);
-        const int endIndex = sdkRootPath.lastIndexOf(QStringLiteral(")"));
+        const int endIndex = sdkRootPath.lastIndexOf(QLatin1Char(')'));
         const QString regString = sdkRootPath.mid(startIndex + startPattern.size(),
                                                   endIndex - startIndex - startPattern.size());
         QSettings sdkRootPathRegistry(regString, QSettings::NativeFormat);
@@ -180,7 +180,7 @@ QStringList CeSdkHandler::filterMsBuildToolPaths(const QStringList &paths) const
     QStringList result;
     foreach (const QString &path, paths) {
         QDir dirVC110(path);
-        if (path.endsWith(QStringLiteral("bin")))
+        if (path.endsWith(QLatin1String("bin")))
             dirVC110.cdUp();
         QDir dirVC120 = dirVC110;
         if (dirVC110.cd(QStringLiteral("Microsoft.Cpp\\v4.0\\V110\\Platforms")))
@@ -279,7 +279,7 @@ void CeSdkHandler::retrieveWEC2013SDKs()
             if (cpuInfo.properties.isEmpty())
                 continue;
             const PropertyContainer &cpuInfoVal = cpuInfo.properties.first().properties.value(QLatin1String("CpuName"));
-            if (cpuInfoVal.name != QStringLiteral("CpuName"))
+            if (cpuInfoVal.name != QLatin1String("CpuName"))
                 continue;
             const QString SDKName = QStringLiteral("SDK name");
             currentSdk.m_name = currentProperty.properties.value(SDKName).value+
diff --git a/qmake/generators/win32/mingw_make.cpp b/qmake/generators/win32/mingw_make.cpp
index 97bfef88a4d72c3f818b79d9c3f1c630fe686aff..1837c6c0cf5775db1ae9888145ec7c91046bfcb8 100644
--- a/qmake/generators/win32/mingw_make.cpp
+++ b/qmake/generators/win32/mingw_make.cpp
@@ -112,6 +112,18 @@ bool MingwMakefileGenerator::writeMakefile(QTextStream &t)
     return false;
  }
 
+QString MingwMakefileGenerator::installRoot() const
+{
+    /*
+      We include a magic prefix on the path to bypass mingw-make's "helpful"
+      intervention in the environment, recognising variables that look like
+      paths and adding the msys system root as prefix, which we don't want.
+      Once this hack has smuggled INSTALL_ROOT into make's variable space, we
+      can trivially strip the magic prefix back off to get the path we meant.
+     */
+    return QStringLiteral("$(INSTALL_ROOT:@msyshack@%=%)");
+}
+
 void createLdObjectScriptFile(const QString &fileName, const ProStringList &objList)
 {
     QString filePath = Option::output_dir + QDir::separator() + fileName;
diff --git a/qmake/generators/win32/mingw_make.h b/qmake/generators/win32/mingw_make.h
index 4e94a23ae20f599fef496569b609787a1e6b2300..1525f04955b79257ea2990ff65c6c1cd35688a96 100644
--- a/qmake/generators/win32/mingw_make.h
+++ b/qmake/generators/win32/mingw_make.h
@@ -50,6 +50,7 @@ protected:
     virtual QString getManifestFileForRcFile() const;
     bool writeMakefile(QTextStream &);
     void init();
+    virtual QString installRoot() const;
 private:
     void writeMingwParts(QTextStream &);
     void writeIncPart(QTextStream &t);
diff --git a/qmake/generators/win32/msbuild_objectmodel.cpp b/qmake/generators/win32/msbuild_objectmodel.cpp
index 8e2be589cdd19f839cb5eab00b9bd93165a1c088..bcfab80ccf1fd1729311263bfea073bd681d91ae 100644
--- a/qmake/generators/win32/msbuild_objectmodel.cpp
+++ b/qmake/generators/win32/msbuild_objectmodel.cpp
@@ -608,8 +608,8 @@ void VCXProjectWriter::write(XmlOutput &xml, VCProject &tool)
 
     xml.setIndentString("  ");
 
-    const QString toolsVersion = (tool.SdkVersion == QStringLiteral("10.0")) ? QStringLiteral("14.0")
-                                                                             : QStringLiteral("4.0");
+    const QString toolsVersion = (tool.SdkVersion == QLatin1String("10.0")) ? QStringLiteral("14.0")
+                                                                            : QStringLiteral("4.0");
 
     xml << decl("1.0", "utf-8")
         << tag("Project")
diff --git a/qmake/generators/win32/msvc_nmake.cpp b/qmake/generators/win32/msvc_nmake.cpp
index 06c99b6e38a100d623ef90767902c1da5ee6c139..27427db68bde6b6d7d0042902307b9b2c2a7b7d2 100644
--- a/qmake/generators/win32/msvc_nmake.cpp
+++ b/qmake/generators/win32/msvc_nmake.cpp
@@ -110,10 +110,10 @@ NmakeMakefileGenerator::writeMakefile(QTextStream &t)
                 QString arch = project->first("VCPROJ_ARCH").toQString().toLower();
                 QString compiler;
                 QString compilerArch;
-                if (arch == QStringLiteral("arm")) {
+                if (arch == QLatin1String("arm")) {
                     compiler = QStringLiteral("x86_arm");
                     compilerArch = QStringLiteral("arm");
-                } else if (arch == QStringLiteral("x64")) {
+                } else if (arch == QLatin1String("x64")) {
                     const ProStringList hostArch = project->values("QMAKE_TARGET.arch");
                     if (hostArch.contains("x86_64"))
                         compiler = QStringLiteral("amd64");
@@ -193,6 +193,9 @@ NmakeMakefileGenerator::writeMakefile(QTextStream &t)
                     incDirs << crtInclude + QStringLiteral("/shared");
                     incDirs << crtInclude + QStringLiteral("/winrt");
 
+                    incDirs << kitDir + QStringLiteral("Extension SDKs/WindowsMobile/")
+                                      + crtVersion + QStringLiteral("/Include/WinRT");
+
                     libDirs << vcInstallDir + QStringLiteral("lib/store/") + compilerArch;
                     libDirs << vcInstallDir + QStringLiteral("atlmfc/lib") + compilerArch;
 
@@ -265,7 +268,7 @@ QString NmakeMakefileGenerator::defaultInstall(const QString &t)
 
     QString ret = Win32MakefileGenerator::defaultInstall(t);
 
-    const QString root = "$(INSTALL_ROOT)";
+    const QString root = installRoot();
     ProStringList &uninst = project->values(ProKey(t + ".uninstall"));
     QString targetdir = fileFixify(project->first(ProKey(t + ".path")).toQString(), FileFixifyAbsolute);
     if(targetdir.right(1) != Option::dir_sep)
diff --git a/qmake/generators/win32/msvc_objectmodel.cpp b/qmake/generators/win32/msvc_objectmodel.cpp
index 18457ac5ad3db2b5d9f5039a4cc046e86d6d511c..f26dbbc40b8b74a78615649540d4c7e61a29bb49 100644
--- a/qmake/generators/win32/msvc_objectmodel.cpp
+++ b/qmake/generators/win32/msvc_objectmodel.cpp
@@ -2196,7 +2196,7 @@ void VCFilter::modifyPCHstage(QString str)
             break;
         }
     }
-    bool isHFile = Option::hasFileExtension(str, Option::h_ext) && (str == Project->precompH);
+    const bool isHFile = (str == Project->precompH);
     bool isCPPFile = pchThroughSourceFile && (str == Project->precompCPP);
 
     if(!isCFile && !isHFile && !isCPPFile)
diff --git a/qmake/generators/win32/msvc_vcproj.cpp b/qmake/generators/win32/msvc_vcproj.cpp
index 465c8fc31295896dffdd065579306ec0b1cc8b05..a1a8407a11c6fec61a336507db2d9e04ceb299a8 100644
--- a/qmake/generators/win32/msvc_vcproj.cpp
+++ b/qmake/generators/win32/msvc_vcproj.cpp
@@ -1199,7 +1199,7 @@ void VcprojGenerator::initResourceTool()
     foreach (const ProString &path, project->values("RC_INCLUDEPATH")) {
         QString fixedPath = fileFixify(path.toQString());
         if (fileInfo(fixedPath).isRelative()) {
-            if (fixedPath == QStringLiteral("."))
+            if (fixedPath == QLatin1String("."))
                 fixedPath = QStringLiteral("$(ProjectDir)");
             else
                 fixedPath.prepend(QStringLiteral("$(ProjectDir)\\"));
@@ -1334,7 +1334,7 @@ void VcprojGenerator::initDeploymentTool()
                     if (!vcInstallDir.isEmpty()) {
                         vcInstallDir += "\\ce\\dll\\";
                         vcInstallDir += project->values("CE_ARCH").join(QLatin1Char(' '));
-                        if (!QFileInfo(vcInstallDir + QDir::separator() + runtimeVersion).exists())
+                        if (!QFileInfo::exists(vcInstallDir + QDir::separator() + runtimeVersion))
                             runtime.clear();
                         else
                             runtime = vcInstallDir;
diff --git a/qmake/generators/win32/winmakefile.cpp b/qmake/generators/win32/winmakefile.cpp
index 1fba7057ab80664bb365d645c4fbf559c0fc154e..a042cb0d4b3a893d5324af25b83d39be10fb9f90 100644
--- a/qmake/generators/win32/winmakefile.cpp
+++ b/qmake/generators/win32/winmakefile.cpp
@@ -689,7 +689,7 @@ QString Win32MakefileGenerator::defaultInstall(const QString &t)
         project->first("TEMPLATE") == "subdirs" || project->first("TEMPLATE") == "aux")
        return QString();
 
-    const QString root = "$(INSTALL_ROOT)";
+    const QString root = installRoot();
     ProStringList &uninst = project->values(ProKey(t + ".uninstall"));
     QString ret;
     QString targetdir = fileFixify(project->first(ProKey(t + ".path")).toQString(), FileFixifyAbsolute);
diff --git a/qmake/library/qmakeevaluator.cpp b/qmake/library/qmakeevaluator.cpp
index 4c5ce2e097859d8982891ec408cde9747b620d79..e9da45c14d2ebc7a3f5a1fc94756986eb383c33b 100644
--- a/qmake/library/qmakeevaluator.cpp
+++ b/qmake/library/qmakeevaluator.cpp
@@ -957,7 +957,7 @@ static ProString msvcBinDirToQMakeArch(QString subdir)
     if (idx >= 0)
         subdir.remove(0, idx + 1);
     subdir = subdir.toLower();
-    if (subdir == QStringLiteral("amd64"))
+    if (subdir == QLatin1String("amd64"))
         return ProString("x86_64");
     return ProString(subdir);
 }
diff --git a/qmake/main.cpp b/qmake/main.cpp
index bde537dcca5642324d5f44476a475d68e2ef4a95..5f848d482047ca5fabf4c52ff4affb849bf499de 100644
--- a/qmake/main.cpp
+++ b/qmake/main.cpp
@@ -309,8 +309,8 @@ int runQMake(int argc, char **argv)
                 dir = tmp_dir;
         }
 #ifdef Q_OS_MAC
-        if (fi.fileName().endsWith(QStringLiteral(".pbxproj"))
-            && dir.endsWith(QStringLiteral(".xcodeproj")))
+        if (fi.fileName().endsWith(QLatin1String(".pbxproj"))
+            && dir.endsWith(QLatin1String(".xcodeproj")))
             dir += QStringLiteral("/..");
 #endif
         if(!dir.isNull() && dir != ".")
diff --git a/src/3rdparty/dbus-ifaces/org.kde.StatusNotifierItem.xml b/src/3rdparty/dbus-ifaces/org.kde.StatusNotifierItem.xml
index aeeb42fa87804c7103fa73d3ae30b2b8dd344dec..1cbd78a9c383969c38de3af201c4f4544e622874 100644
--- a/src/3rdparty/dbus-ifaces/org.kde.StatusNotifierItem.xml
+++ b/src/3rdparty/dbus-ifaces/org.kde.StatusNotifierItem.xml
@@ -19,13 +19,13 @@
     <property name="IconName" type="s" access="read"/>
 
     <!--struct containing width, height and image data-->
-    <property name="IconPixmap" type="(iiay)" access="read">
+    <property name="IconPixmap" type="a(iiay)" access="read">
       <annotation name="org.qtproject.QtDBus.QtTypeName" value="QXdgDBusImageVector"/>
     </property>
 
     <property name="OverlayIconName" type="s" access="read"/>
 
-    <property name="OverlayIconPixmap" type="(iiay)" access="read">
+    <property name="OverlayIconPixmap" type="a(iiay)" access="read">
       <annotation name="org.qtproject.QtDBus.QtTypeName" value="QXdgDBusImageVector"/>
     </property>
 
@@ -34,7 +34,7 @@
     <property name="AttentionIconName" type="s" access="read"/>
 
     <!--same definition as image-->
-    <property name="AttentionIconPixmap" type="(iiay)" access="read">
+    <property name="AttentionIconPixmap" type="a(iiay)" access="read">
       <annotation name="org.qtproject.QtDBus.QtTypeName" value="QXdgDBusImageVector"/>
     </property>
 
@@ -45,7 +45,7 @@
     <!-- tooltip data -->
 
     <!--(iiay) is an image-->
-    <property name="ToolTip" type="(s(iiay)ss)" access="read">
+    <property name="ToolTip" type="(sa(iiay)ss)" access="read">
       <annotation name="org.qtproject.QtDBus.QtTypeName" value="QXdgDBusToolTipStruct"/>
     </property>
 
diff --git a/src/3rdparty/forkfd/forkfd.c b/src/3rdparty/forkfd/forkfd.c
index 3bf7fc3deb7a1c1a2ed00d46969337d3463e5f13..fef710a79e61210efe46f0d442d521a5c9140a42 100644
--- a/src/3rdparty/forkfd/forkfd.c
+++ b/src/3rdparty/forkfd/forkfd.c
@@ -65,7 +65,7 @@
 #  undef HAVE_WAITID
 #endif
 
-#if defined(__FreeBSD__)
+#if defined(__FreeBSD__) && defined(__FreeBSD_version) && __FreeBSD_version >= 1000032
 #  define HAVE_PIPE2    1
 #endif
 #if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__FreeBSD_kernel__) || \
diff --git a/src/3rdparty/freetype/freetype.pro b/src/3rdparty/freetype/freetype.pro
index e9436febc6b10c452427033499062f18fd6fab81..04aa3b8e18d622e78caabe29f9cdee023a9754e5 100644
--- a/src/3rdparty/freetype/freetype.pro
+++ b/src/3rdparty/freetype/freetype.pro
@@ -3,7 +3,8 @@ TARGET = qtfreetype
 CONFIG += \
     static \
     hide_symbols \
-    exceptions_off rtti_off warn_off
+    exceptions_off rtti_off warn_off \
+    installed
 
 load(qt_helper_lib)
 
diff --git a/src/3rdparty/harfbuzz-ng/harfbuzz-ng.pro b/src/3rdparty/harfbuzz-ng/harfbuzz-ng.pro
index 031f7ecd5870e0e366f37ccf2c1e37ddb6cf5d1f..edfc0e7954d2777d3ad2e317b8be62537d0b7c31 100644
--- a/src/3rdparty/harfbuzz-ng/harfbuzz-ng.pro
+++ b/src/3rdparty/harfbuzz-ng/harfbuzz-ng.pro
@@ -15,6 +15,9 @@ DEFINES += HAVE_ATEXIT
 unix: DEFINES += HAVE_PTHREAD HAVE_SCHED_H HAVE_SCHED_YIELD
 win32: DEFINES += HB_NO_WIN1256
 
+#Workaround https://code.google.com/p/android/issues/detail?id=194631
+android: DEFINES += _POSIX_C_SOURCE=200112L
+
 INCLUDEPATH += $$PWD/include
 INCLUDEPATH += $$QT.core.includes
 
diff --git a/src/3rdparty/libpng/ANNOUNCE b/src/3rdparty/libpng/ANNOUNCE
index 131e0aa369e60446c90802642eea197f766a8f94..9f1b66583422a4e466b5cbcaf3700047c6117301 100644
--- a/src/3rdparty/libpng/ANNOUNCE
+++ b/src/3rdparty/libpng/ANNOUNCE
@@ -1,4 +1,4 @@
-Libpng 1.6.17 - March 26, 2015
+Libpng 1.6.19 - November 12, 2015
 
 This is a public release of libpng, intended for use in production codes.
 
@@ -7,61 +7,104 @@ Files available for download:
 Source files with LF line endings (for Unix/Linux) and with a
 "configure" script
 
-   libpng-1.6.17.tar.xz (LZMA-compressed, recommended)
-   libpng-1.6.17.tar.gz
+   libpng-1.6.19.tar.xz (LZMA-compressed, recommended)
+   libpng-1.6.19.tar.gz
 
 Source files with CRLF line endings (for Windows), without the
 "configure" script
 
-   lpng1617.7z  (LZMA-compressed, recommended)
-   lpng1617.zip
+   lpng1619.7z  (LZMA-compressed, recommended)
+   lpng1619.zip
 
 Other information:
 
-   libpng-1.6.17-README.txt
-   libpng-1.6.17-LICENSE.txt
-   libpng-1.6.17-*.asc (armored detached GPG signatures)
+   libpng-1.6.19-README.txt
+   libpng-1.6.19-LICENSE.txt
+   libpng-1.6.19-*.asc (armored detached GPG signatures)
 
-Changes since the last public release (1.6.16):
+Changes since the last public release (1.6.18):
 
-  Removed duplicate PNG_SAFE_LIMITS_SUPPORTED handling from pngconf.h
-  Corrected the width limit calculation in png_check_IHDR().
-  Removed user limits from pngfix. Also pass NULL pointers to
-    png_read_row to skip the unnecessary row de-interlace stuff.
-  Added testing of png_set_packing() to pngvalid.c
-  Regenerated configure scripts in the *.tar distributions with libtool-2.4.4
-  Implement previously untested cases of libpng transforms in pngvalid.c
-  Fixed byte order in 2-byte filler, in png_do_read_filler().
-  Made the check for out-of-range values in png_set_tRNS() detect
-    values that are exactly 2^bit_depth, and work on 16-bit platforms.
-  Merged some parts of libpng-1.6.17beta01 and libpng-1.7.0beta47.
-  Added #ifndef __COVERITY__ where needed in png.c, pngrutil.c and
-    pngset.c to avoid warnings about dead code.
-  Do not build png_product2() when it is unused.
-  Display user limits in the output from pngtest.
-  Eliminated the PNG_SAFE_LIMITS macro and restored the 1-million-column
-    and 1-million-row default limits in pnglibconf.dfa, that can be reset
-    by the user at build time or run time.  This provides a more robust
-    defense against DOS and as-yet undiscovered overflows.
-  Added PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED macro, on by default.
-  Allow user to call png_get_IHDR() with NULL arguments (Reuben Hawkins).
-  Rebuilt configure scripts with automake-1.15 and libtool-2.4.6
-  Moved png_set_filter() prototype into a PNG_WRITE_SUPPORTED block
-    of png.h.
-  Avoid runtime checks when converting integer to png_byte with
-    Visual Studio (Sergey Kosarevsky)
-  Removed some comments that the configure script did not handle
-    properly from scripts/pnglibconf.dfa and pnglibconf.h.prebuilt.
-  Free the unknown_chunks structure even when it contains no data.
-  Updated CMakeLists.txt to add OSX framework, change YES/NO to ON/OFF
-    for consistency, and remove some useless tests (Alexey Petruchik).
-  Remove pnglibconf.h, pnglibconf.c, pnglibconf.pre, pnglibconf.dfn,
-    and pnglibconf.out instead of pnglibconf.* in "make clean" (Cosmin).
-  Fixed simplified 8-bit-linear to sRGB alpha. The calculated alpha
-    value was wrong.  It's not clear if this affected the final stored
-    value; in the obvious code path the upper and lower 8-bits of the
-    alpha value were identical and the alpha was truncated to 8-bits
-    rather than dividing by 257 (John Bowler).
+  Updated obsolete information about the simplified API macros in the
+    manual pages (Bug report by Arc Riley).
+  Avoid potentially dereferencing NULL info_ptr in png_info_init_3().
+  Rearranged png.h to put the major sections in the same order as
+    in libpng17.
+  Eliminated unused PNG_COST_SHIFT, PNG_WEIGHT_SHIFT, PNG_COST_FACTOR, and
+    PNG_WEIGHT_FACTOR macros.
+  Suppressed some warnings from the Borland C++ 5.5.1/5.82 compiler
+    (Bug report by Viktor Szakats).  Several warnings remain and are
+    unavoidable, where we test for overflow.
+  Fixed potential leak of png_pixels in contrib/pngminus/pnm2png.c
+  Fixed uninitialized variable in contrib/gregbook/rpng2-x.c
+  Moved config.h.in~ from the "libpng_autotools_files" list to the
+    "libpng_autotools_extra" list in autogen.sh because it was causing a
+    false positive for missing files (bug report by Robert C. Seacord).
+  Removed unreachable "break" statements in png.c, pngread.c, and pngrtran.c
+    to suppress clang warnings (Bug report by Viktor Szakats).
+  Fixed some bad links in the man page.
+  Changed "n bit" to "n-bit" in comments.
+  Added signed/unsigned 16-bit safety net. This removes the dubious
+    0x8000 flag definitions on 16-bit systems. They aren't supported
+    yet the defs *probably* work, however it seems much safer to do this
+    and be advised if anyone, contrary to advice, is building libpng 1.6
+    on a 16-bit system. It also adds back various switch default clauses
+    for GCC; GCC errors out if they are not present (with an appropriately
+    high level of warnings).
+  Safely convert num_bytes to a png_byte in png_set_sig_bytes() (Robert
+    Seacord).
+  Fixed the recently reported 1's complement security issue by replacing
+    the value that is illegal in the PNG spec, in both signed and unsigned
+    values, with 0. Illegal unsigned values (anything greater than or equal
+    to  0x80000000) can still pass through, but since these are not illegal
+    in ANSI-C (unlike 0x80000000 in the signed case) the checking that
+    occurs later can catch them (John Bowler).
+  Fixed png_save_int_32 when int is not 2's complement (John Bowler).
+  Updated libpng16 with all the recent test changes from libpng17,
+    including changes to pngvalid.c to ensure that the original,
+    distributed, version of contrib/visupng/cexcept.h can be used
+    (John Bowler).
+  pngvalid contains the correction to the use of SAVE/STORE_
+    UNKNOWN_CHUNKS; a bug revealed by changes in libpng 1.7. More
+    tests contain the --strict option to detect warnings and the
+    pngvalid-standard test has been corrected so that it does not
+    turn on progressive-read. There is a separate test which does
+    that. (John Bowler)
+  Also made some signed/unsigned fixes.
+  Make pngstest error limits version specific. Splitting the machine
+    generated error structs out to a file allows the values to be updated
+    without changing pngstest.c itself. Since libpng 1.6 and 1.7 have
+    slightly different error limits this simplifies maintenance. The
+    makepngs.sh script has also been updated to more accurately reflect
+    current problems in libpng 1.7 (John Bowler).
+  Incorporated new test PNG files into make check.  tests/pngstest-*
+    are changed so that the new test files are divided into 8 groups by
+    gamma and alpha channel.  These tests have considerably better code
+    and pixel-value coverage than contrib/pngsuite; however,coverage is
+    still incomplete (John Bowler).
+  Removed the '--strict' in 1.6 because of the double-gamma-correction
+    warning, updated pngstest-errors.h for the errors detected with the
+    new contrib/testspngs PNG test files (John Bowler).
+  Worked around rgb-to-gray issues in libpng 1.6.  The previous
+    attempts to ignore the errors in the code aren't quite enough to
+    deal with the 'channel selection' encoding added to libpng 1.7; abort.
+  Fixed 'pow' macros in pngvalid.c. It is legal for 'pow' to be a
+    macro, therefore the argument list cannot contain preprocessing
+    directives.  Make sure pow is a function where this happens. This is
+    a minimal safe fix, the issue only arises in non-performance-critical
+    code (bug report by Curtis Leach, fix by John Bowler).
+  Added sPLT support to pngtest.c
+  Prevent setting or writing over-length PLTE chunk (Cosmin Truta).
+  Silently truncate over-length PLTE chunk while reading.
+  Libpng incorrectly calculated the output rowbytes when the application
+    decreased either the number of channels or the bit depth (or both) in
+    a user transform.  This was safe; libpng overallocated buffer space
+   (potentially by quite a lot; up to 4 times the amount required) but,
+   from 1.5.4 on, resulted in a png_error (John Bowler).
+  Fixed some inconsequential cut-and-paste typos in png_set_cHRM_XYZ_fixed().
+  Clarified COPYRIGHT information to state explicitly that versions
+    are derived from previous versions.
+  Removed much of the long list of previous versions from png.h and
+    libpng.3.
 
 Send comments/corrections/commendations to png-mng-implement at lists.sf.net
 (subscription required; visit
diff --git a/src/3rdparty/libpng/CHANGES b/src/3rdparty/libpng/CHANGES
index 1be09e93856385614e7757e0d68dd50d54ee0fae..2e4d2bb292c6096ed2f5707df6da5b3b9cc9bc73 100644
--- a/src/3rdparty/libpng/CHANGES
+++ b/src/3rdparty/libpng/CHANGES
@@ -1,11 +1,14 @@
-
+#if 0
 CHANGES - changes for libpng
 
-Version 0.2
+version 0.1 [March 29, 1995]
+  initial work-in-progress release
+
+version 0.2 [April 1, 1995]
   added reader into png.h
   fixed small problems in stub file
 
-Version 0.3
+version 0.3 [April 8, 1995]
   added pull reader
   split up pngwrite.c to several files
   added pnglib.txt
@@ -14,9 +17,9 @@ Version 0.3
   fixed some bugs in writer
   interfaced with zlib 0.5
   added K&R support
-  added check for 64 KB blocks for 16-bit machines
+  added check for 64 KB blocks for 16 bit machines
 
-Version 0.4
+version 0.4 [April 26, 1995]
   cleaned up code and commented code
   simplified time handling into png_time
   created png_color_16 and png_color_8 to handle color needs
@@ -27,28 +30,29 @@ Version 0.4
   cleaned up zTXt reader and writer (using zlib's Reset functions)
   split transformations into pngrtran.c and pngwtran.c
 
-Version 0.5
+version 0.5 [April 30, 1995]
   interfaced with zlib 0.8
   fixed many reading and writing bugs
   saved using 3 spaces instead of tabs
 
-Version 0.6
+version 0.6 [May 1, 1995]
+  first beta release
   added png_large_malloc() and png_large_free()
   added png_size_t
   cleaned up some compiler warnings
   added png_start_read_image()
 
-Version 0.7
+version 0.7 [June 24, 1995]
   cleaned up lots of bugs
   finished dithering and other stuff
   added test program
   changed name from pnglib to libpng
 
-Version 0.71 [June, 1995]
+version 0.71 [June 26, 1995]
   changed pngtest.png for zlib 0.93
   fixed error in libpng.txt and example.c
 
-Version 0.8
+version 0.8 [August 20, 1995]
   cleaned up some bugs
   added png_set_filler()
   split up pngstub.c into pngmem.c, pngio.c, and pngerror.c
@@ -91,7 +95,7 @@ Version 0.88 [January, 1996]
   cleaned up documentation
   added callbacks for read/write and warning/error functions
 
-Version 0.89 [July, 1996]
+Version 0.89 [June 5, 1996]
   Added new initialization API to make libpng work better with shared libs
     we now have png_create_read_struct(), png_create_write_struct(),
     png_create_info_struct(), png_destroy_read_struct(), and
@@ -118,6 +122,9 @@ Version 0.89 [July, 1996]
   New pngtest image also has interlacing and zTXt
   Updated documentation to reflect new API
 
+Version 0.89c [June 17, 1996]
+  Bug fixes.
+
 Version 0.90 [January, 1997]
   Made CRC errors/warnings on critical and ancillary chunks configurable
   libpng will use the zlib CRC routines by (compile-time) default
@@ -158,7 +165,7 @@ Version 0.95 [March, 1997]
   Added new pCAL chunk read/write support
   Added experimental filter selection weighting (Greg Roelofs)
   Removed old png_set_rgbx() and png_set_xrgb() functions that have been
-     obsolete for about 2 years now (use png_set_filler() instead)
+    obsolete for about 2 years now (use png_set_filler() instead)
   Added macros to read 16- and 32-bit ints directly from buffer, to be
     used only on those systems that support it (namely PowerPC and 680x0)
     With some testing, this may become the default for MACOS/PPC systems.
@@ -440,7 +447,7 @@ Version 1.0.3 [January 14, 1999]
 
 Version 1.0.3a [August 12, 1999]
   Added check for PNG_READ_INTERLACE_SUPPORTED in pngread.c; issue a warning
-     if an attempt is made to read an interlaced image when it's not supported.
+    if an attempt is made to read an interlaced image when it's not supported.
   Added check if png_ptr->trans is defined before freeing it in pngread.c
   Modified the Y2K statement to include versions back to version 0.71
   Fixed a bug in the check for valid IHDR bit_depth/color_types in pngrutil.c
@@ -448,7 +455,7 @@ Version 1.0.3a [August 12, 1999]
   Replaced leading blanks with tab characters in makefile.hux
   Changed "dworkin.wustl.edu" to "ccrc.wustl.edu" in various documents.
   Changed (float)red and (float)green to (double)red, (double)green
-     in png_set_rgb_to_gray() to avoid "promotion" problems in AIX.
+    in png_set_rgb_to_gray() to avoid "promotion" problems in AIX.
   Fixed a bug in pngconf.h that omitted <stdio.h> when PNG_DEBUG==0 (K Bracey).
   Reformatted libpng.3 and libpngpf.3 with proper fonts (script by J. vanZandt).
   Updated documentation to refer to the PNG-1.2 specification.
@@ -491,7 +498,7 @@ Version 1.0.3d [September 4, 1999]
   Added new png_expand functions to scripts/pngdef.pas and pngos2.def
   Added a demo read_user_transform_fn that examines the row filters in pngtest.c
 
-Version 1.0.4 [September 24, 1999]
+Version 1.0.4 [September 24, 1999, not distributed publicly]
   Define PNG_ALWAYS_EXTERN in pngconf.h if __STDC__ is defined
   Delete #define PNG_INTERNAL and include "png.h" from pngasmrd.h
   Made several minor corrections to pngtest.c
@@ -518,6 +525,7 @@ Version 1.0.4c [October 1, 1999]
   Added a "png_check_version" function in png.c and pngtest.c that will generate
     a helpful compiler error if an old png.h is found in the search path.
   Changed type of png_user_transform_depth|channels from int to png_byte.
+  Added "Libpng is OSI Certified Open Source Software" statement to png.h
 
 Version 1.0.4d [October 6, 1999]
   Changed 0.45 to 0.45455 in png_set_sRGB()
@@ -904,7 +912,7 @@ Version 1.0.7 [July 1, 2000]
 Version 1.0.8beta1 [July 8, 2000]
   Added png_free(png_ptr, key) two places in pngpread.c to stop memory leaks.
   Changed PNG_NO_STDIO to PNG_NO_CONSOLE_IO, several places in pngrutil.c and
-     pngwutil.c.
+    pngwutil.c.
   Changed PNG_EXPORT_VAR to use PNG_IMPEXP, in pngconf.h.
   Removed unused "#include <assert.h>" from png.c
   Added WindowsCE support.
@@ -912,12 +920,12 @@ Version 1.0.8beta1 [July 8, 2000]
 
 Version 1.0.8beta2 [July 10, 2000]
   Added project files to the wince directory and made further revisions
-     of pngtest.c, pngrio.c, and pngwio.c in support of WindowsCE.
+    of pngtest.c, pngrio.c, and pngwio.c in support of WindowsCE.
 
 Version 1.0.8beta3 [July 11, 2000]
   Only set the PNG_FLAG_FREE_TRNS or PNG_FREE_TRNS flag in png_handle_tRNS()
-     for indexed-color input files to avoid potential double-freeing trans array
-     under some unusual conditions; problem was introduced in version 1.0.6f.
+    for indexed-color input files to avoid potential double-freeing trans array
+    under some unusual conditions; problem was introduced in version 1.0.6f.
   Further revisions to pngtest.c and files in the wince subdirectory.
 
 Version 1.0.8beta4 [July 14, 2000]
@@ -1089,16 +1097,16 @@ Version 1.2.0beta3 [May 17, 2001]
 
 Version 1.2.0beta4 [June 23, 2001]
   Check for missing profile length field in iCCP chunk and free chunk_data
-     in case of truncated iCCP chunk.
+    in case of truncated iCCP chunk.
   Bumped shared-library number to 3 in makefile.sgi and makefile.sggcc
   Bumped dll-number from 2 to 3 in makefile.cygwin
   Revised contrib/gregbook/rpng*-x.c to avoid a memory leak and to exit cleanly
-     if user attempts to run it on an 8-bit display.
+    if user attempts to run it on an 8-bit display.
   Updated contrib/gregbook
   Use png_malloc instead of png_zalloc to allocate palette in pngset.c
   Updated makefile.ibmc
   Added some typecasts to eliminate gcc 3.0 warnings.  Changed prototypes
-     of png_write_oFFS width and height from png_uint_32 to png_int_32.
+    of png_write_oFFS width and height from png_uint_32 to png_int_32.
   Updated example.c
   Revised prototypes for png_debug_malloc and png_debug_free in pngtest.c
 
@@ -1106,9 +1114,9 @@ Version 1.2.0beta5 [August 8, 2001]
   Revised contrib/gregbook
   Revised makefile.gcmmx
   Revised pnggccrd.c to conditionally compile some thread-unsafe code only
-     when PNG_THREAD_UNSAFE_OK is defined.
+    when PNG_THREAD_UNSAFE_OK is defined.
   Added tests to prevent pngwutil.c from writing a bKGD or tRNS chunk with
-     value exceeding 2^bit_depth-1
+    value exceeding 2^bit_depth-1
   Revised makefile.sgi and makefile.sggcc
   Replaced calls to fprintf(stderr,...) with png_warning() in pnggccrd.c
   Removed restriction that do_invert_mono only operate on 1-bit opaque files
@@ -1449,8 +1457,9 @@ Version 1.2.6beta4 [July 28, 2004]
   Use png_malloc instead of png_zalloc to allocate the pallete.
 
 Version 1.0.16rc1 and 1.2.6rc1 [August 4, 2004]
-  Fixed buffer overflow vulnerability in png_handle_tRNS()
-  Fixed integer arithmetic overflow vulnerability in png_read_png().
+  Fixed buffer overflow vulnerability (CVE-2004-0597) in png_handle_tRNS().
+  Fixed NULL dereference vulnerability (CVE-2004-0598) in png_handle_iCCP().
+  Fixed integer overflow vulnerability (CVE-2004-0599) in png_read_png().
   Fixed some harmless bugs in png_handle_sBIT, etc, that would cause
     duplicate chunk types to go undetected.
   Fixed some timestamps in the -config version
@@ -1493,7 +1502,7 @@ Version 1.0.16rc4 and 1.2.6rc4 [August 10, 2004]
 
 Version 1.0.16rc5 and 1.2.6rc5 [August 10, 2004]
   Moved  "PNG_HANDLE_CHUNK_*" macros out of PNG_ASSEMBLER_CODE_SUPPORTED
-     section of png.h where they were inadvertently placed in version rc3.
+    section of png.h where they were inadvertently placed in version rc3.
 
 Version 1.2.6 and 1.0.16 [August 15, 2004]
   Revised pngtest so memory allocation testing is only done when PNG_DEBUG==1.
@@ -2325,7 +2334,7 @@ Version 1.4.0beta63 [June 15, 2009]
 Version 1.4.0beta64 [June 24, 2009]
   Eliminated PNG_LEGACY_SUPPORTED code.
   Moved the various unknown chunk macro definitions outside of the
-     PNG_READ|WRITE_ANCILLARY_CHUNK_SUPPORTED blocks.
+    PNG_READ|WRITE_ANCILLARY_CHUNK_SUPPORTED blocks.
 
 Version 1.4.0beta65 [June 26, 2009]
   Added a reference to the libpng license in each file.
@@ -3747,8 +3756,9 @@ Version 1.5.7beta04 [November 17, 2011]
 
 Version 1.5.7beta05 [November 25, 2011]
   Removed "zTXt" from warning in generic chunk decompression function.
-  Validate time settings passed to pngset() and png_convert_to_rfc1123()
-    (Frank Busse).
+  Validate time settings passed to png_set_tIME() and png_convert_to_rfc1123()
+    (Frank Busse). Note: This prevented CVE-2015-7981 from affecting
+    libpng-1.5.7 and later.
   Added MINGW support to CMakeLists.txt
   Reject invalid compression flag or method when reading the iTXt chunk.
   Backed out 'simplified' API changes. The API seems too complex and there
@@ -3794,12 +3804,13 @@ Version 1.6.0beta01 [December 15, 2011]
     (the other two required headers aren't used).  Non-ANSI systems that don't
     have stddef.h or limits.h will have to provide an appropriate fake
     containing the relevant types and #defines.
-  The use of FAR/far has been eliminated and the definition of png_alloc_size_t
-    is now controlled by a flag so that 'small size_t' systems can select it
-    if necessary.  Libpng 1.6 may not currently work on such systems -- it
-    seems likely that it will ask 'malloc' for more than 65535 bytes with any
-    image that has a sufficiently large row size (rather than simply failing
-    to read such images).
+  Dropped support for 16-bit platforms. The use of FAR/far has been eliminated
+    and the definition of png_alloc_size_t is now controlled by a flag so
+    that 'small size_t' systems can select it if necessary.  Libpng 1.6 may
+    not currently work on such systems -- it seems likely that it will
+    ask 'malloc' for more than 65535 bytes with any image that has a
+    sufficiently large row size (rather than simply failing to read such
+    images).
   New tools directory containing tools used to generate libpng code.
   Fixed race conditions in parallel make builds. With higher degrees of
     parallelism during 'make' the use of the same temporary file names such
@@ -4411,7 +4422,7 @@ Version 1.6.1beta02 [February 19, 2013]
 
 Version 1.6.1beta03 [February 22, 2013]
   Fixed ALIGNED_MEMORY support.
-  Allow run-time ARM NEON checking to be disabled. A new configure option:
+  Added a new configure option:
     --enable-arm-neon=always will stop the run-time checks. New checks
     within arm/arm_init.c will cause the code not to be compiled unless
     __ARM_NEON__ is set. This should make it fail safe (if someone asks
@@ -4430,10 +4441,10 @@ Version 1.6.1beta05 [March 1, 2013]
 Version 1.6.1beta06 [March 4, 2013]
   Better documentation of unknown handling API interactions.
   Corrected Android builds and corrected libpng.vers with symbol
-    prefixing. This adds an API to set optimization options externally,
+    prefixing.  It also makes those tests compile and link on Android.
+  Added an API png_set_option() to set optimization options externally,
     providing an alternative and general solution for the non-portable
-    run-time tests used by the ARM Neon code.  It also makes those tests
-    compile and link on Android.
+    run-time tests used by the ARM Neon code, using the PNG_ARM_NEON option.
   The order of settings vs options in pnglibconf.h is reversed to allow
     settings to depend on options and options can now set (or override) the
     defaults for settings.
@@ -4525,13 +4536,14 @@ Version 1.6.3beta03 [April 30, 2013]
   Expanded manual paragraph about writing private chunks, particularly
     the need to call png_set_keep_unknown_chunks() when writing them.
   Avoid dereferencing NULL pointer possibly returned from
-     png_create_write_struct() (Andrew Church).
+    png_create_write_struct() (Andrew Church).
 
 Version 1.6.3beta05 [May 9, 2013]
   Calculate our own zlib windowBits when decoding rather than trusting the
     CMF bytes in the PNG datastream.
   Added an option to force maximum window size for inflating, which was
-    the behavior of libpng15 and earlier.
+    the behavior of libpng15 and earlier, via a new PNG_MAXIMUM_INFLATE_WINDOW
+    option for png_set_options().
   Added png-fix-itxt and png-fix-too-far-back to the built programs and
     removed warnings from the source code and timepng that are revealed as
     a result.
@@ -5134,14 +5146,16 @@ Version 1.6.17beta01 [January 29, 2015]
   Added testing of png_set_packing() to pngvalid.c
   Regenerated configure scripts in the *.tar distributions with libtool-2.4.4
   Implement previously untested cases of libpng transforms in pngvalid.c
-  Fixed byte order in 2-byte filler, in png_do_read_filler().
+  Fixed byte order in png_do_read_filler() with 16-bit input. Previously
+    the high and low bytes of the filler, from png_set_filler() or from
+    png_set_add_alpha(), were read in the wrong order.
   Made the check for out-of-range values in png_set_tRNS() detect
     values that are exactly 2^bit_depth, and work on 16-bit platforms.
   Merged some parts of libpng-1.6.17beta01 and libpng-1.7.0beta47.
   Added #ifndef __COVERITY__ where needed in png.c, pngrutil.c and
     pngset.c to avoid warnings about dead code.
   Added "& 0xff" to many instances of expressions that are typecast
-    to (png_byte), to avoid Coverity gripes.
+    to (png_byte), to avoid Coverity warnings.
 
 Version 1.6.17beta02 [February 7, 2015]
   Work around one more Coverity-scan dead-code warning.
@@ -5205,6 +5219,201 @@ Version 1.6.17rc06 [March 23, 2015]
 Version 1.6.17 [March 26, 2015]
   No changes.
 
+Version 1.6.18beta01 [April 1, 2015]
+  Removed PNG_SET_CHUNK_[CACHE|MALLOC]_LIMIT_SUPPORTED macros.  They
+    have been combined with PNG_SET_USER_LIMITS_SUPPORTED (resolves
+    bug report by Andrew Church).
+  Fixed rgb_to_gray checks and added tRNS checks to pngvalid.c.  This
+    fixes some arithmetic errors that caused some tests to fail on
+    some 32-bit platforms (Bug reports by Peter Breitenlohner [i686]
+    and Petr Gajdos [i586]).
+
+Version 1.6.18beta02 [April 26, 2015]
+  Suppressed some warnings from the Borland C++ 5.5.1/5.82 compiler
+    (Bug report by Viktor Szakats).
+
+Version 1.6.18beta03 [May 6, 2015]
+  Replaced "unexpected" with an integer (0xabadca11) in pngset.c
+    where a long was expected, to avoid a compiler warning when PNG_DEBUG > 1.
+  Added contrib/examples/simpleover.c, to demonstrate how to handle
+    alpha compositing of multiple images, using the "simplified API"
+    and an example PNG generation tool, contrib/examples/genpng.c
+    (John Bowler).
+
+Version 1.6.18beta04 [May 20, 2015]
+  PNG_RELEASE_BUILD replaces tests where the code depended on the build base
+    type and can be defined on the command line, allowing testing in beta
+    builds (John Bowler).
+  Avoid Coverity issue 80858 (REVERSE NULL) in pngtest.c PNG_DEBUG builds.
+  Avoid a harmless potential integer overflow in png_XYZ_from_xy() (Bug
+    report from Christopher Ferris).
+
+Version 1.6.18beta05 [May 31, 2015]
+  Backport filter selection code from libpng-1.7.0beta51, to combine
+    sub_row, up_row, avg_row, and paeth_row into try_row and tst_row.
+  Changed png_voidcast(), etc., to voidcast(), etc., in contrib/tools/pngfix.c
+    to avoid confusion with the libpng private macros.
+  Fixed old cut&paste bug in the weighted filter selection code in
+    pngwutil.c, introduced in libpng-0.95, March 1997.
+
+Version 1.6.18beta06 [June 1, 2015]
+  Removed WRITE_WEIGHTED_FILTERED code, to save a few kbytes of the
+    compiled library size. It never worked properly and as far as we can
+    tell, no one uses it. The png_set_filter_heuristics() and
+    png_set_filter_heuristics_fixed() APIs are retained but deprecated
+    and do nothing.
+
+Version 1.6.18beta07 [June 6, 2015]
+  Removed non-working progressive reader 'skip' function. This
+    function has apparently never been used. It was implemented
+    to support back-door modification of png_struct in libpng-1.4.x
+    but (because it does nothing and cannot do anything) was apparently
+    never tested (John Bowler).
+  Fixed cexcept.h in which GCC 5 now reports that one of the auto
+    variables in the Try macro needs to be volatile to prevent value
+    being lost over the setjmp (John Bowler).
+  Fixed NO_WRITE_FILTER and -Wconversion build breaks (John Bowler).
+  Fix g++ build breaks (John Bowler).
+  Quieted some Coverity issues in pngfix.c, png-fix-itxt.c, pngvalid.c,
+    pngstest.c, and pngimage.c. Most seem harmless, but png-fix-itxt
+    would only work with iTXt chunks with length 255 or less.
+  Added #ifdef's to contrib/examples programs so people don't try
+    to compile them without the minimum required support enabled
+    (suggested by Flavio Medeiros).
+
+Version 1.6.18beta08 [June 30, 2015]
+  Eliminated the final two Coverity defects (insecure temporary file
+    handling in contrib/libtests/pngstest.c; possible overflow of
+    unsigned char in contrib/tools/png-fix-itxt.c). To use the "secure"
+    file handling, define PNG_USE_MKSTEMP, otherwise "tmpfile()" will
+    be used.
+  Removed some unused WEIGHTED_FILTER macros from png.h and pngstruct.h
+
+Version 1.6.18beta09 [July 5, 2015]
+  Removed some useless typecasts from contrib/tools/png-fix-itxt.c
+  Fixed a new signed-unsigned comparison in pngrtran.c (Max Stepin).
+  Replaced arbitrary use of 'extern' with #define PNG_LINKAGE_*.  To
+    preserve API compatibility, the new defines all default to "extern"
+    (requested by Jan Nijtmans).
+
+Version 1.6.18rc01 [July 9, 2015]
+  Belatedly added Mans Rullgard and James Yu to the list of Contributing
+    Authors.
+
+Version 1.6.18rc02 [July 12, 2015]
+  Restored unused FILTER_HEURISTIC macros removed at libpng-1.6.18beta08
+    to png.h to avoid compatibility warnings.
+
+Version 1.6.18rc03 [July 15, 2015]
+  Minor changes to the man page
+
+Version 1.6.18 [July 23, 2015]
+  No changes.
+
+Version 1.6.19beta01 [July 30, 2015]
+  Updated obsolete information about the simplified API macros in the
+    manual pages (Bug report by Arc Riley).
+  Avoid potentially dereferencing NULL info_ptr in png_info_init_3().
+  Rearranged png.h to put the major sections in the same order as
+    in libpng17.
+  Eliminated unused PNG_COST_SHIFT, PNG_WEIGHT_SHIFT, PNG_COST_FACTOR, and
+    PNG_WEIGHT_FACTOR macros.
+  Suppressed some warnings from the Borland C++ 5.5.1/5.82 compiler
+    (Bug report by Viktor Szakats).  Several warnings remain and are
+    unavoidable, where we test for overflow.
+  Fixed potential leak of png_pixels in contrib/pngminus/pnm2png.c
+  Fixed uninitialized variable in contrib/gregbook/rpng2-x.c
+
+Version 1.6.19beta02 [August 19, 2015]
+  Moved config.h.in~ from the "libpng_autotools_files" list to the
+    "libpng_autotools_extra" list in autogen.sh because it was causing a
+    false positive for missing files (bug report by Robert C. Seacord).
+  Removed unreachable "break" statements in png.c, pngread.c, and pngrtran.c
+    to suppress clang warnings (Bug report by Viktor Szakats).
+  Fixed some bad links in the man page.
+  Changed "n bit" to "n-bit" in comments.
+  Added signed/unsigned 16-bit safety net. This removes the dubious
+    0x8000 flag definitions on 16-bit systems. They aren't supported
+    yet the defs *probably* work, however it seems much safer to do this
+    and be advised if anyone, contrary to advice, is building libpng 1.6
+    on a 16-bit system. It also adds back various switch default clauses
+    for GCC; GCC errors out if they are not present (with an appropriately
+    high level of warnings).
+  Safely convert num_bytes to a png_byte in png_set_sig_bytes() (Robert
+    Seacord).
+  Fixed the recently reported 1's complement security issue by replacing
+    the value that is illegal in the PNG spec, in both signed and unsigned
+    values, with 0. Illegal unsigned values (anything greater than or equal
+    to  0x80000000) can still pass through, but since these are not illegal
+    in ANSI-C (unlike 0x80000000 in the signed case) the checking that
+    occurs later can catch them (John Bowler).
+
+Version 1.6.19beta03 [September 26, 2015]
+  Fixed png_save_int_32 when int is not 2's complement (John Bowler).
+  Updated libpng16 with all the recent test changes from libpng17,
+    including changes to pngvalid.c to ensure that the original,
+    distributed, version of contrib/visupng/cexcept.h can be used
+    (John Bowler).
+  pngvalid contains the correction to the use of SAVE/STORE_
+    UNKNOWN_CHUNKS; a bug revealed by changes in libpng 1.7. More
+    tests contain the --strict option to detect warnings and the
+    pngvalid-standard test has been corrected so that it does not
+    turn on progressive-read. There is a separate test which does
+    that. (John Bowler)
+  Also made some signed/unsigned fixes.
+  Make pngstest error limits version specific. Splitting the machine
+    generated error structs out to a file allows the values to be updated
+    without changing pngstest.c itself. Since libpng 1.6 and 1.7 have
+    slightly different error limits this simplifies maintenance. The
+    makepngs.sh script has also been updated to more accurately reflect
+    current problems in libpng 1.7 (John Bowler).
+  Incorporated new test PNG files into make check.  tests/pngstest-*
+    are changed so that the new test files are divided into 8 groups by
+    gamma and alpha channel.  These tests have considerably better code
+    and pixel-value coverage than contrib/pngsuite; however,coverage is
+    still incomplete (John Bowler).
+  Removed the '--strict' in 1.6 because of the double-gamma-correction
+    warning, updated pngstest-errors.h for the errors detected with the
+    new contrib/testspngs PNG test files (John Bowler).
+
+Version 1.6.19beta04 [October 15, 2015]
+  Worked around rgb-to-gray issues in libpng 1.6.  The previous
+    attempts to ignore the errors in the code aren't quite enough to
+    deal with the 'channel selection' encoding added to libpng 1.7; abort.
+    pngvalid.c is changed to drop this encoding in prior versions.
+  Fixed 'pow' macros in pngvalid.c. It is legal for 'pow' to be a
+    macro, therefore the argument list cannot contain preprocessing
+    directives.  Make sure pow is a function where this happens. This is
+    a minimal safe fix, the issue only arises in non-performance-critical
+    code (bug report by Curtis Leach, fix by John Bowler).
+  Added sPLT support to pngtest.c
+
+Version 1.6.19rc01 [October 23, 2015]
+  No changes.
+
+Version 1.6.19rc02 [October 31, 2015]
+  Prevent setting or writing over-length PLTE chunk (Cosmin Truta).
+  Silently truncate over-length PLTE chunk while reading.
+  Libpng incorrectly calculated the output rowbytes when the application
+    decreased either the number of channels or the bit depth (or both) in
+    a user transform.  This was safe; libpng overallocated buffer space
+   (potentially by quite a lot; up to 4 times the amount required) but,
+   from 1.5.4 on, resulted in a png_error (John Bowler).
+
+Version 1.6.19rc03 [November 3, 2015]
+  Fixed some inconsequential cut-and-paste typos in png_set_cHRM_XYZ_fixed().
+  Clarified COPYRIGHT information to state explicitly that versions
+    are derived from previous versions.
+  Removed much of the long list of previous versions from png.h and
+    libpng.3.
+
+Version 1.6.19rc04 [November 5, 2015]
+  Fixed new bug with CRC error after reading an over-length palette
+    (bug report by Cosmin Truta).
+
+Version 1.6.19 [November 12, 2015]
+  Cleaned up coding style in png_handle_PLTE().
+
 Send comments/corrections/commendations to png-mng-implement at lists.sf.net
 (subscription required; visit
 https://lists.sourceforge.net/lists/listinfo/png-mng-implement
@@ -5212,3 +5421,4 @@ to subscribe)
 or to glennrp at users.sourceforge.net
 
 Glenn R-P
+#endif
diff --git a/src/3rdparty/libpng/INSTALL b/src/3rdparty/libpng/INSTALL
index a294ffe633a4b3ce599567920f5a7b1172cd079f..531652abe0d32b6f2cfba063ca9a2ec7a5ae522d 100644
--- a/src/3rdparty/libpng/INSTALL
+++ b/src/3rdparty/libpng/INSTALL
@@ -385,23 +385,3 @@ XVI. Other sources of information about libpng:
 Further information can be found in the README and libpng-manual.txt
 files, in the individual makefiles, in png.h, and the manual pages
 libpng.3 and png.5.
-
-Using the ./configure script -- 16 December 2002.
-=================================================
-
-The ./configure script should work compatibly with what scripts/makefile.*
-did, however there are some options you might need to add to configure
-explicitly, which previously was done semi-automatically (if you didn't edit
-scripts/makefile.* yourself, that is)
-
-CFLAGS="-Wall -O -funroll-loops \
--malign-loops=2 -malign-functions=2" ./configure --prefix=/usr/include \
---with-pkgconfigdir=/usr/lib/pkgconfig --includedir=/usr/include
-
-You can alternatively specify --includedir=/usr/include, /usr/local/include,
-/usr/include/libpng16, or whatever.
-
-If you find that the configure script is out-of-date or is not supporting
-your platform properly, try running autogen.sh to regenerate "configure",
-"Makefile.in", and the other configuration files. Then try configure again.
-
diff --git a/src/3rdparty/libpng/LICENSE b/src/3rdparty/libpng/LICENSE
index eb4a9a9da4735a0e8aeb09f2a929a3e590e0b5ed..11f6ffe5db47ea0eb803bd509d165c30c751c76a 100644
--- a/src/3rdparty/libpng/LICENSE
+++ b/src/3rdparty/libpng/LICENSE
@@ -10,21 +10,18 @@ this sentence.
 
 This code is released under the libpng license.
 
-libpng versions 1.2.6, August 15, 2004, through 1.6.17, March 26, 2015, are
-Copyright (c) 2004, 2006-2015 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-1.2.5
-with the following individual added to the list of Contributing Authors
-
-   Cosmin Truta
-
-libpng versions 1.0.7, July 1, 2000, through 1.2.5 - October 3, 2002, are
-Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-1.0.6
-with the following individuals added to the list of Contributing Authors
+libpng versions 1.0.7, July 1, 2000, through 1.6.19, November 12, 2015, are
+Copyright (c) 2000-2002, 2004, 2006-2015 Glenn Randers-Pehrson, are
+derived from libpng-1.0.6, and are distributed according to the same
+disclaimer and license as libpng-1.0.6 with the following individuals
+added to the list of Contributing Authors:
 
    Simon-Pierre Cadieux
    Eric S. Raymond
+   Mans Rullgard
+   Cosmin Truta
    Gilles Vollant
+   James Yu
 
 and with the following additions to the disclaimer:
 
@@ -36,18 +33,20 @@ and with the following additions to the disclaimer:
    the user.
 
 libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
-Copyright (c) 1998, 1999 Glenn Randers-Pehrson, and are
-distributed according to the same disclaimer and license as libpng-0.96,
-with the following individuals added to the list of Contributing Authors:
+Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
+libpng-0.96, and are distributed according to the same disclaimer and
+license as libpng-0.96, with the following individuals added to the list
+of Contributing Authors:
 
    Tom Lane
    Glenn Randers-Pehrson
    Willem van Schaik
 
 libpng versions 0.89, June 1996, through 0.96, May 1997, are
-Copyright (c) 1996, 1997 Andreas Dilger
-Distributed according to the same disclaimer and license as libpng-0.88,
-with the following individuals added to the list of Contributing Authors:
+Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
+and are distributed according to the same disclaimer and license as
+libpng-0.88, with the following individuals added to the list of
+Contributing Authors:
 
    John Bowler
    Kevin Bracey
@@ -57,7 +56,7 @@ with the following individuals added to the list of Contributing Authors:
    Tom Tanner
 
 libpng versions 0.5, May 1995, through 0.88, January 1996, are
-Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
+Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
 
 For the purposes of this copyright and license, "Contributing Authors"
 is defined as the following set of individuals:
@@ -80,13 +79,13 @@ Permission is hereby granted to use, copy, modify, and distribute this
 source code, or portions hereof, for any purpose, without fee, subject
 to the following restrictions:
 
-1. The origin of this source code must not be misrepresented.
+  1. The origin of this source code must not be misrepresented.
 
-2. Altered versions must be plainly marked as such and must not
-   be misrepresented as being the original source.
+  2. Altered versions must be plainly marked as such and must not
+     be misrepresented as being the original source.
 
-3. This Copyright notice may not be removed or altered from any
-   source or altered source distribution.
+  3. This Copyright notice may not be removed or altered from any
+     source or altered source distribution.
 
 The Contributing Authors and Group 42, Inc. specifically permit, without
 fee, and encourage the use of this source code as a component to
@@ -94,18 +93,20 @@ supporting the PNG file format in commercial products.  If you use this
 source code in a product, acknowledgment is not required but would be
 appreciated.
 
+END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
 
 A "png_get_copyright" function is available, for convenient use in "about"
 boxes and the like:
 
-   printf("%s",png_get_copyright(NULL));
+   printf("%s", png_get_copyright(NULL));
 
 Also, the PNG logo (in PNG format, of course) is supplied in the
 files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
 
-Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is a
-certification mark of the Open Source Initiative.
+Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is
+a certification mark of the Open Source Initiative. OSI has not addressed
+the additional disclaimers inserted at version 1.0.7.
 
 Glenn Randers-Pehrson
 glennrp at users.sourceforge.net
-March 26, 2015
+November 12, 2015
diff --git a/src/3rdparty/libpng/README b/src/3rdparty/libpng/README
index a158ea8a77489adf8046478c5fd4d164245e809e..17484e0fd78a86d43e41d859a38a16af57b2389c 100644
--- a/src/3rdparty/libpng/README
+++ b/src/3rdparty/libpng/README
@@ -1,4 +1,4 @@
-README for libpng version 1.6.17 - March 26, 2015 (shared library 16.0)
+README for libpng version 1.6.19 - November 12, 2015 (shared library 16.0)
 See the note about version numbers near the top of png.h
 
 See INSTALL for instructions on how to install libpng.
@@ -134,7 +134,7 @@ and ...".  If in doubt, send questions to me.  I'll bounce them
 to others, if necessary.
 
 Please do not send suggestions on how to change PNG.  We have
-been discussing PNG for nineteen years now, and it is official and
+been discussing PNG for twenty years now, and it is official and
 finished.  If you have suggestions for libpng, however, I'll
 gladly listen.  Even if your suggestion is not used immediately,
 it may be used later.
diff --git a/src/3rdparty/libpng/libpng-manual.txt b/src/3rdparty/libpng/libpng-manual.txt
index f0dae987f9854b087abc7a1f67062f733263b6c6..bc7a441cf28a2a44138d55d6a47f1345c18e22cf 100644
--- a/src/3rdparty/libpng/libpng-manual.txt
+++ b/src/3rdparty/libpng/libpng-manual.txt
@@ -1,6 +1,6 @@
 libpng-manual.txt - A description on how to use and modify libpng
 
- libpng version 1.6.17 - March 26, 2015
+ libpng version 1.6.19 - November 12, 2015
  Updated and distributed by Glenn Randers-Pehrson
  <glennrp at users.sourceforge.net>
  Copyright (c) 1998-2015 Glenn Randers-Pehrson
@@ -11,7 +11,7 @@ libpng-manual.txt - A description on how to use and modify libpng
 
  Based on:
 
- libpng versions 0.97, January 1998, through 1.6.17 - March 26, 2015
+ libpng versions 0.97, January 1998, through 1.6.19 - November 12, 2015
  Updated and distributed by Glenn Randers-Pehrson
  Copyright (c) 1998-2015 Glenn Randers-Pehrson
 
@@ -70,15 +70,16 @@ a W3C Recommendation and as an ISO Standard (ISO/IEC 15948:2004 (E)) at
 The W3C and ISO documents have identical technical content.
 
 The PNG-1.2 specification is available at
-<http://www.libpng.org/pub/png/documents/>.  It is technically equivalent
+<http://png-mng.sourceforge.net/pub/png/spec/1.2/>.
+It is technically equivalent
 to the PNG specification (second edition) but has some additional material.
 
-The PNG-1.0 specification is available
-as RFC 2083 <http://www.libpng.org/pub/png/documents/> and as a
-W3C Recommendation <http://www.w3.org/TR/REC.png.html>.
+The PNG-1.0 specification is available as RFC 2083 
+<http://png-mng.sourceforge.net/pub/png/spec/1.0/> and as a
+W3C Recommendation <http://www.w3.org/TR/REC-png-961001>.
 
 Some additional chunks are described in the special-purpose public chunks
-documents at <http://www.libpng.org/pub/png/documents/>.
+documents at <http://www.libpng.org/pub/png/spec/register/>
 
 Other information
 about PNG, and the latest version of libpng, can be found at the PNG home
@@ -100,7 +101,7 @@ majority of the needs of its users.
 
 Libpng uses zlib for its compression and decompression of PNG files.
 Further information about zlib, and the latest version of zlib, can
-be found at the zlib home page, <http://www.info-zip.org/pub/infozip/zlib/>.
+be found at the zlib home page, <http://zlib.net/>.
 The zlib compression utility is a general purpose utility that is
 useful for more than PNG files, and can be used without libpng.
 See the documentation delivered with zlib for more details.
@@ -649,6 +650,7 @@ User limits
 
 The PNG specification allows the width and height of an image to be as
 large as 2^31-1 (0x7fffffff), or about 2.147 billion rows and columns.
+For safety, libpng imposes a default limit of 1 million rows and columns.
 Larger images will be rejected immediately with a png_error() call. If
 you wish to change these limits, you can use
 
@@ -669,8 +671,11 @@ If you need to retrieve the limits that are being applied, use
    height_max = png_get_user_height_max(png_ptr);
 
 The PNG specification sets no limit on the number of ancillary chunks
-allowed in a PNG datastream.  You can impose a limit on the total number
-of sPLT, tEXt, iTXt, zTXt, and unknown chunks that will be stored, with
+allowed in a PNG datastream.  By default, libpng imposes a limit of
+a total of 1000 sPLT, tEXt, iTXt, zTXt, and unknown chunks to be stored.
+If you have set up both info_ptr and end_info_ptr, the limit applies
+separately to each.  You can change the limit on the total number of such
+chunks that will be stored, with
 
    png_set_chunk_cache_max(png_ptr, user_chunk_cache_max);
 
@@ -678,8 +683,9 @@ where 0x7fffffffL means unlimited.  You can retrieve this limit with
 
    chunk_cache_max = png_get_chunk_cache_max(png_ptr);
 
-You can also set a limit on the amount of memory that a compressed chunk
-other than IDAT can occupy, with
+Libpng imposes a limit of 8 Megabytes (8,000,000 bytes) on the amount of
+memory that a compressed chunk other than IDAT can occupy, when decompressed.
+You can change this limit with
 
    png_set_chunk_malloc_max(png_ptr, user_chunk_malloc_max);
 
@@ -1679,15 +1685,16 @@ described below.
 Data will be decoded into the supplied row buffers packed into bytes
 unless the library has been told to transform it into another format.
 For example, 4 bit/pixel paletted or grayscale data will be returned
-2 pixels/byte with the leftmost pixel in the high-order bits of the
-byte, unless png_set_packing() is called.  8-bit RGB data will be stored
+2 pixels/byte with the leftmost pixel in the high-order bits of the byte,
+unless png_set_packing() is called.  8-bit RGB data will be stored
 in RGB RGB RGB format unless png_set_filler() or png_set_add_alpha()
 is called to insert filler bytes, either before or after each RGB triplet.
+
 16-bit RGB data will be returned RRGGBB RRGGBB, with the most significant
 byte of the color value first, unless png_set_scale_16() is called to
 transform it to regular RGB RGB triplets, or png_set_filler() or
-png_set_add alpha() is called to insert filler bytes, either before or
-after each RRGGBB triplet.  Similarly, 8-bit or 16-bit grayscale data can
+png_set_add alpha() is called to insert two filler bytes, either before
+or after each RRGGBB triplet.  Similarly, 8-bit or 16-bit grayscale data can
 be modified with png_set_filler(), png_set_add_alpha(), png_set_strip_16(),
 or png_set_scale_16().
 
@@ -1844,12 +1851,13 @@ into 4 or 8 bytes for windowing systems that need them in this format:
     if (color_type == PNG_COLOR_TYPE_RGB)
        png_set_filler(png_ptr, filler, PNG_FILLER_BEFORE);
 
-where "filler" is the 8 or 16-bit number to fill with, and the location is
-either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
-you want the filler before the RGB or after.  This transformation
-does not affect images that already have full alpha channels.  To add an
-opaque alpha channel, use filler=0xff or 0xffff and PNG_FILLER_AFTER which
-will generate RGBA pixels.
+where "filler" is the 8-bit or 16-bit number to fill with, and the location
+is either PNG_FILLER_BEFORE or PNG_FILLER_AFTER, depending upon whether
+you want the filler before the RGB or after. When filling an 8-bit pixel,
+the least significant 8 bits of the number are used, if a 16-bit number is
+supplied.  This transformation does not affect images that already have full
+alpha channels.  To add an opaque alpha channel, use filler=0xffff and
+PNG_FILLER_AFTER which will generate RGBA pixels.
 
 Note that png_set_filler() does not change the color type.  If you want
 to do that, you can add a true alpha channel with
@@ -1859,7 +1867,7 @@ to do that, you can add a true alpha channel with
        png_set_add_alpha(png_ptr, filler, PNG_FILLER_AFTER);
 
 where "filler" contains the alpha value to assign to each pixel.
-This function was added in libpng-1.2.7.
+The png_set_add_alpha() function was added in libpng-1.2.7.
 
 If you are reading an image with an alpha channel, and you need the
 data as ARGB instead of the normal PNG format RGBA:
@@ -1917,9 +1925,9 @@ data for sBIT, regardless of the error_action setting.
 The default values come from the PNG file cHRM chunk if present; otherwise, the
 defaults correspond to the ITU-R recommendation 709, and also the sRGB color
 space, as recommended in the Charles Poynton's Colour FAQ,
-<http://www.poynton.com/>, in section 9:
+Copyright (c) 2006-11-28 Charles Poynton, in section 9:
 
-   <http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html#RTFToC9>
+<http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html#RTFToC9>
 
     Y = 0.2126 * R + 0.7152 * G + 0.0722 * B
 
@@ -3716,21 +3724,26 @@ as a wide variety of APIs to manipulate ancilliary information.
 
 To read a PNG file using the simplified API:
 
-  1) Declare a 'png_image' structure (see below) on the
-     stack and memset() it to all zero.
+  1) Declare a 'png_image' structure (see below) on the stack, set the
+     version field to PNG_IMAGE_VERSION and the 'opaque' pointer to NULL
+     (this is REQUIRED, your program may crash if you don't do it.)
 
   2) Call the appropriate png_image_begin_read... function.
 
-  3) Set the png_image 'format' member to the required
-     format and allocate a buffer for the image.
+  3) Set the png_image 'format' member to the required sample format.
+
+  4) Allocate a buffer for the image and, if required, the color-map.
 
-  4) Call png_image_finish_read to read the image into
-     your buffer.
+  5) Call png_image_finish_read to read the image and, if required, the
+     color-map into your buffers.
 
 There are no restrictions on the format of the PNG input itself; all valid
 color types, bit depths, and interlace methods are acceptable, and the
 input image is transformed as necessary to the requested in-memory format
-during the png_image_finish_read() step.
+during the png_image_finish_read() step.  The only caveat is that if you
+request a color-mapped image from a PNG that is full-color or makes
+complex use of an alpha channel the transformation is extremely lossy and the
+result may look terrible.
 
 To write a PNG file using the simplified API:
 
@@ -3739,34 +3752,35 @@ To write a PNG file using the simplified API:
 
   2) Initialize the members of the structure that describe the
      image, setting the 'format' member to the format of the
-     image in memory.
+     image samples.
 
   3) Call the appropriate png_image_write... function with a
-     pointer to the image to write the PNG data.
+     pointer to the image and, if necessary, the color-map to write
+     the PNG data.
 
 png_image is a structure that describes the in-memory format of an image
-when it is being read or define the in-memory format of an image that you
+when it is being read or defines the in-memory format of an image that you
 need to write.  The "png_image" structure contains the following members:
 
+   png_controlp opaque  Initialize to NULL, free with png_image_free
    png_uint_32  version Set to PNG_IMAGE_VERSION
    png_uint_32  width   Image width in pixels (columns)
    png_uint_32  height  Image height in pixels (rows)
    png_uint_32  format  Image format as defined below
    png_uint_32  flags   A bit mask containing informational flags
-   png_controlp opaque  Initialize to NULL, free with png_image_free
    png_uint_32  colormap_entries; Number of entries in the color-map
    png_uint_32  warning_or_error;
    char         message[64];
 
-In the event of an error or warning the following field warning_or_error
+In the event of an error or warning the "warning_or_error"
 field will be set to a non-zero value and the 'message' field will contain
 a '\0' terminated string with the libpng error or warning message.  If both
 warnings and an error were encountered, only the error is recorded.  If there
 are multiple warnings, only the first one is recorded.
 
-The upper 30 bits of this value are reserved; the low two bits contain
-a two bit code such that a value more than 1 indicates a failure in the API
-just called:
+The upper 30 bits of the "warning_or_error" value are reserved; the low two
+bits contain a two bit code such that a value more than 1 indicates a failure
+in the API just called:
 
    0 - no warning or error
    1 - warning
@@ -3798,64 +3812,72 @@ channels are linear.  Color channels use the RGB encoding (RGB end-points) of
 the sRGB specification.  This encoding is identified by the
 PNG_FORMAT_FLAG_LINEAR flag below.
 
+When the simplified API needs to convert between sRGB and linear colorspaces,
+the actual sRGB transfer curve defined in the sRGB specification (see the
+article at http://en.wikipedia.org/wiki/SRGB) is used, not the gamma=1/2.2
+approximation used elsewhere in libpng.
+
 When an alpha channel is present it is expected to denote pixel coverage
 of the color or luminance channels and is returned as an associated alpha
 channel: the color/gray channels are scaled (pre-multiplied) by the alpha
 value.
 
-When a color-mapped image is used as a result of calling
-png_image_read_colormap or png_image_write_colormap the channels are encoded
-in the color-map and the descriptions above apply to the color-map entries.
-The image data is encoded as small integers, value 0..255, that index the
-entries in the color-map.  One integer (one byte) is stored for each pixel.
+The samples are either contained directly in the image data, between 1 and 8
+bytes per pixel according to the encoding, or are held in a color-map indexed
+by bytes in the image data.  In the case of a color-map the color-map entries
+are individual samples, encoded as above, and the image data has one byte per
+pixel to select the relevant sample from the color-map.
 
 PNG_FORMAT_*
 
 The #defines to be used in png_image::format.  Each #define identifies a
 particular layout of channel data and, if present, alpha values.  There are
-separate defines for each of the two channel encodings.
+separate defines for each of the two component encodings.
 
-A format is built up using single bit flag values.  Not all combinations are
-valid: use the bit flag values below for testing a format returned by the
-read APIs, but set formats from the derived values.
+A format is built up using single bit flag values.  All combinations are
+valid.  Formats can be built up from the flag values or you can use one of
+the predefined values below.  When testing formats always use the FORMAT_FLAG
+macros to test for individual features - future versions of the library may
+add new flags.
 
 When reading or writing color-mapped images the format should be set to the
 format of the entries in the color-map then png_image_{read,write}_colormap
 called to read or write the color-map and set the format correctly for the
 image data.  Do not set the PNG_FORMAT_FLAG_COLORMAP bit directly!
 
-NOTE: libpng can be built with particular features disabled, if you see
+NOTE: libpng can be built with particular features disabled. If you see
 compiler errors because the definition of one of the following flags has been
 compiled out it is because libpng does not have the required support.  It is
 possible, however, for the libpng configuration to enable the format on just
-read or just write; in that case you may see an error at run time.  You can
-guard against this by checking for the definition of:
+read or just write; in that case you may see an error at run time.
+You can guard against this by checking for the definition of the
+appropriate "_SUPPORTED" macro, one of:
 
    PNG_SIMPLIFIED_{READ,WRITE}_{BGR,AFIRST}_SUPPORTED
 
-   PNG_FORMAT_FLAG_ALPHA    0x01 format with an alpha channel
-   PNG_FORMAT_FLAG_COLOR    0x02 color format: otherwise grayscale
-   PNG_FORMAT_FLAG_LINEAR   0x04 png_uint_16 channels else png_byte
-   PNG_FORMAT_FLAG_COLORMAP 0x08 libpng use only
-   PNG_FORMAT_FLAG_BGR      0x10 BGR colors, else order is RGB
-   PNG_FORMAT_FLAG_AFIRST   0x20 alpha channel comes first
+   PNG_FORMAT_FLAG_ALPHA    format with an alpha channel
+   PNG_FORMAT_FLAG_COLOR    color format: otherwise grayscale
+   PNG_FORMAT_FLAG_LINEAR   2-byte channels else 1-byte
+   PNG_FORMAT_FLAG_COLORMAP image data is color-mapped
+   PNG_FORMAT_FLAG_BGR      BGR colors, else order is RGB
+   PNG_FORMAT_FLAG_AFIRST   alpha channel comes first
 
 Supported formats are as follows.  Future versions of libpng may support more
 formats; for compatibility with older versions simply check if the format
 macro is defined using #ifdef.  These defines describe the in-memory layout
 of the components of the pixels of the image.
 
-First the single byte formats:
+First the single byte (sRGB) formats:
 
-   PNG_FORMAT_GRAY 0
-   PNG_FORMAT_GA   PNG_FORMAT_FLAG_ALPHA
-   PNG_FORMAT_AG   (PNG_FORMAT_GA|PNG_FORMAT_FLAG_AFIRST)
-   PNG_FORMAT_RGB  PNG_FORMAT_FLAG_COLOR
-   PNG_FORMAT_BGR  (PNG_FORMAT_FLAG_COLOR|PNG_FORMAT_FLAG_BGR)
-   PNG_FORMAT_RGBA (PNG_FORMAT_RGB|PNG_FORMAT_FLAG_ALPHA)
-   PNG_FORMAT_ARGB (PNG_FORMAT_RGBA|PNG_FORMAT_FLAG_AFIRST)
-   PNG_FORMAT_BGRA (PNG_FORMAT_BGR|PNG_FORMAT_FLAG_ALPHA)
-   PNG_FORMAT_ABGR (PNG_FORMAT_BGRA|PNG_FORMAT_FLAG_AFIRST)
+   PNG_FORMAT_GRAY
+   PNG_FORMAT_GA
+   PNG_FORMAT_AG
+   PNG_FORMAT_RGB
+   PNG_FORMAT_BGR
+   PNG_FORMAT_RGBA
+   PNG_FORMAT_ARGB
+   PNG_FORMAT_BGRA
+   PNG_FORMAT_ABGR
 
 Then the linear 2-byte formats.  When naming these "Y" is used to
 indicate a luminance (gray) channel.  The component order within the pixel
@@ -3864,22 +3886,22 @@ components in the linear format.  The components are 16-bit integers in
 the native byte order for your platform, and there is no provision for
 swapping the bytes to a different endian condition.
 
-   PNG_FORMAT_LINEAR_Y PNG_FORMAT_FLAG_LINEAR
+   PNG_FORMAT_LINEAR_Y
    PNG_FORMAT_LINEAR_Y_ALPHA
-      (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_ALPHA)
    PNG_FORMAT_LINEAR_RGB
-      (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR)
    PNG_FORMAT_LINEAR_RGB_ALPHA
-      (PNG_FORMAT_FLAG_LINEAR|PNG_FORMAT_FLAG_COLOR|
-      PNG_FORMAT_FLAG_ALPHA)
 
-Color-mapped formats are obtained by calling png_image_{read,write}_colormap,
-as appropriate after setting png_image::format to the format of the color-map
-to be read or written.  Applications may check the value of
-PNG_FORMAT_FLAG_COLORMAP to see if they have called the colormap API.  The
-format of the color-map may be extracted using the following macro.
+With color-mapped formats the image data is one byte for each pixel. The byte
+is an index into the color-map which is formatted as above.  To obtain a
+color-mapped format it is sufficient just to add the PNG_FOMAT_FLAG_COLORMAP
+to one of the above definitions, or you can use one of the definitions below.
 
-   PNG_FORMAT_OF_COLORMAP(fmt) ((fmt) & ~PNG_FORMAT_FLAG_COLORMAP)
+   PNG_FORMAT_RGB_COLORMAP
+   PNG_FORMAT_BGR_COLORMAP
+   PNG_FORMAT_RGBA_COLORMAP
+   PNG_FORMAT_ARGB_COLORMAP
+   PNG_FORMAT_BGRA_COLORMAP
+   PNG_FORMAT_ABGR_COLORMAP
 
 PNG_IMAGE macros
 
@@ -3887,9 +3909,9 @@ These are convenience macros to derive information from a png_image
 structure.  The PNG_IMAGE_SAMPLE_ macros return values appropriate to the
 actual image sample values - either the entries in the color-map or the
 pixels in the image.  The PNG_IMAGE_PIXEL_ macros return corresponding values
-for the pixels and will always return 1 after a call to
-png_image_{read,write}_colormap.  The remaining macros return information
-about the rows in the image and the complete image.
+for the pixels and will always return 1 for color-mapped formats.  The
+remaining macros return information about the rows in the image and the
+complete image.
 
 NOTE: All the macros that take a png_image::format parameter are compile time
 constants if the format parameter is, itself, a constant.  Therefore these
@@ -3897,46 +3919,39 @@ macros can be used in array declarations and case labels where required.
 Similarly the macros are also pre-processor constants (sizeof is not used) so
 they can be used in #if tests.
 
-First the information about the samples.
-
   PNG_IMAGE_SAMPLE_CHANNELS(fmt)
     Returns the total number of channels in a given format: 1..4
 
   PNG_IMAGE_SAMPLE_COMPONENT_SIZE(fmt)
     Returns the size in bytes of a single component of a pixel or color-map
-    entry (as appropriate) in the image.
+    entry (as appropriate) in the image: 1 or 2.
 
   PNG_IMAGE_SAMPLE_SIZE(fmt)
     This is the size of the sample data for one sample.  If the image is
     color-mapped it is the size of one color-map entry (and image pixels are
     one byte in size), otherwise it is the size of one image pixel.
 
+  PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(fmt)
+    The maximum size of the color-map required by the format expressed in a
+    count of components.  This can be used to compile-time allocate a
+    color-map:
+
+    png_uint_16 colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(linear_fmt)];
+
+    png_byte colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(sRGB_fmt)];
+
+    Alternatively use the PNG_IMAGE_COLORMAP_SIZE macro below to use the
+    information from one of the png_image_begin_read_ APIs and dynamically
+    allocate the required memory.
+
   PNG_IMAGE_COLORMAP_SIZE(fmt)
    The size of the color-map required by the format; this is the size of the
-   color-map buffer passed to the png_image_{read,write}_colormap APIs, it is
+   color-map buffer passed to the png_image_{read,write}_colormap APIs. It is
    a fixed number determined by the format so can easily be allocated on the
    stack if necessary.
 
-#define PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(fmt)\
-   (PNG_IMAGE_SAMPLE_CHANNELS(fmt) * 256)
-   /* The maximum size of the color-map required by the format expressed in a
-    * count of components.  This can be used to compile-time allocate a
-    * color-map:
-    *
-    * png_uint_16 colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(linear_fmt)];
-    *
-    * png_byte colormap[PNG_IMAGE_MAXIMUM_COLORMAP_COMPONENTS(sRGB_fmt)];
-    *
-    * Alternatively, use the PNG_IMAGE_COLORMAP_SIZE macro below to use the
-    * information from one of the png_image_begin_read_ APIs and dynamically
-    * allocate the required memory.
-    */
-
-
 Corresponding information about the pixels
 
-  PNG_IMAGE_PIXEL_(test,fmt)
-
   PNG_IMAGE_PIXEL_CHANNELS(fmt)
    The number of separate channels (components) in a pixel; 1 for a
    color-mapped image.
@@ -3962,19 +3977,54 @@ Information about the whole row, or whole image
    to start the next row on a 4-byte boundary.
 
   PNG_IMAGE_BUFFER_SIZE(image, row_stride)
-    Returns the size, in bytes, of an image buffer given a png_image and a row
-    stride - the number of components to leave space for in each row.  This
-    macro takes care of multiplying row_stride by PNG_IMAGE_PIXEL_COMONENT_SIZE
-    when the image has 2-byte components.
+   Return the size, in bytes, of an image buffer given a png_image and a row
+   stride - the number of components to leave space for in each row.
+
+  PNG_IMAGE_SIZE(image)
+   Return the size, in bytes, of the image in memory given just a png_image;
+   the row stride is the minimum stride required for the image.
+
+  PNG_IMAGE_COLORMAP_SIZE(image)
+   Return the size, in bytes, of the color-map of this image.  If the image
+   format is not a color-map format this will return a size sufficient for
+   256 entries in the given format; check PNG_FORMAT_FLAG_COLORMAP if
+   you don't want to allocate a color-map in this case.
+
+PNG_IMAGE_FLAG_*
+
+Flags containing additional information about the image are held in
+the 'flags' field of png_image.
 
   PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB == 0x01
     This indicates the the RGB values of the in-memory bitmap do not
     correspond to the red, green and blue end-points defined by sRGB.
 
-  PNG_IMAGE_FLAG_COLORMAP == 0x02
-    The PNG is color-mapped.  If this flag is set png_image_read_colormap
-    can be used without further loss of image information.  If it is not set
-    png_image_read_colormap will cause significant loss if the image has any
+  PNG_IMAGE_FLAG_FAST == 0x02
+   On write emphasise speed over compression; the resultant PNG file will be
+   larger but will be produced significantly faster, particular for large
+   images.  Do not use this option for images which will be distributed, only
+   used it when producing intermediate files that will be read back in
+   repeatedly.  For a typical 24-bit image the option will double the read
+   speed at the cost of increasing the image size by 25%, however for many
+   more compressible images the PNG file can be 10 times larger with only a
+   slight speed gain.
+
+  PNG_IMAGE_FLAG_16BIT_sRGB == 0x04
+    On read if the image is a 16-bit per component image and there is no gAMA
+    or sRGB chunk assume that the components are sRGB encoded.  Notice that
+    images output by the simplified API always have gamma information; setting
+    this flag only affects the interpretation of 16-bit images from an
+    external source.  It is recommended that the application expose this flag
+    to the user; the user can normally easily recognize the difference between
+    linear and sRGB encoding.  This flag has no effect on write - the data
+    passed to the write APIs must have the correct encoding (as defined
+    above.)
+
+    If the flag is not set (the default) input 16-bit per component data is
+    assumed to be linear.
+
+    NOTE: the flag can only be set after the png_image_begin_read_ call,
+    because that call initializes the 'flags' field.
 
 READ APIs
 
@@ -4065,10 +4115,11 @@ a 16-bit linear encoded PNG file is written.
 
 With all APIs row_stride is handled as in the read APIs - it is the spacing
 from one row to the next in component sized units (float) and if negative
-indicates a bottom-up row layout in the buffer.
+indicates a bottom-up row layout in the buffer.  If you pass zero, libpng will
+calculate the row_stride for you from the width and number of channels.
 
 Note that the write API does not support interlacing, sub-8-bit pixels,
-and indexed (paletted) images.
+indexed (paletted) images, or most ancillary chunks.
 
 VI. Modifying/Customizing libpng
 
@@ -4356,41 +4407,6 @@ is called for the first time.)
               same as the value of filter_method used
               in png_set_IHDR().
 
-It is also possible to influence how libpng chooses from among the
-available filters.  This is done in one or both of two ways - by
-telling it how important it is to keep the same filter for successive
-rows, and by telling it the relative computational costs of the filters.
-
-    double weights[3] = {1.5, 1.3, 1.1},
-       costs[PNG_FILTER_VALUE_LAST] =
-       {1.0, 1.3, 1.3, 1.5, 1.7};
-
-    png_set_filter_heuristics(png_ptr,
-       PNG_FILTER_HEURISTIC_WEIGHTED, 3,
-       weights, costs);
-
-The weights are multiplying factors that indicate to libpng that the
-row filter should be the same for successive rows unless another row filter
-is that many times better than the previous filter.  In the above example,
-if the previous 3 filters were SUB, SUB, NONE, the SUB filter could have a
-"sum of absolute differences" 1.5 x 1.3 times higher than other filters
-and still be chosen, while the NONE filter could have a sum 1.1 times
-higher than other filters and still be chosen.  Unspecified weights are
-taken to be 1.0, and the specified weights should probably be declining
-like those above in order to emphasize recent filters over older filters.
-
-The filter costs specify for each filter type a relative decoding cost
-to be considered when selecting row filters.  This means that filters
-with higher costs are less likely to be chosen over filters with lower
-costs, unless their "sum of absolute differences" is that much smaller.
-The costs do not necessarily reflect the exact computational speeds of
-the various filters, since this would unduly influence the final image
-size.
-
-Note that the numbers above were invented purely for this example and
-are given only to help explain the function usage.  Little testing has
-been done to find optimum values for either the costs or the weights.
-
 Requesting debug printout
 
 The macro definition PNG_DEBUG can be used to request debugging
@@ -4890,7 +4906,7 @@ limits are now
    png_user_chunk_malloc_max 0 (unlimited) 8,000,000
 
 The png_set_option() function (and the "options" member of the png struct) was
-added to libpng-1.5.15.
+added to libpng-1.5.15, with option PNG_ARM_NEON.
 
 The library now supports a complete fixed point implementation and can
 thus be used on systems that have no floating point support or very
@@ -5032,9 +5048,9 @@ The signatures of many exported functions were changed, such that
    png_infop became png_inforp or png_const_inforp
 where "rp" indicates a "restricted pointer".
 
-The support for FAR/far types has been eliminated and the definition of
-png_alloc_size_t is now controlled by a flag so that 'small size_t' systems
-can select it if necessary.
+Dropped support for 16-bit platforms. The support for FAR/far types has
+been eliminated and the definition of png_alloc_size_t is now controlled
+by a flag so that 'small size_t' systems can select it if necessary.
 
 Error detection in some chunks has improved; in particular the iCCP chunk
 reader now does pretty complete validation of the basic format.  Some bad
@@ -5109,6 +5125,28 @@ length, which resulted in PNG files that cannot be read beyond the bad iTXt
 chunk.  This error was fixed in libpng-1.6.3, and a tool (called
 contrib/tools/png-fix-itxt) has been added to the libpng distribution.
 
+Starting with libpng-1.6.17, the PNG_SAFE_LIMITS macro was eliminated
+and safe limits are used by default (users who need larger limits
+can still override them at compile time or run time, as described above).
+
+The new limits are
+                                default   spec limit
+   png_user_width_max         1,000,000  2,147,483,647
+   png_user_height_max        1,000,000  2,147,483,647
+   png_user_chunk_cache_max         128  unlimited
+   png_user_chunk_malloc_max  8,000,000  unlimited
+
+Starting with libpng-1.6.18, a PNG_RELEASE_BUILD macro was added, which allows
+library builders to control compilation for an installed system (a release build).
+It can be set for testing debug or beta builds to ensure that they will compile
+when the build type is switched to RC or STABLE. In essence this overrides the
+PNG_LIBPNG_BUILD_BASE_TYPE definition which is not directly user controllable.
+
+Starting with libpng-1.6.19, attempting to set an over-length PLTE chunk
+is an error. Previously this requirement of the PNG specification was not
+enforced, and the palette was always limited to 256 entries. An over-length
+PLTE chunk found in an input PNG is silently truncated.
+
 XIII.  Detecting libpng
 
 The png_get_io_ptr() function has been present since libpng-0.88, has never
@@ -5262,10 +5300,12 @@ We prefer #ifdef and #ifndef to #if defined() and #if !defined()
 when there is only one macro being tested.  We always use parentheses
 with "defined".
 
-We prefer to express integers that are used as bit masks in hex format,
-with an even number of lower-case hex digits (e.g., 0x00, 0xff, 0x0100).
+We express integer constants that are used as bit masks in hex format,
+with an even number of lower-case hex digits, and to make them unsigned
+(e.g., 0x00U, 0xffU, 0x0100U) and long if they are greater than 0x7fff
+(e.g., 0xffffUL).
 
-We prefer to use underscores in variable names rather than camelCase, except
+We prefer to use underscores rather than camelCase in names, except
 for a few type names that we inherit from zlib.h.
 
 We prefer "if (something != 0)" and "if (something == 0)"
@@ -5279,13 +5319,11 @@ Other rules can be inferred by inspecting the libpng source.
 
 XVI. Y2K Compliance in libpng
 
-March 26, 2015
-
 Since the PNG Development group is an ad-hoc body, we can't make
 an official declaration.
 
 This is your unofficial assurance that libpng from version 0.71 and
-upward through 1.6.17 are Y2K compliant.  It is my belief that earlier
+upward through 1.6.19 are Y2K compliant.  It is my belief that earlier
 versions were also Y2K compliant.
 
 Libpng only has two year fields.  One is a 2-byte unsigned integer
diff --git a/src/3rdparty/libpng/png.c b/src/3rdparty/libpng/png.c
index 7575ede97bcaf2b379ea780831c906186f0d57f7..6fcfad72ec1a5db7d24206181193623c31f655c5 100644
--- a/src/3rdparty/libpng/png.c
+++ b/src/3rdparty/libpng/png.c
@@ -1,7 +1,7 @@
 
 /* png.c - location for general purpose libpng functions
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.19 [November 12, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -14,7 +14,7 @@
 #include "pngpriv.h"
 
 /* Generate a compiler error if there is an old png.h in the search path. */
-typedef png_libpng_version_1_6_17 Your_png_h_is_not_version_1_6_17;
+typedef png_libpng_version_1_6_19 Your_png_h_is_not_version_1_6_19;
 
 /* Tells libpng that we have already handled the first "num_bytes" bytes
  * of the PNG file signature.  If the PNG data is embedded into another
@@ -26,15 +26,20 @@ typedef png_libpng_version_1_6_17 Your_png_h_is_not_version_1_6_17;
 void PNGAPI
 png_set_sig_bytes(png_structrp png_ptr, int num_bytes)
 {
+   unsigned int nb = (unsigned int)num_bytes;
+
    png_debug(1, "in png_set_sig_bytes");
 
    if (png_ptr == NULL)
       return;
 
-   if (num_bytes > 8)
+   if (num_bytes < 0)
+      nb = 0;
+
+   if (nb > 8)
       png_error(png_ptr, "Too many bytes for PNG signature");
 
-   png_ptr->sig_bytes = (png_byte)((num_bytes < 0 ? 0 : num_bytes) & 0xff);
+   png_ptr->sig_bytes = (png_byte)nb;
 }
 
 /* Checks whether the supplied bytes match the PNG signature.  We allow
@@ -101,7 +106,7 @@ png_zfree(voidpf png_ptr, voidpf ptr)
 void /* PRIVATE */
 png_reset_crc(png_structrp png_ptr)
 {
-   /* The cast is safe because the crc is a 32 bit value. */
+   /* The cast is safe because the crc is a 32-bit value. */
    png_ptr->crc = (png_uint_32)crc32(0, Z_NULL, 0);
 }
 
@@ -129,7 +134,7 @@ png_calculate_crc(png_structrp png_ptr, png_const_bytep ptr, png_size_t length)
    }
 
    /* 'uLong' is defined in zlib.h as unsigned long; this means that on some
-    * systems it is a 64 bit value.  crc32, however, returns 32 bits so the
+    * systems it is a 64-bit value.  crc32, however, returns 32 bits so the
     * following cast is safe.  'uInt' may be no more than 16 bits, so it is
     * necessary to perform a loop here.
     */
@@ -243,15 +248,15 @@ png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
       create_struct.user_height_max = PNG_USER_HEIGHT_MAX;
 
 #     ifdef PNG_USER_CHUNK_CACHE_MAX
-         /* Added at libpng-1.2.43 and 1.4.0 */
-         create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;
+      /* Added at libpng-1.2.43 and 1.4.0 */
+      create_struct.user_chunk_cache_max = PNG_USER_CHUNK_CACHE_MAX;
 #     endif
 
 #     ifdef PNG_USER_CHUNK_MALLOC_MAX
-         /* Added at libpng-1.2.43 and 1.4.1, required only for read but exists
-          * in png_struct regardless.
-          */
-         create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;
+      /* Added at libpng-1.2.43 and 1.4.1, required only for read but exists
+       * in png_struct regardless.
+       */
+      create_struct.user_chunk_malloc_max = PNG_USER_CHUNK_MALLOC_MAX;
 #     endif
 #  endif
 
@@ -275,7 +280,9 @@ png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
 
 #  ifdef PNG_SETJMP_SUPPORTED
       if (!setjmp(create_jmp_buf))
+#  endif
       {
+#  ifdef PNG_SETJMP_SUPPORTED
          /* Temporarily fake out the longjmp information until we have
           * successfully completed this function.  This only works if we have
           * setjmp() support compiled in, but it is safe - this stuff should
@@ -284,8 +291,6 @@ png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
          create_struct.jmp_buf_ptr = &create_jmp_buf;
          create_struct.jmp_buf_size = 0; /*stack allocation*/
          create_struct.longjmp_fn = longjmp;
-#  else
-      {
 #  endif
          /* Call the general version checker (shared with read and write code):
           */
@@ -304,10 +309,10 @@ png_create_png_struct,(png_const_charp user_png_ver, png_voidp error_ptr,
                create_struct.zstream.opaque = png_ptr;
 
 #              ifdef PNG_SETJMP_SUPPORTED
-                  /* Eliminate the local error handling: */
-                  create_struct.jmp_buf_ptr = NULL;
-                  create_struct.jmp_buf_size = 0;
-                  create_struct.longjmp_fn = 0;
+               /* Eliminate the local error handling: */
+               create_struct.jmp_buf_ptr = NULL;
+               create_struct.jmp_buf_size = 0;
+               create_struct.longjmp_fn = 0;
 #              endif
 
                *png_ptr = create_struct;
@@ -413,6 +418,8 @@ png_info_init_3,(png_infopp ptr_ptr, png_size_t png_info_struct_size),
       free(info_ptr);
       info_ptr = png_voidcast(png_inforp, png_malloc_base(NULL,
          (sizeof *info_ptr)));
+      if (info_ptr == NULL)
+         return;
       *ptr_ptr = info_ptr;
    }
 
@@ -664,19 +671,20 @@ png_init_io(png_structrp png_ptr, png_FILE_p fp)
 #  endif
 
 #  ifdef PNG_SAVE_INT_32_SUPPORTED
-/* The png_save_int_32 function assumes integers are stored in two's
- * complement format.  If this isn't the case, then this routine needs to
- * be modified to write data in two's complement format.  Note that,
- * the following works correctly even if png_int_32 has more than 32 bits
- * (compare the more complex code required on read for sign extension.)
+/* PNG signed integers are saved in 32-bit 2's complement format.  ANSI C-90
+ * defines a cast of a signed integer to an unsigned integer either to preserve
+ * the value, if it is positive, or to calculate:
+ *
+ *     (UNSIGNED_MAX+1) + integer
+ *
+ * Where UNSIGNED_MAX is the appropriate maximum unsigned value, so when the
+ * negative integral value is added the result will be an unsigned value
+ * correspnding to the 2's complement representation.
  */
 void PNGAPI
 png_save_int_32(png_bytep buf, png_int_32 i)
 {
-   buf[0] = (png_byte)((i >> 24) & 0xff);
-   buf[1] = (png_byte)((i >> 16) & 0xff);
-   buf[2] = (png_byte)((i >> 8) & 0xff);
-   buf[3] = (png_byte)(i & 0xff);
+   png_save_uint_32(buf, i);
 }
 #  endif
 
@@ -722,6 +730,7 @@ png_convert_to_rfc1123_buffer(char out[29], png_const_timep ptime)
       APPEND(':');
       APPEND_NUMBER(PNG_NUMBER_FORMAT_02u, (unsigned)ptime->second);
       APPEND_STRING(" +0000"); /* This reliably terminates the buffer */
+      PNG_UNUSED (pos)
 
 #     undef APPEND
 #     undef APPEND_NUMBER
@@ -766,13 +775,13 @@ png_get_copyright(png_const_structrp png_ptr)
 #else
 #  ifdef __STDC__
    return PNG_STRING_NEWLINE \
-     "libpng version 1.6.17 - March 26, 2015" PNG_STRING_NEWLINE \
-     "Copyright (c) 1998-2015 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
-     "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
-     "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
-     PNG_STRING_NEWLINE;
+      "libpng version 1.6.19 - November 12, 2015" PNG_STRING_NEWLINE \
+      "Copyright (c) 1998-2015 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
+      "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
+      "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
+      PNG_STRING_NEWLINE;
 #  else
-      return "libpng version 1.6.17 - March 26, 2015\
+   return "libpng version 1.6.19 - November 12, 2015\
       Copyright (c) 1998-2015 Glenn Randers-Pehrson\
       Copyright (c) 1996-1997 Andreas Dilger\
       Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
@@ -811,9 +820,9 @@ png_get_header_version(png_const_structrp png_ptr)
 #ifdef __STDC__
    return PNG_HEADER_VERSION_STRING
 #  ifndef PNG_READ_SUPPORTED
-   "     (NO READ SUPPORT)"
+      " (NO READ SUPPORT)"
 #  endif
-   PNG_STRING_NEWLINE;
+      PNG_STRING_NEWLINE;
 #else
    return PNG_HEADER_VERSION_STRING;
 #endif
@@ -1086,10 +1095,10 @@ png_colorspace_set_gamma(png_const_structrp png_ptr,
       errmsg = "gamma value out of range";
 
 #  ifdef PNG_READ_gAMA_SUPPORTED
-      /* Allow the application to set the gamma value more than once */
-      else if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0 &&
-         (colorspace->flags & PNG_COLORSPACE_FROM_gAMA) != 0)
-         errmsg = "duplicate";
+   /* Allow the application to set the gamma value more than once */
+   else if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0 &&
+      (colorspace->flags & PNG_COLORSPACE_FROM_gAMA) != 0)
+      errmsg = "duplicate";
 #  endif
 
    /* Do nothing if the colorspace is already invalid */
@@ -1130,31 +1139,31 @@ png_colorspace_sync_info(png_const_structrp png_ptr, png_inforp info_ptr)
          PNG_INFO_iCCP);
 
 #     ifdef PNG_COLORSPACE_SUPPORTED
-         /* Clean up the iCCP profile now if it won't be used. */
-         png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, -1/*not used*/);
+      /* Clean up the iCCP profile now if it won't be used. */
+      png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, -1/*not used*/);
 #     else
-         PNG_UNUSED(png_ptr)
+      PNG_UNUSED(png_ptr)
 #     endif
    }
 
    else
    {
 #     ifdef PNG_COLORSPACE_SUPPORTED
-         /* Leave the INFO_iCCP flag set if the pngset.c code has already set
-          * it; this allows a PNG to contain a profile which matches sRGB and
-          * yet still have that profile retrievable by the application.
-          */
-         if ((info_ptr->colorspace.flags & PNG_COLORSPACE_MATCHES_sRGB) != 0)
-            info_ptr->valid |= PNG_INFO_sRGB;
+      /* Leave the INFO_iCCP flag set if the pngset.c code has already set
+       * it; this allows a PNG to contain a profile which matches sRGB and
+       * yet still have that profile retrievable by the application.
+       */
+      if ((info_ptr->colorspace.flags & PNG_COLORSPACE_MATCHES_sRGB) != 0)
+         info_ptr->valid |= PNG_INFO_sRGB;
 
-         else
-            info_ptr->valid &= ~PNG_INFO_sRGB;
+      else
+         info_ptr->valid &= ~PNG_INFO_sRGB;
 
-         if ((info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0)
-            info_ptr->valid |= PNG_INFO_cHRM;
+      if ((info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_ENDPOINTS) != 0)
+         info_ptr->valid |= PNG_INFO_cHRM;
 
-         else
-            info_ptr->valid &= ~PNG_INFO_cHRM;
+      else
+         info_ptr->valid &= ~PNG_INFO_cHRM;
 #     endif
 
       if ((info_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) != 0)
@@ -1235,16 +1244,17 @@ png_XYZ_from_xy(png_XYZ *XYZ, const png_xy *xy)
 
    /* Check xy and, implicitly, z.  Note that wide gamut color spaces typically
     * have end points with 0 tristimulus values (these are impossible end
-    * points, but they are used to cover the possible colors.)
+    * points, but they are used to cover the possible colors).  We check
+    * xy->whitey against 5, not 0, to avoid a possible integer overflow.
     */
-   if (xy->redx < 0 || xy->redx > PNG_FP_1) return 1;
-   if (xy->redy < 0 || xy->redy > PNG_FP_1-xy->redx) return 1;
+   if (xy->redx   < 0 || xy->redx > PNG_FP_1) return 1;
+   if (xy->redy   < 0 || xy->redy > PNG_FP_1-xy->redx) return 1;
    if (xy->greenx < 0 || xy->greenx > PNG_FP_1) return 1;
    if (xy->greeny < 0 || xy->greeny > PNG_FP_1-xy->greenx) return 1;
-   if (xy->bluex < 0 || xy->bluex > PNG_FP_1) return 1;
-   if (xy->bluey < 0 || xy->bluey > PNG_FP_1-xy->bluex) return 1;
+   if (xy->bluex  < 0 || xy->bluex > PNG_FP_1) return 1;
+   if (xy->bluey  < 0 || xy->bluey > PNG_FP_1-xy->bluex) return 1;
    if (xy->whitex < 0 || xy->whitex > PNG_FP_1) return 1;
-   if (xy->whitey < 0 || xy->whitey > PNG_FP_1-xy->whitex) return 1;
+   if (xy->whitey < 5 || xy->whitey > PNG_FP_1-xy->whitex) return 1;
 
    /* The reverse calculation is more difficult because the original tristimulus
     * value had 9 independent values (red,green,blue)x(X,Y,Z) however only 8
@@ -1702,7 +1712,6 @@ png_colorspace_set_chromaticities(png_const_structrp png_ptr,
           */
          colorspace->flags |= PNG_COLORSPACE_INVALID;
          png_error(png_ptr, "internal error checking chromaticities");
-         break;
    }
 
    return 0; /* failed */
@@ -1730,7 +1739,6 @@ png_colorspace_set_endpoints(png_const_structrp png_ptr,
       default:
          colorspace->flags |= PNG_COLORSPACE_INVALID;
          png_error(png_ptr, "internal error checking chromaticities");
-         break;
    }
 
    return 0; /* failed */
@@ -2056,8 +2064,8 @@ png_icc_check_header(png_const_structrp png_ptr, png_colorspacerp colorspace,
    temp = png_get_uint_32(profile+12); /* profile/device class */
    switch (temp)
    {
-      case 0x73636E72: /* 'scnr' */
-      case 0x6D6E7472: /* 'mntr' */
+      case 0x73636e72: /* 'scnr' */
+      case 0x6d6e7472: /* 'mntr' */
       case 0x70727472: /* 'prtr' */
       case 0x73706163: /* 'spac' */
          /* All supported */
@@ -2068,7 +2076,7 @@ png_icc_check_header(png_const_structrp png_ptr, png_colorspacerp colorspace,
          return png_icc_profile_error(png_ptr, colorspace, name, temp,
             "invalid embedded Abstract ICC profile");
 
-      case 0x6C696E6B: /* 'link' */
+      case 0x6c696e6b: /* 'link' */
          /* DeviceLink profiles cannot be interpreted in a non-device specific
           * fashion, if an app uses the AToB0Tag in the profile the results are
           * undefined unless the result is sent to the intended device,
@@ -2078,7 +2086,7 @@ png_icc_check_header(png_const_structrp png_ptr, png_colorspacerp colorspace,
          return png_icc_profile_error(png_ptr, colorspace, name, temp,
             "unexpected DeviceLink ICC profile class");
 
-      case 0x6E6D636C: /* 'nmcl' */
+      case 0x6e6d636c: /* 'nmcl' */
          /* A NamedColor profile is also device specific, however it doesn't
           * contain an AToB0 tag that is open to misinterpretation.  Almost
           * certainly it will fail the tests below.
@@ -2104,8 +2112,8 @@ png_icc_check_header(png_const_structrp png_ptr, png_colorspacerp colorspace,
    temp = png_get_uint_32(profile+20);
    switch (temp)
    {
-      case 0x58595A20: /* 'XYZ ' */
-      case 0x4C616220: /* 'Lab ' */
+      case 0x58595a20: /* 'XYZ ' */
+      case 0x4c616220: /* 'Lab ' */
          break;
 
       default:
@@ -2275,8 +2283,8 @@ png_compare_ICC_profile_with_sRGB(png_const_structrp png_ptr,
          }
 
          /* Length *and* intent must match */
-         if (length == png_sRGB_checks[i].length &&
-            intent == png_sRGB_checks[i].intent)
+         if (length == (png_uint_32) png_sRGB_checks[i].length &&
+            intent == (png_uint_32) png_sRGB_checks[i].intent)
          {
             /* Now calculate the adler32 if not done already. */
             if (adler == 0)
@@ -2843,7 +2851,7 @@ png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
 
       if (fp >= DBL_MIN && fp <= DBL_MAX)
       {
-         int exp_b10;       /* A base 10 exponent */
+         int exp_b10;   /* A base 10 exponent */
          double base;   /* 10^exp_b10 */
 
          /* First extract a base 10 exponent of the number,
@@ -2891,7 +2899,7 @@ png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
           */
 
          {
-            int czero, clead, cdigits;
+            unsigned int czero, clead, cdigits;
             char exponent[10];
 
             /* Allow up to two leading zeros - this will not lengthen
@@ -2921,7 +2929,7 @@ png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
                 * of the loop don't break the number into parts so
                 * that the final digit is rounded.
                 */
-               if (cdigits+czero-clead+1 < (int)precision)
+               if (cdigits+czero+1 < precision+clead)
                   fp = modf(fp, &d);
 
                else
@@ -3027,7 +3035,7 @@ png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
                   *ascii++ = (char)(48 + (int)d), ++cdigits;
                }
             }
-            while (cdigits+czero-clead < (int)precision && fp > DBL_MIN);
+            while (cdigits+czero < precision+clead && fp > DBL_MIN);
 
             /* The total output count (max) is now 4+precision */
 
@@ -3095,7 +3103,7 @@ png_ascii_from_fp(png_const_structrp png_ptr, png_charp ascii, png_size_t size,
             /* Need another size check here for the exponent digits, so
              * this need not be considered above.
              */
-            if ((int)size > cdigits)
+            if (size > cdigits)
             {
                while (cdigits > 0) *ascii++ = exponent[--cdigits];
 
@@ -3143,7 +3151,7 @@ png_ascii_from_fixed(png_const_structrp png_ptr, png_charp ascii,
 
       /* Avoid overflow here on the minimum integer. */
       if (fp < 0)
-         *ascii++ = 45, --size, num = -fp;
+         *ascii++ = 45, num = -fp;
       else
          num = fp;
 
@@ -3674,7 +3682,7 @@ png_exp(png_fixed_point x)
    if (x > 0 && x <= 0xfffff) /* Else overflow or zero (underflow) */
    {
       /* Obtain a 4-bit approximation */
-      png_uint_32 e = png_32bit_exp[(x >> 12) & 0xf];
+      png_uint_32 e = png_32bit_exp[(x >> 12) & 0x0f];
 
       /* Incorporate the low 12 bits - these decrease the returned value by
        * multiplying by a number less than 1 if the bit is set.  The multiplier
@@ -4236,7 +4244,7 @@ png_set_option(png_structrp png_ptr, int option, int onoff)
  * contrib/tools/makesRGB.c.  The actual sRGB transfer curve defined in the
  * specification (see the article at http://en.wikipedia.org/wiki/SRGB)
  * is used, not the gamma=1/2.2 approximation use elsewhere in libpng.
- * The sRGB to linear table is exact (to the nearest 16 bit linear fraction).
+ * The sRGB to linear table is exact (to the nearest 16-bit linear fraction).
  * The inverse (linear to sRGB) table has accuracies as follows:
  *
  * For all possible (255*65535+1) input values:
diff --git a/src/3rdparty/libpng/png.h b/src/3rdparty/libpng/png.h
index 372599bfb47e23343db115e7927628c55e64f8fb..c83051b1ca7949f45ca0a5cfaa71e9456cb1c790 100644
--- a/src/3rdparty/libpng/png.h
+++ b/src/3rdparty/libpng/png.h
@@ -1,7 +1,7 @@
 
 /* png.h - header file for PNG reference library
  *
- * libpng version 1.6.17, March 26, 2015
+ * libpng version 1.6.19, November 12, 2015
  *
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
@@ -11,232 +11,9 @@
  *
  * Authors and maintainers:
  *   libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
- *   libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
- *   libpng versions 0.97, January 1998, through 1.6.17, March 26, 2015: Glenn
+ *   libpng versions 0.89, June 1996, through 0.96, May 1997: Andreas Dilger
+ *   libpng versions 0.97, January 1998, through 1.6.19, November 12, 2015: Glenn
  *   See also "Contributing Authors", below.
- *
- * Note about libpng version numbers:
- *
- *   Due to various miscommunications, unforeseen code incompatibilities
- *   and occasional factors outside the authors' control, version numbering
- *   on the library has not always been consistent and straightforward.
- *   The following table summarizes matters since version 0.89c, which was
- *   the first widely used release:
- *
- *    source                 png.h  png.h  shared-lib
- *    version                string   int  version
- *    -------                ------ -----  ----------
- *    0.89c "1.0 beta 3"     0.89      89  1.0.89
- *    0.90  "1.0 beta 4"     0.90      90  0.90  [should have been 2.0.90]
- *    0.95  "1.0 beta 5"     0.95      95  0.95  [should have been 2.0.95]
- *    0.96  "1.0 beta 6"     0.96      96  0.96  [should have been 2.0.96]
- *    0.97b "1.00.97 beta 7" 1.00.97   97  1.0.1 [should have been 2.0.97]
- *    0.97c                  0.97      97  2.0.97
- *    0.98                   0.98      98  2.0.98
- *    0.99                   0.99      98  2.0.99
- *    0.99a-m                0.99      99  2.0.99
- *    1.00                   1.00     100  2.1.0 [100 should be 10000]
- *    1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]
- *    1.0.1       png.h string is   10001  2.1.0
- *    1.0.1a-e    identical to the  10002  from here on, the shared library
- *    1.0.2       source version)   10002  is 2.V where V is the source code
- *    1.0.2a-b                      10003  version, except as noted.
- *    1.0.3                         10003
- *    1.0.3a-d                      10004
- *    1.0.4                         10004
- *    1.0.4a-f                      10005
- *    1.0.5 (+ 2 patches)           10005
- *    1.0.5a-d                      10006
- *    1.0.5e-r                      10100 (not source compatible)
- *    1.0.5s-v                      10006 (not binary compatible)
- *    1.0.6 (+ 3 patches)           10006 (still binary incompatible)
- *    1.0.6d-f                      10007 (still binary incompatible)
- *    1.0.6g                        10007
- *    1.0.6h                        10007  10.6h (testing xy.z so-numbering)
- *    1.0.6i                        10007  10.6i
- *    1.0.6j                        10007  2.1.0.6j (incompatible with 1.0.0)
- *    1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compatible)
- *    1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compatible)
- *    1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)
- *    1.0.7                    1    10007  (still compatible)
- *    1.0.8beta1-4             1    10008  2.1.0.8beta1-4
- *    1.0.8rc1                 1    10008  2.1.0.8rc1
- *    1.0.8                    1    10008  2.1.0.8
- *    1.0.9beta1-6             1    10009  2.1.0.9beta1-6
- *    1.0.9rc1                 1    10009  2.1.0.9rc1
- *    1.0.9beta7-10            1    10009  2.1.0.9beta7-10
- *    1.0.9rc2                 1    10009  2.1.0.9rc2
- *    1.0.9                    1    10009  2.1.0.9
- *    1.0.10beta1              1    10010  2.1.0.10beta1
- *    1.0.10rc1                1    10010  2.1.0.10rc1
- *    1.0.10                   1    10010  2.1.0.10
- *    1.0.11beta1-3            1    10011  2.1.0.11beta1-3
- *    1.0.11rc1                1    10011  2.1.0.11rc1
- *    1.0.11                   1    10011  2.1.0.11
- *    1.0.12beta1-2            2    10012  2.1.0.12beta1-2
- *    1.0.12rc1                2    10012  2.1.0.12rc1
- *    1.0.12                   2    10012  2.1.0.12
- *    1.1.0a-f                 -    10100  2.1.1.0a-f (branch abandoned)
- *    1.2.0beta1-2             2    10200  2.1.2.0beta1-2
- *    1.2.0beta3-5             3    10200  3.1.2.0beta3-5
- *    1.2.0rc1                 3    10200  3.1.2.0rc1
- *    1.2.0                    3    10200  3.1.2.0
- *    1.2.1beta1-4             3    10201  3.1.2.1beta1-4
- *    1.2.1rc1-2               3    10201  3.1.2.1rc1-2
- *    1.2.1                    3    10201  3.1.2.1
- *    1.2.2beta1-6            12    10202  12.so.0.1.2.2beta1-6
- *    1.0.13beta1             10    10013  10.so.0.1.0.13beta1
- *    1.0.13rc1               10    10013  10.so.0.1.0.13rc1
- *    1.2.2rc1                12    10202  12.so.0.1.2.2rc1
- *    1.0.13                  10    10013  10.so.0.1.0.13
- *    1.2.2                   12    10202  12.so.0.1.2.2
- *    1.2.3rc1-6              12    10203  12.so.0.1.2.3rc1-6
- *    1.2.3                   12    10203  12.so.0.1.2.3
- *    1.2.4beta1-3            13    10204  12.so.0.1.2.4beta1-3
- *    1.0.14rc1               13    10014  10.so.0.1.0.14rc1
- *    1.2.4rc1                13    10204  12.so.0.1.2.4rc1
- *    1.0.14                  10    10014  10.so.0.1.0.14
- *    1.2.4                   13    10204  12.so.0.1.2.4
- *    1.2.5beta1-2            13    10205  12.so.0.1.2.5beta1-2
- *    1.0.15rc1-3             10    10015  10.so.0.1.0.15rc1-3
- *    1.2.5rc1-3              13    10205  12.so.0.1.2.5rc1-3
- *    1.0.15                  10    10015  10.so.0.1.0.15
- *    1.2.5                   13    10205  12.so.0.1.2.5
- *    1.2.6beta1-4            13    10206  12.so.0.1.2.6beta1-4
- *    1.0.16                  10    10016  10.so.0.1.0.16
- *    1.2.6                   13    10206  12.so.0.1.2.6
- *    1.2.7beta1-2            13    10207  12.so.0.1.2.7beta1-2
- *    1.0.17rc1               10    10017  12.so.0.1.0.17rc1
- *    1.2.7rc1                13    10207  12.so.0.1.2.7rc1
- *    1.0.17                  10    10017  12.so.0.1.0.17
- *    1.2.7                   13    10207  12.so.0.1.2.7
- *    1.2.8beta1-5            13    10208  12.so.0.1.2.8beta1-5
- *    1.0.18rc1-5             10    10018  12.so.0.1.0.18rc1-5
- *    1.2.8rc1-5              13    10208  12.so.0.1.2.8rc1-5
- *    1.0.18                  10    10018  12.so.0.1.0.18
- *    1.2.8                   13    10208  12.so.0.1.2.8
- *    1.2.9beta1-3            13    10209  12.so.0.1.2.9beta1-3
- *    1.2.9beta4-11           13    10209  12.so.0.9[.0]
- *    1.2.9rc1                13    10209  12.so.0.9[.0]
- *    1.2.9                   13    10209  12.so.0.9[.0]
- *    1.2.10beta1-7           13    10210  12.so.0.10[.0]
- *    1.2.10rc1-2             13    10210  12.so.0.10[.0]
- *    1.2.10                  13    10210  12.so.0.10[.0]
- *    1.4.0beta1-5            14    10400  14.so.0.0[.0]
- *    1.2.11beta1-4           13    10211  12.so.0.11[.0]
- *    1.4.0beta7-8            14    10400  14.so.0.0[.0]
- *    1.2.11                  13    10211  12.so.0.11[.0]
- *    1.2.12                  13    10212  12.so.0.12[.0]
- *    1.4.0beta9-14           14    10400  14.so.0.0[.0]
- *    1.2.13                  13    10213  12.so.0.13[.0]
- *    1.4.0beta15-36          14    10400  14.so.0.0[.0]
- *    1.4.0beta37-87          14    10400  14.so.14.0[.0]
- *    1.4.0rc01               14    10400  14.so.14.0[.0]
- *    1.4.0beta88-109         14    10400  14.so.14.0[.0]
- *    1.4.0rc02-08            14    10400  14.so.14.0[.0]
- *    1.4.0                   14    10400  14.so.14.0[.0]
- *    1.4.1beta01-03          14    10401  14.so.14.1[.0]
- *    1.4.1rc01               14    10401  14.so.14.1[.0]
- *    1.4.1beta04-12          14    10401  14.so.14.1[.0]
- *    1.4.1                   14    10401  14.so.14.1[.0]
- *    1.4.2                   14    10402  14.so.14.2[.0]
- *    1.4.3                   14    10403  14.so.14.3[.0]
- *    1.4.4                   14    10404  14.so.14.4[.0]
- *    1.5.0beta01-58          15    10500  15.so.15.0[.0]
- *    1.5.0rc01-07            15    10500  15.so.15.0[.0]
- *    1.5.0                   15    10500  15.so.15.0[.0]
- *    1.5.1beta01-11          15    10501  15.so.15.1[.0]
- *    1.5.1rc01-02            15    10501  15.so.15.1[.0]
- *    1.5.1                   15    10501  15.so.15.1[.0]
- *    1.5.2beta01-03          15    10502  15.so.15.2[.0]
- *    1.5.2rc01-03            15    10502  15.so.15.2[.0]
- *    1.5.2                   15    10502  15.so.15.2[.0]
- *    1.5.3beta01-10          15    10503  15.so.15.3[.0]
- *    1.5.3rc01-02            15    10503  15.so.15.3[.0]
- *    1.5.3beta11             15    10503  15.so.15.3[.0]
- *    1.5.3 [omitted]
- *    1.5.4beta01-08          15    10504  15.so.15.4[.0]
- *    1.5.4rc01               15    10504  15.so.15.4[.0]
- *    1.5.4                   15    10504  15.so.15.4[.0]
- *    1.5.5beta01-08          15    10505  15.so.15.5[.0]
- *    1.5.5rc01               15    10505  15.so.15.5[.0]
- *    1.5.5                   15    10505  15.so.15.5[.0]
- *    1.5.6beta01-07          15    10506  15.so.15.6[.0]
- *    1.5.6rc01-03            15    10506  15.so.15.6[.0]
- *    1.5.6                   15    10506  15.so.15.6[.0]
- *    1.5.7beta01-05          15    10507  15.so.15.7[.0]
- *    1.5.7rc01-03            15    10507  15.so.15.7[.0]
- *    1.5.7                   15    10507  15.so.15.7[.0]
- *    1.6.0beta01-40          16    10600  16.so.16.0[.0]
- *    1.6.0rc01-08            16    10600  16.so.16.0[.0]
- *    1.6.0                   16    10600  16.so.16.0[.0]
- *    1.6.1beta01-09          16    10601  16.so.16.1[.0]
- *    1.6.1rc01               16    10601  16.so.16.1[.0]
- *    1.6.1                   16    10601  16.so.16.1[.0]
- *    1.6.2beta01             16    10602  16.so.16.2[.0]
- *    1.6.2rc01-06            16    10602  16.so.16.2[.0]
- *    1.6.2                   16    10602  16.so.16.2[.0]
- *    1.6.3beta01-11          16    10603  16.so.16.3[.0]
- *    1.6.3rc01               16    10603  16.so.16.3[.0]
- *    1.6.3                   16    10603  16.so.16.3[.0]
- *    1.6.4beta01-02          16    10604  16.so.16.4[.0]
- *    1.6.4rc01               16    10604  16.so.16.4[.0]
- *    1.6.4                   16    10604  16.so.16.4[.0]
- *    1.6.5                   16    10605  16.so.16.5[.0]
- *    1.6.6                   16    10606  16.so.16.6[.0]
- *    1.6.7beta01-04          16    10607  16.so.16.7[.0]
- *    1.6.7rc01-03            16    10607  16.so.16.7[.0]
- *    1.6.7                   16    10607  16.so.16.7[.0]
- *    1.6.8beta01-02          16    10608  16.so.16.8[.0]
- *    1.6.8rc01-02            16    10608  16.so.16.8[.0]
- *    1.6.8                   16    10608  16.so.16.8[.0]
- *    1.6.9beta01-04          16    10609  16.so.16.9[.0]
- *    1.6.9rc01-02            16    10609  16.so.16.9[.0]
- *    1.6.9                   16    10609  16.so.16.9[.0]
- *    1.6.10beta01-03         16    10610  16.so.16.10[.0]
- *    1.6.10rc01-03           16    10610  16.so.16.10[.0]
- *    1.6.10                  16    10610  16.so.16.10[.0]
- *    1.6.11beta01-06         16    10611  16.so.16.11[.0]
- *    1.6.11rc01-02           16    10611  16.so.16.11[.0]
- *    1.6.11                  16    10611  16.so.16.11[.0]
- *    1.6.12rc01-03           16    10612  16.so.16.12[.0]
- *    1.6.12                  16    10612  16.so.16.12[.0]
- *    1.6.13beta01-04         16    10613  16.so.16.13[.0]
- *    1.6.13rc01-02           16    10613  16.so.16.13[.0]
- *    1.6.13                  16    10613  16.so.16.13[.0]
- *    1.6.14beta01-07         16    10614  16.so.16.14[.0]
- *    1.6.14rc01-02           16    10614  16.so.16.14[.0]
- *    1.6.14                  16    10614  16.so.16.14[.0]
- *    1.6.15beta01-08         16    10615  16.so.16.15[.0]
- *    1.6.15rc01-03           16    10615  16.so.16.15[.0]
- *    1.6.15                  16    10615  16.so.16.15[.0]
- *    1.6.16beta01-03         16    10616  16.so.16.16[.0]
- *    1.6.16rc01-02           16    10616  16.so.16.16[.0]
- *    1.6.16                  16    10616  16.so.16.16[.0]
- *    1.6.17beta01-06         16    10617  16.so.16.17[.0]
- *    1.6.17rc01-06           16    10617  16.so.16.17[.0]
- *    1.6.17                  16    10617  16.so.16.17[.0]
- *
- *   Henceforth the source version will match the shared-library major
- *   and minor numbers; the shared-library major version number will be
- *   used for changes in backward compatibility, as it is intended.  The
- *   PNG_LIBPNG_VER macro, which is not used within libpng but is available
- *   for applications, is an unsigned integer of the form xyyzz corresponding
- *   to the source version x.y.z (leading zeros in y and z).  Beta versions
- *   were given the previous public release number plus a letter, until
- *   version 1.0.6j; from then on they were given the upcoming public
- *   release number plus "betaNN" or "rcNN".
- *
- *   Binary incompatibility exists only when applications make direct access
- *   to the info_ptr or png_ptr members through png.h, and the compiled
- *   application is loaded with a different version of the library.
- *
- *   DLLNUM will change each time there are forward or backward changes
- *   in binary compatibility (e.g., when a new feature is added).
- *
- * See libpng-manual.txt or libpng.3 for more information.  The PNG
- * specification is available as a W3C Recommendation and as an ISO
- * Specification, <http://www.w3.org/TR/2003/REC-PNG-20031110/
  */
 
 /*
@@ -247,21 +24,18 @@
  *
  * This code is released under the libpng license.
  *
- * libpng versions 1.2.6, August 15, 2004, through 1.6.17, March 26, 2015, are
- * Copyright (c) 2004, 2006-2015 Glenn Randers-Pehrson, and are
- * distributed according to the same disclaimer and license as libpng-1.2.5
- * with the following individual added to the list of Contributing Authors:
- *
- *    Cosmin Truta
- *
- * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
- * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
- * distributed according to the same disclaimer and license as libpng-1.0.6
- * with the following individuals added to the list of Contributing Authors:
+ * libpng versions 1.0.7, July 1, 2000, through 1.6.19, November 12, 2015, are
+ * Copyright (c) 2000-2002, 2004, 2006-2015 Glenn Randers-Pehrson, are
+ * derived from libpng-1.0.6, and are distributed according to the same
+ * disclaimer and license as libpng-1.0.6 with the following individuals
+ * added to the list of Contributing Authors:
  *
  *    Simon-Pierre Cadieux
  *    Eric S. Raymond
+ *    Mans Rullgard
+ *    Cosmin Truta
  *    Gilles Vollant
+ *    James Yu
  *
  * and with the following additions to the disclaimer:
  *
@@ -273,18 +47,20 @@
  *    the user.
  *
  * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
- * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
- * distributed according to the same disclaimer and license as libpng-0.96,
- * with the following individuals added to the list of Contributing Authors:
+ * Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
+ * libpng-0.96, and are distributed according to the same disclaimer and
+ * license as libpng-0.96, with the following individuals added to the list
+ * of Contributing Authors:
  *
  *    Tom Lane
  *    Glenn Randers-Pehrson
  *    Willem van Schaik
  *
  * libpng versions 0.89, June 1996, through 0.96, May 1997, are
- * Copyright (c) 1996, 1997 Andreas Dilger
- * Distributed according to the same disclaimer and license as libpng-0.88,
- * with the following individuals added to the list of Contributing Authors:
+ * Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
+ * and are distributed according to the same disclaimer and license as
+ * libpng-0.88, with the following individuals added to the list of
+ * Contributing Authors:
  *
  *    John Bowler
  *    Kevin Bracey
@@ -294,7 +70,7 @@
  *    Tom Tanner
  *
  * libpng versions 0.5, May 1995, through 0.88, January 1996, are
- * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
+ * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
  *
  * For the purposes of this copyright and license, "Contributing Authors"
  * is defined as the following set of individuals:
@@ -322,29 +98,32 @@
  *   2. Altered versions must be plainly marked as such and must not
  *      be misrepresented as being the original source.
  *
- *   3. This Copyright notice may not be removed or altered from
- *      any source or altered source distribution.
+ *   3. This Copyright notice may not be removed or altered from any
+ *      source or altered source distribution.
  *
  * The Contributing Authors and Group 42, Inc. specifically permit, without
  * fee, and encourage the use of this source code as a component to
  * supporting the PNG file format in commercial products.  If you use this
  * source code in a product, acknowledgment is not required but would be
  * appreciated.
+ *
+ * END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
  */
 
 /*
  * A "png_get_copyright" function is available, for convenient use in "about"
  * boxes and the like:
  *
- *     printf("%s", png_get_copyright(NULL));
+ *    printf("%s", png_get_copyright(NULL));
  *
  * Also, the PNG logo (in PNG format, of course) is supplied in the
  * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  */
 
 /*
- * Libpng is OSI Certified Open Source Software.  OSI Certified is a
- * certification mark of the Open Source Initiative.
+ * Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is
+ * a certification mark of the Open Source Initiative. OSI has not addressed
+ * the additional disclaimers inserted at version 1.0.7.
  */
 
 /*
@@ -355,17 +134,92 @@
  * Thanks to Frank J. T. Wojcik for helping with the documentation.
  */
 
+/* Note about libpng version numbers:
+ *
+ *    Due to various miscommunications, unforeseen code incompatibilities
+ *    and occasional factors outside the authors' control, version numbering
+ *    on the library has not always been consistent and straightforward.
+ *    The following table summarizes matters since version 0.89c, which was
+ *    the first widely used release:
+ *
+ *    source                 png.h  png.h  shared-lib
+ *    version                string   int  version
+ *    -------                ------ -----  ----------
+ *    0.89c "1.0 beta 3"     0.89      89  1.0.89
+ *    0.90  "1.0 beta 4"     0.90      90  0.90  [should have been 2.0.90]
+ *    0.95  "1.0 beta 5"     0.95      95  0.95  [should have been 2.0.95]
+ *    0.96  "1.0 beta 6"     0.96      96  0.96  [should have been 2.0.96]
+ *    0.97b "1.00.97 beta 7" 1.00.97   97  1.0.1 [should have been 2.0.97]
+ *    0.97c                  0.97      97  2.0.97
+ *    0.98                   0.98      98  2.0.98
+ *    0.99                   0.99      98  2.0.99
+ *    0.99a-m                0.99      99  2.0.99
+ *    1.00                   1.00     100  2.1.0 [100 should be 10000]
+ *    1.0.0      (from here on, the   100  2.1.0 [100 should be 10000]
+ *    1.0.1       png.h string is   10001  2.1.0
+ *    1.0.1a-e    identical to the  10002  from here on, the shared library
+ *    1.0.2       source version)   10002  is 2.V where V is the source code
+ *    1.0.2a-b                      10003  version, except as noted.
+ *    1.0.3                         10003
+ *    1.0.3a-d                      10004
+ *    1.0.4                         10004
+ *    1.0.4a-f                      10005
+ *    1.0.5 (+ 2 patches)           10005
+ *    1.0.5a-d                      10006
+ *    1.0.5e-r                      10100 (not source compatible)
+ *    1.0.5s-v                      10006 (not binary compatible)
+ *    1.0.6 (+ 3 patches)           10006 (still binary incompatible)
+ *    1.0.6d-f                      10007 (still binary incompatible)
+ *    1.0.6g                        10007
+ *    1.0.6h                        10007  10.6h (testing xy.z so-numbering)
+ *    1.0.6i                        10007  10.6i
+ *    1.0.6j                        10007  2.1.0.6j (incompatible with 1.0.0)
+ *    1.0.7beta11-14        DLLNUM  10007  2.1.0.7beta11-14 (binary compatible)
+ *    1.0.7beta15-18           1    10007  2.1.0.7beta15-18 (binary compatible)
+ *    1.0.7rc1-2               1    10007  2.1.0.7rc1-2 (binary compatible)
+ *    1.0.7                    1    10007  (still compatible)
+ *    ...
+ *    1.0.19                  10    10019  10.so.0.19[.0]
+ *    ...
+ *    1.2.53                  13    10253  12.so.0.53[.0]
+ *    ...
+ *    1.5.23                  15    10523  15.so.15.23[.0]
+ *    ...
+ *    1.6.19                  16    10619  16.so.16.19[.0]
+ *
+ *    Henceforth the source version will match the shared-library major
+ *    and minor numbers; the shared-library major version number will be
+ *    used for changes in backward compatibility, as it is intended.  The
+ *    PNG_LIBPNG_VER macro, which is not used within libpng but is available
+ *    for applications, is an unsigned integer of the form xyyzz corresponding
+ *    to the source version x.y.z (leading zeros in y and z).  Beta versions
+ *    were given the previous public release number plus a letter, until
+ *    version 1.0.6j; from then on they were given the upcoming public
+ *    release number plus "betaNN" or "rcNN".
+ *
+ *    Binary incompatibility exists only when applications make direct access
+ *    to the info_ptr or png_ptr members through png.h, and the compiled
+ *    application is loaded with a different version of the library.
+ *
+ *    DLLNUM will change each time there are forward or backward changes
+ *    in binary compatibility (e.g., when a new feature is added).
+ *
+ * See libpng.txt or libpng.3 for more information.  The PNG specification
+ * is available as a W3C Recommendation and as an ISO Specification,
+ * <http://www.w3.org/TR/2003/REC-PNG-20031110/
+ */
+
 /*
  * Y2K compliance in libpng:
  * =========================
  *
- *    March 26, 2015
+ *    November 12, 2015
  *
  *    Since the PNG Development group is an ad-hoc body, we can't make
  *    an official declaration.
  *
  *    This is your unofficial assurance that libpng from version 0.71 and
- *    upward through 1.6.17 are Y2K compliant.  It is my belief that
+ *    upward through 1.6.19 are Y2K compliant.  It is my belief that
  *    earlier versions were also Y2K compliant.
  *
  *    Libpng only has two year fields.  One is a 2-byte unsigned integer
@@ -427,9 +281,9 @@
  */
 
 /* Version information for png.h - this should match the version in png.c */
-#define PNG_LIBPNG_VER_STRING "1.6.17"
+#define PNG_LIBPNG_VER_STRING "1.6.19"
 #define PNG_HEADER_VERSION_STRING \
-     " libpng version 1.6.17 - March 26, 2015\n"
+     " libpng version 1.6.19 - November 12, 2015\n"
 
 #define PNG_LIBPNG_VER_SONUM   16
 #define PNG_LIBPNG_VER_DLLNUM  16
@@ -437,7 +291,7 @@
 /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
 #define PNG_LIBPNG_VER_MAJOR   1
 #define PNG_LIBPNG_VER_MINOR   6
-#define PNG_LIBPNG_VER_RELEASE 17
+#define PNG_LIBPNG_VER_RELEASE 19
 
 /* This should match the numeric part of the final component of
  * PNG_LIBPNG_VER_STRING, omitting any leading zero:
@@ -468,7 +322,7 @@
  * version 1.0.0 was mis-numbered 100 instead of 10000).  From
  * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release
  */
-#define PNG_LIBPNG_VER 10617 /* 1.6.17 */
+#define PNG_LIBPNG_VER 10619 /* 1.6.19 */
 
 /* Library configuration: these options cannot be changed after
  * the library has been built.
@@ -525,17 +379,22 @@ extern "C" {
 
 /* This file is arranged in several sections:
  *
- * 1. Any configuration options that can be specified by for the application
+ * 1. [omitted]
+ * 2. Any configuration options that can be specified by for the application
  *    code when it is built.  (Build time configuration is in pnglibconf.h)
- * 2. Type definitions (base types are defined in pngconf.h), structure
+ * 3. Type definitions (base types are defined in pngconf.h), structure
  *    definitions.
- * 3. Exported library functions.
- * 4. Simplified API.
+ * 4. Exported library functions.
+ * 5. Simplified API.
+ * 6. Implementation options.
  *
  * The library source code has additional files (principally pngpriv.h) that
  * allow configuration of the library.
  */
-/* Section 1: run time configuration
+
+/* Section 1: [omitted] */
+
+/* Section 2: run time configuration
  * See pnglibconf.h for build time configuration
  *
  * Run time configuration allows the application to choose between
@@ -565,7 +424,7 @@ extern "C" {
  * Otherwise the calls are mapped to png_error.
  */
 
-/* Section 2: type definitions, including structures and compile time
+/* Section 3: type definitions, including structures and compile time
  * constants.
  * See pngconf.h for base types that vary by machine/system
  */
@@ -573,7 +432,7 @@ extern "C" {
 /* This triggers a compiler error in png.c, if png.c and png.h
  * do not agree upon the version number.
  */
-typedef char* png_libpng_version_1_6_17;
+typedef char* png_libpng_version_1_6_19;
 
 /* Basic control structions.  Read libpng-manual.txt or libpng.3 for more info.
  *
@@ -889,7 +748,9 @@ typedef png_unknown_chunk * * png_unknown_chunkpp;
 #define PNG_INFO_iCCP 0x1000   /* ESR, 1.0.6 */
 #define PNG_INFO_sPLT 0x2000   /* ESR, 1.0.6 */
 #define PNG_INFO_sCAL 0x4000   /* ESR, 1.0.6 */
+#if INT_MAX >= 0x8000 /* else this might break */
 #define PNG_INFO_IDAT 0x8000   /* ESR, 1.0.6 */
+#endif
 
 /* This is used for the transformation routines, as some of them
  * change these values for the row.  It also should enable using
@@ -993,7 +854,9 @@ PNG_FUNCTION(void, (PNGCAPI *png_longjmp_ptr), PNGARG((jmp_buf, int)), typedef);
 #define PNG_TRANSFORM_GRAY_TO_RGB   0x2000      /* read only */
 /* Added to libpng-1.5.4 */
 #define PNG_TRANSFORM_EXPAND_16     0x4000      /* read only */
+#if INT_MAX >= 0x8000 /* else this might break */
 #define PNG_TRANSFORM_SCALE_16      0x8000      /* read only */
+#endif
 
 /* Flags for MNG supported features */
 #define PNG_FLAG_MNG_EMPTY_PLTE     0x01
@@ -1010,7 +873,7 @@ typedef PNG_CALLBACK(png_voidp, *png_malloc_ptr, (png_structp,
     png_alloc_size_t));
 typedef PNG_CALLBACK(void, *png_free_ptr, (png_structp, png_voidp));
 
-/* Section 3: exported functions
+/* Section 4: exported functions
  * Here are the function definitions most commonly used.  This is not
  * the place to find out how to use libpng.  See libpng-manual.txt for the
  * full explanation, see example.c for the summary.  This just provides
@@ -1383,13 +1246,13 @@ PNG_EXPORT(38, void, png_set_invert_alpha, (png_structrp png_ptr));
 #endif
 
 #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
-/* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
+/* Add a filler byte to 8-bit or 16-bit Gray or 24-bit or 48-bit RGB images. */
 PNG_EXPORT(39, void, png_set_filler, (png_structrp png_ptr, png_uint_32 filler,
     int flags));
 /* The values of the PNG_FILLER_ defines should NOT be changed */
 #  define PNG_FILLER_BEFORE 0
 #  define PNG_FILLER_AFTER 1
-/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
+/* Add an alpha byte to 8-bit or 16-bit Gray or 24-bit or 48-bit RGB images. */
 PNG_EXPORT(40, void, png_set_add_alpha, (png_structrp png_ptr,
     png_uint_32 filler, int flags));
 #endif /* READ_FILLER || WRITE_FILLER */
@@ -1623,35 +1486,7 @@ PNG_EXPORT(67, void, png_set_filter, (png_structrp png_ptr, int method,
 #define PNG_FILTER_VALUE_LAST  5
 
 #ifdef PNG_WRITE_SUPPORTED
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* EXPERIMENTAL */
-/* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
- * defines, either the default (minimum-sum-of-absolute-differences), or
- * the experimental method (weighted-minimum-sum-of-absolute-differences).
- *
- * Weights are factors >= 1.0, indicating how important it is to keep the
- * filter type consistent between rows.  Larger numbers mean the current
- * filter is that many times as likely to be the same as the "num_weights"
- * previous filters.  This is cumulative for each previous row with a weight.
- * There needs to be "num_weights" values in "filter_weights", or it can be
- * NULL if the weights aren't being specified.  Weights have no influence on
- * the selection of the first row filter.  Well chosen weights can (in theory)
- * improve the compression for a given image.
- *
- * Costs are factors >= 1.0 indicating the relative decoding costs of a
- * filter type.  Higher costs indicate more decoding expense, and are
- * therefore less likely to be selected over a filter with lower computational
- * costs.  There needs to be a value in "filter_costs" for each valid filter
- * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
- * setting the costs.  Costs try to improve the speed of decompression without
- * unduly increasing the compressed image size.
- *
- * A negative weight or cost indicates the default value is to be used, and
- * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
- * The default values for both weights and costs are currently 1.0, but may
- * change if good general weighting/cost heuristics can be found.  If both
- * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
- * to the UNWEIGHTED method, but with added encoding time/computation.
- */
+#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */
 PNG_FP_EXPORT(68, void, png_set_filter_heuristics, (png_structrp png_ptr,
     int heuristic_method, int num_weights, png_const_doublep filter_weights,
     png_const_doublep filter_costs))
@@ -1661,9 +1496,7 @@ PNG_FIXED_EXPORT(209, void, png_set_filter_heuristics_fixed,
     png_const_fixed_point_p filter_costs))
 #endif /* WRITE_WEIGHTED_FILTER */
 
-/* Heuristic used for row filter selection.  These defines should NOT be
- * changed.
- */
+/* The following are no longer used and will be removed from libpng-1.7: */
 #define PNG_FILTER_HEURISTIC_DEFAULT    0  /* Currently "UNWEIGHTED" */
 #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1  /* Used by libpng < 0.95 */
 #define PNG_FILTER_HEURISTIC_WEIGHTED   2  /* Experimental feature */
@@ -2744,7 +2577,7 @@ PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i));
 
 #  define PNG_get_int_32(buf) \
      ((png_int_32)((*(buf) & 0x80) \
-      ? -((png_int_32)((png_get_uint_32(buf) ^ 0xffffffffL) + 1)) \
+      ? -((png_int_32)(((png_get_uint_32(buf)^0xffffffffU)+1U)&0x7fffffffU)) \
       : (png_int_32)png_get_uint_32(buf)))
 
    /* If PNG_PREFIX is defined the same thing as below happens in pnglibconf.h,
@@ -2764,10 +2597,17 @@ PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i));
 #  endif
 #endif
 
-#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) || \
-    defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
+#ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
+PNG_EXPORT(242, void, png_set_check_for_invalid_index,
+    (png_structrp png_ptr, int allowed));
+#  ifdef PNG_GET_PALETTE_MAX_SUPPORTED
+PNG_EXPORT(243, int, png_get_palette_max, (png_const_structp png_ptr,
+    png_const_infop info_ptr));
+#  endif
+#endif /* CHECK_FOR_INVALID_INDEX */
+
 /*******************************************************************************
- *  SIMPLIFIED API
+ * Section 5: SIMPLIFIED API
  *******************************************************************************
  *
  * Please read the documentation in libpng-manual.txt (TODO: write said
@@ -2783,8 +2623,9 @@ PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i));
  *
  * To read a PNG file using the simplified API:
  *
- * 1) Declare a 'png_image' structure (see below) on the stack and set the
- *    version field to PNG_IMAGE_VERSION.
+ * 1) Declare a 'png_image' structure (see below) on the stack, set the
+ *    version field to PNG_IMAGE_VERSION and the 'opaque' pointer to NULL
+ *    (this is REQUIRED, your program may crash if you don't do it.)
  * 2) Call the appropriate png_image_begin_read... function.
  * 3) Set the png_image 'format' member to the required sample format.
  * 4) Allocate a buffer for the image and, if required, the color-map.
@@ -2811,6 +2652,9 @@ PNG_EXPORT(207, void, png_save_uint_16, (png_bytep buf, unsigned int i));
  * when it is being read or defines the in-memory format of an image that you
  * need to write:
  */
+#if defined(PNG_SIMPLIFIED_READ_SUPPORTED) || \
+    defined(PNG_SIMPLIFIED_WRITE_SUPPORTED)
+
 #define PNG_IMAGE_VERSION 1
 
 typedef struct png_control *png_controlp;
@@ -2910,7 +2754,7 @@ typedef struct
  * called to read or write the color-map and set the format correctly for the
  * image data.  Do not set the PNG_FORMAT_FLAG_COLORMAP bit directly!
  *
- * NOTE: libpng can be built with particular features disabled, if you see
+ * NOTE: libpng can be built with particular features disabled. If you see
  * compiler errors because the definition of one of the following flags has been
  * compiled out it is because libpng does not have the required support.  It is
  * possible, however, for the libpng configuration to enable the format on just
@@ -2922,7 +2766,7 @@ typedef struct
  */
 #define PNG_FORMAT_FLAG_ALPHA    0x01U /* format with an alpha channel */
 #define PNG_FORMAT_FLAG_COLOR    0x02U /* color format: otherwise grayscale */
-#define PNG_FORMAT_FLAG_LINEAR   0x04U /* 2 byte channels else 1 byte */
+#define PNG_FORMAT_FLAG_LINEAR   0x04U /* 2-byte channels else 1-byte */
 #define PNG_FORMAT_FLAG_COLORMAP 0x08U /* image data is color-mapped */
 
 #ifdef PNG_FORMAT_BGR_SUPPORTED
@@ -3209,9 +3053,11 @@ PNG_EXPORT(240, int, png_image_write_to_stdio, (png_imagep image, FILE *file,
  *
  * With all APIs row_stride is handled as in the read APIs - it is the spacing
  * from one row to the next in component sized units (1 or 2 bytes) and if
- * negative indicates a bottom-up row layout in the buffer.
+ * negative indicates a bottom-up row layout in the buffer.  If row_stride is zero,
+ * libpng will calculate it for you from the image width and number of channels.
  *
- * Note that the write API does not support interlacing or sub-8-bit pixels.
+ * Note that the write API does not support interlacing, sub-8-bit pixels, indexed
+ * PNG (color_type 3) or most ancillary chunks.
  */
 #endif /* STDIO */
 #endif /* SIMPLIFIED_WRITE */
@@ -3220,17 +3066,8 @@ PNG_EXPORT(240, int, png_image_write_to_stdio, (png_imagep image, FILE *file,
  ******************************************************************************/
 #endif /* SIMPLIFIED_{READ|WRITE} */
 
-#ifdef PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
-PNG_EXPORT(242, void, png_set_check_for_invalid_index,
-    (png_structrp png_ptr, int allowed));
-#  ifdef PNG_GET_PALETTE_MAX_SUPPORTED
-PNG_EXPORT(243, int, png_get_palette_max, (png_const_structp png_ptr,
-    png_const_infop info_ptr));
-#  endif
-#endif /* CHECK_FOR_INVALID_INDEX */
-
 /*******************************************************************************
- *  IMPLEMENTATION OPTIONS
+ * Section 6: IMPLEMENTATION OPTIONS
  *******************************************************************************
  *
  * Support for arbitrary implementation-specific optimizations.  The API allows
diff --git a/src/3rdparty/libpng/pngconf.h b/src/3rdparty/libpng/pngconf.h
index 3f9493e438454ff5bbf4746977617f26dea04ce8..f1b795b478406a35bcc0f07ad0c663bebb492453 100644
--- a/src/3rdparty/libpng/pngconf.h
+++ b/src/3rdparty/libpng/pngconf.h
@@ -1,7 +1,7 @@
 
 /* pngconf.h - machine configurable file for libpng
  *
- * libpng version 1.6.17, March 26, 2015
+ * libpng version 1.6.19, July 23, 2015
  *
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
@@ -63,7 +63,7 @@
  */
 #define PNG_CONST const /* backward compatibility only */
 
-/* This controls optimization of the reading of 16 and 32 bit values
+/* This controls optimization of the reading of 16-bit and 32-bit values
  * from PNG files.  It can be set on a per-app-file basis - it
  * just changes whether a macro is used when the function is called.
  * The library builder sets the default; if read functions are not
@@ -295,11 +295,11 @@
     * table entries, so we discard it here.  See the .dfn files in the
     * scripts directory.
     */
-#ifndef PNG_EXPORTA
 
-#  define PNG_EXPORTA(ordinal, type, name, args, attributes)\
-      PNG_FUNCTION(PNG_EXPORT_TYPE(type),(PNGAPI name),PNGARG(args), \
-        extern attributes)
+#ifndef PNG_EXPORTA
+#  define PNG_EXPORTA(ordinal, type, name, args, attributes) \
+      PNG_FUNCTION(PNG_EXPORT_TYPE(type), (PNGAPI name), PNGARG(args), \
+      PNG_LINKAGE_API attributes)
 #endif
 
 /* ANSI-C (C90) does not permit a macro to be invoked with an empty argument,
@@ -307,7 +307,7 @@
  */
 #define PNG_EMPTY /*empty list*/
 
-#define PNG_EXPORT(ordinal, type, name, args)\
+#define PNG_EXPORT(ordinal, type, name, args) \
    PNG_EXPORTA(ordinal, type, name, args, PNG_EMPTY)
 
 /* Use PNG_REMOVED to comment out a removed interface. */
@@ -480,7 +480,7 @@
 #if CHAR_BIT == 8 && UCHAR_MAX == 255
    typedef unsigned char png_byte;
 #else
-#  error "libpng requires 8 bit bytes"
+#  error "libpng requires 8-bit bytes"
 #endif
 
 #if INT_MIN == -32768 && INT_MAX == 32767
@@ -488,7 +488,7 @@
 #elif SHRT_MIN == -32768 && SHRT_MAX == 32767
    typedef short png_int_16;
 #else
-#  error "libpng requires a signed 16 bit type"
+#  error "libpng requires a signed 16-bit type"
 #endif
 
 #if UINT_MAX == 65535
@@ -496,7 +496,7 @@
 #elif USHRT_MAX == 65535
    typedef unsigned short png_uint_16;
 #else
-#  error "libpng requires an unsigned 16 bit type"
+#  error "libpng requires an unsigned 16-bit type"
 #endif
 
 #if INT_MIN < -2147483646 && INT_MAX > 2147483646
@@ -504,7 +504,7 @@
 #elif LONG_MIN < -2147483646 && LONG_MAX > 2147483646
    typedef long int png_int_32;
 #else
-#  error "libpng requires a signed 32 bit (or more) type"
+#  error "libpng requires a signed 32-bit (or more) type"
 #endif
 
 #if UINT_MAX > 4294967294
@@ -512,7 +512,7 @@
 #elif ULONG_MAX > 4294967294
    typedef unsigned long int png_uint_32;
 #else
-#  error "libpng requires an unsigned 32 bit (or more) type"
+#  error "libpng requires an unsigned 32-bit (or more) type"
 #endif
 
 /* Prior to 1.6.0 it was possible to disable the use of size_t, 1.6.0, however,
diff --git a/src/3rdparty/libpng/pnglibconf.h b/src/3rdparty/libpng/pnglibconf.h
index f0fdcf8068c816aa48f774085494e7d8a5162abe..8b6da9eb2c74a8bcf21310948f5ae0777ccbb033 100644
--- a/src/3rdparty/libpng/pnglibconf.h
+++ b/src/3rdparty/libpng/pnglibconf.h
@@ -1,8 +1,6 @@
-/* libpng 1.6.17 STANDARD API DEFINITION */
-
 /* pnglibconf.h - library build configuration */
 
-/* Libpng version 1.6.17 - March 26, 2015 */
+/* libpng version 1.6.19, July 23, 2015 */
 
 /* Copyright (c) 1998-2014 Glenn Randers-Pehrson */
 
@@ -196,6 +194,10 @@
 #define PNG_GAMMA_THRESHOLD_FIXED 5000
 #define PNG_IDAT_READ_SIZE PNG_ZBUF_SIZE
 #define PNG_INFLATE_BUF_SIZE 1024
+#define PNG_LINKAGE_API extern
+#define PNG_LINKAGE_CALLBACK extern
+#define PNG_LINKAGE_DATA extern
+#define PNG_LINKAGE_FUNCTION extern
 #define PNG_MAX_GAMMA_8 11
 #define PNG_QUANTIZE_BLUE_BITS 5
 #define PNG_QUANTIZE_GREEN_BITS 5
diff --git a/src/3rdparty/libpng/pngmem.c b/src/3rdparty/libpng/pngmem.c
index 8b157e54d2a416a5862b17f31a6f909f74cee704..45ac5579b2119d11241c9a9a377e26c6d34d438c 100644
--- a/src/3rdparty/libpng/pngmem.c
+++ b/src/3rdparty/libpng/pngmem.c
@@ -77,6 +77,9 @@ png_malloc_base,(png_const_structrp png_ptr, png_alloc_size_t size),
    PNG_UNUSED(png_ptr)
 #endif
 
+   /* Some compilers complain that this is always true.  However, it
+    * can be false when integer overflow happens.
+    */
    if (size > 0 && size <= PNG_SIZE_MAX
 #     ifdef PNG_MAX_MALLOC_64K
          && size <= 65536U
diff --git a/src/3rdparty/libpng/pngpread.c b/src/3rdparty/libpng/pngpread.c
index 823dcad8c00dc39d81ea2c8a1faaafd524f08075..9f68f99023289b2b7ac006e67afcd3ac3ab1b3b6 100644
--- a/src/3rdparty/libpng/pngpread.c
+++ b/src/3rdparty/libpng/pngpread.c
@@ -1,7 +1,7 @@
 
 /* pngpread.c - read a png file in push mode
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.18 [July 23, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -19,7 +19,6 @@
 #define PNG_READ_SIG_MODE   0
 #define PNG_READ_CHUNK_MODE 1
 #define PNG_READ_IDAT_MODE  2
-#define PNG_SKIP_MODE       3
 #define PNG_READ_tEXt_MODE  4
 #define PNG_READ_zTXt_MODE  5
 #define PNG_READ_DONE_MODE  6
@@ -78,32 +77,14 @@ png_process_data_pause(png_structrp png_ptr, int save)
 png_uint_32 PNGAPI
 png_process_data_skip(png_structrp png_ptr)
 {
-   png_uint_32 remaining = 0;
-
-   if (png_ptr != NULL && png_ptr->process_mode == PNG_SKIP_MODE &&
-      png_ptr->skip_length > 0)
-   {
-      /* At the end of png_process_data the buffer size must be 0 (see the loop
-       * above) so we can detect a broken call here:
-       */
-      if (png_ptr->buffer_size != 0)
-         png_error(png_ptr,
-            "png_process_data_skip called inside png_process_data");
-
-      /* If is impossible for there to be a saved buffer at this point -
-       * otherwise we could not be in SKIP mode.  This will also happen if
-       * png_process_skip is called inside png_process_data (but only very
-       * rarely.)
-       */
-      if (png_ptr->save_buffer_size != 0)
-         png_error(png_ptr, "png_process_data_skip called with saved data");
-
-      remaining = png_ptr->skip_length;
-      png_ptr->skip_length = 0;
-      png_ptr->process_mode = PNG_READ_CHUNK_MODE;
-   }
-
-   return remaining;
+  /* TODO: Deprecate and remove this API.
+   * Somewhere the implementation of this seems to have been lost,
+   * or abandoned.  It was only to support some internal back-door access
+   * to png_struct) in libpng-1.4.x.
+   */
+   png_app_warning(png_ptr,
+"png_process_data_skip is not implemented in any current version of libpng");
+   return 0;
 }
 
 /* What we do with the incoming data depends on what we were previously
@@ -135,12 +116,6 @@ png_process_some_data(png_structrp png_ptr, png_inforp info_ptr)
          break;
       }
 
-      case PNG_SKIP_MODE:
-      {
-         png_push_crc_finish(png_ptr);
-         break;
-      }
-
       default:
       {
          png_ptr->buffer_size = 0;
@@ -159,7 +134,7 @@ void /* PRIVATE */
 png_push_read_sig(png_structrp png_ptr, png_inforp info_ptr)
 {
    png_size_t num_checked = png_ptr->sig_bytes, /* SAFE, does not exceed 8 */ 
-             num_to_check = 8 - num_checked;
+       num_to_check = 8 - num_checked;
 
    if (png_ptr->buffer_size < num_to_check)
    {
@@ -439,69 +414,6 @@ png_push_read_chunk(png_structrp png_ptr, png_inforp info_ptr)
    png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
 }
 
-void /* PRIVATE */
-png_push_crc_skip(png_structrp png_ptr, png_uint_32 skip)
-{
-   png_ptr->process_mode = PNG_SKIP_MODE;
-   png_ptr->skip_length = skip;
-}
-
-void /* PRIVATE */
-png_push_crc_finish(png_structrp png_ptr)
-{
-   if (png_ptr->skip_length != 0 && png_ptr->save_buffer_size != 0)
-   {
-      png_size_t save_size = png_ptr->save_buffer_size;
-      png_uint_32 skip_length = png_ptr->skip_length;
-
-      /* We want the smaller of 'skip_length' and 'save_buffer_size', but
-       * they are of different types and we don't know which variable has the
-       * fewest bits.  Carefully select the smaller and cast it to the type of
-       * the larger - this cannot overflow.  Do not cast in the following test
-       * - it will break on either 16 or 64 bit platforms.
-       */
-      if (skip_length < save_size)
-         save_size = (png_size_t)skip_length;
-
-      else
-         skip_length = (png_uint_32)save_size;
-
-      png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
-
-      png_ptr->skip_length -= skip_length;
-      png_ptr->buffer_size -= save_size;
-      png_ptr->save_buffer_size -= save_size;
-      png_ptr->save_buffer_ptr += save_size;
-   }
-   if (png_ptr->skip_length != 0 && png_ptr->current_buffer_size != 0)
-   {
-      png_size_t save_size = png_ptr->current_buffer_size;
-      png_uint_32 skip_length = png_ptr->skip_length;
-
-      /* We want the smaller of 'skip_length' and 'current_buffer_size', here,
-       * the same problem exists as above and the same solution.
-       */
-      if (skip_length < save_size)
-         save_size = (png_size_t)skip_length;
-
-      else
-         skip_length = (png_uint_32)save_size;
-
-      png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
-
-      png_ptr->skip_length -= skip_length;
-      png_ptr->buffer_size -= save_size;
-      png_ptr->current_buffer_size -= save_size;
-      png_ptr->current_buffer_ptr += save_size;
-   }
-   if (png_ptr->skip_length == 0)
-   {
-      PNG_PUSH_SAVE_BUFFER_IF_LT(4)
-      png_crc_finish(png_ptr, 0);
-      png_ptr->process_mode = PNG_READ_CHUNK_MODE;
-   }
-}
-
 void PNGCBAPI
 png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
 {
@@ -584,13 +496,11 @@ png_push_save_buffer(png_structrp png_ptr)
       if (png_ptr->save_buffer == NULL)
       {
          png_free(png_ptr, old_buffer);
-         old_buffer = NULL;
          png_error(png_ptr, "Insufficient memory for save_buffer");
       }
 
       memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
       png_free(png_ptr, old_buffer);
-      old_buffer = NULL;
       png_ptr->save_buffer_max = new_max;
    }
    if (png_ptr->current_buffer_size)
@@ -653,7 +563,7 @@ png_push_read_IDAT(png_structrp png_ptr)
        * are of different types and we don't know which variable has the fewest
        * bits.  Carefully select the smaller and cast it to the type of the
        * larger - this cannot overflow.  Do not cast in the following test - it
-       * will break on either 16 or 64 bit platforms.
+       * will break on either 16-bit or 64-bit platforms.
        */
       if (idat_size < save_size)
          save_size = (png_size_t)idat_size;
@@ -696,6 +606,7 @@ png_push_read_IDAT(png_structrp png_ptr)
       png_ptr->current_buffer_size -= save_size;
       png_ptr->current_buffer_ptr += save_size;
    }
+
    if (png_ptr->idat_size == 0)
    {
       PNG_PUSH_SAVE_BUFFER_IF_LT(4)
diff --git a/src/3rdparty/libpng/pngpriv.h b/src/3rdparty/libpng/pngpriv.h
index 7185444f2ceb6ae961016789349d624d7aad5603..f7a45477a4c189f413573164865919db177671d6 100644
--- a/src/3rdparty/libpng/pngpriv.h
+++ b/src/3rdparty/libpng/pngpriv.h
@@ -1,7 +1,7 @@
 
 /* pngpriv.h - private declarations for use inside libpng
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.18 [July 23, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -124,8 +124,12 @@
     * to compile with an appropriate #error if ALIGNED_MEMORY has been turned
     * off.
     *
-    * Note that gcc-4.9 defines __ARM_NEON instead of __ARM_NEON__, so we
-    * check both variants.
+    * Note that gcc-4.9 defines __ARM_NEON instead of the deprecated
+    * __ARM_NEON__, so we check both variants.
+    *
+    * To disable ARM_NEON optimizations entirely, and skip compiling the
+    * associated assembler code, pass --enable-arm-neon=no to configure
+    * or put -DPNG_ARM_NEON_OPT=0 in CPPFLAGS.
     */
 #  if (defined(__ARM_NEON__) || defined(__ARM_NEON)) && \
    defined(PNG_ALIGNED_MEMORY_SUPPORTED)
@@ -259,17 +263,18 @@
  * always be used to declare an extern data or function object in this file.
  */
 #ifndef PNG_INTERNAL_DATA
-#  define PNG_INTERNAL_DATA(type, name, array) extern type name array
+#  define PNG_INTERNAL_DATA(type, name, array) PNG_LINKAGE_DATA type name array
 #endif
 
 #ifndef PNG_INTERNAL_FUNCTION
 #  define PNG_INTERNAL_FUNCTION(type, name, args, attributes)\
-      extern PNG_FUNCTION(type, name, args, PNG_EMPTY attributes)
+      PNG_LINKAGE_FUNCTION PNG_FUNCTION(type, name, args, PNG_EMPTY attributes)
 #endif
 
 #ifndef PNG_INTERNAL_CALLBACK
 #  define PNG_INTERNAL_CALLBACK(type, name, args, attributes)\
-      extern PNG_FUNCTION(type, (PNGCBAPI name), args, PNG_EMPTY attributes)
+      PNG_LINKAGE_CALLBACK PNG_FUNCTION(type, (PNGCBAPI name), args,\
+         PNG_EMPTY attributes)
 #endif
 
 /* If floating or fixed point APIs are disabled they may still be compiled
@@ -307,6 +312,22 @@
 #  define PNG_DLL_EXPORT
 #endif
 
+/* This is a global switch to set the compilation for an installed system
+ * (a release build).  It can be set for testing debug builds to ensure that
+ * they will compile when the build type is switched to RC or STABLE, the
+ * default is just to use PNG_LIBPNG_BUILD_BASE_TYPE.  Set this in CPPFLAGS
+ * with either:
+ *
+ *   -DPNG_RELEASE_BUILD Turns on the release compile path
+ *   -DPNG_RELEASE_BUILD=0 Turns it off
+ * or in your pngusr.h with
+ *   #define PNG_RELEASE_BUILD=1 Turns on the release compile path
+ *   #define PNG_RELEASE_BUILD=0 Turns it off
+ */
+#ifndef PNG_RELEASE_BUILD
+#  define PNG_RELEASE_BUILD (PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC)
+#endif
+
 /* SECURITY and SAFETY:
  *
  * libpng is built with support for internal limits on image dimensions and
@@ -568,10 +589,6 @@
 #define PNG_STRUCT_PNG   0x0001
 #define PNG_STRUCT_INFO  0x0002
 
-/* Scaling factor for filter heuristic weighting calculations */
-#define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
-#define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
-
 /* Flags for the png_ptr->flags rather than declaring a byte for each one */
 #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY     0x0001
 #define PNG_FLAG_ZSTREAM_INITIALIZED      0x0002 /* Added to libpng-1.6.0 */
@@ -662,7 +679,7 @@
 /* The fixed point conversion performs range checking and evaluates
  * its argument multiple times, so must be used with care.  The
  * range checking uses the PNG specification values for a signed
- * 32 bit fixed point value except that the values are deliberately
+ * 32-bit fixed point value except that the values are deliberately
  * rounded-to-zero to an integral value - 21474 (21474.83 is roughly
  * (2^31-1) * 100000). 's' is a string that describes the value being
  * converted.
@@ -809,7 +826,7 @@
     */
 #endif
 
-/* This is used for 16 bit gamma tables -- only the top level pointers are
+/* This is used for 16-bit gamma tables -- only the top level pointers are
  * const; this could be changed:
  */
 typedef const png_uint_16p * png_const_uint_16pp;
@@ -1386,10 +1403,6 @@ PNG_INTERNAL_FUNCTION(void,png_push_read_chunk,(png_structrp png_ptr,
 PNG_INTERNAL_FUNCTION(void,png_push_read_sig,(png_structrp png_ptr,
     png_inforp info_ptr),PNG_EMPTY);
 PNG_INTERNAL_FUNCTION(void,png_push_check_crc,(png_structrp png_ptr),PNG_EMPTY);
-PNG_INTERNAL_FUNCTION(void,png_push_crc_skip,(png_structrp png_ptr,
-    png_uint_32 length),PNG_EMPTY);
-PNG_INTERNAL_FUNCTION(void,png_push_crc_finish,(png_structrp png_ptr),
-    PNG_EMPTY);
 PNG_INTERNAL_FUNCTION(void,png_push_save_buffer,(png_structrp png_ptr),
     PNG_EMPTY);
 PNG_INTERNAL_FUNCTION(void,png_push_restore_buffer,(png_structrp png_ptr,
diff --git a/src/3rdparty/libpng/pngread.c b/src/3rdparty/libpng/pngread.c
index 6764dbe561862f02ec8dd9a4226b6028714ad746..48aae84881d24807b2411e7bfe1f6b4450090d07 100644
--- a/src/3rdparty/libpng/pngread.c
+++ b/src/3rdparty/libpng/pngread.c
@@ -63,7 +63,7 @@ png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
          /* In stable builds only warn if an application error can be completely
           * handled.
           */
-#        if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
+#        if PNG_RELEASE_BUILD
             png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
 #        endif
 #     endif
@@ -1043,9 +1043,9 @@ png_read_png(png_structrp png_ptr, png_inforp info_ptr,
    /* Tell libpng to strip 16-bit/color files down to 8 bits per color.
     */
    if ((transforms & PNG_TRANSFORM_SCALE_16) != 0)
-     /* Added at libpng-1.5.4. "strip_16" produces the same result that it
-      * did in earlier versions, while "scale_16" is now more accurate.
-      */
+      /* Added at libpng-1.5.4. "strip_16" produces the same result that it
+       * did in earlier versions, while "scale_16" is now more accurate.
+       */
 #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
       png_set_scale_16(png_ptr);
 #else
@@ -1209,7 +1209,7 @@ png_read_png(png_structrp png_ptr, png_inforp info_ptr,
 
       for (iptr = 0; iptr < info_ptr->height; iptr++)
          info_ptr->row_pointers[iptr] = png_voidcast(png_bytep,
-            png_malloc(png_ptr, info_ptr->rowbytes));
+             png_malloc(png_ptr, info_ptr->rowbytes));
    }
 
    png_read_image(png_ptr, info_ptr->row_pointers);
@@ -1683,10 +1683,11 @@ decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding)
          value *= 257;
          break;
 
+#ifdef __GNUC__
       default:
          png_error(display->image->opaque->png_ptr,
             "unexpected encoding (internal error)");
-         break;
+#endif
    }
 
    return value;
@@ -2847,10 +2848,6 @@ png_image_read_colormap(png_voidp argument)
 
    switch (data_encoding)
    {
-      default:
-         png_error(png_ptr, "bad data option (internal error)");
-         break;
-
       case P_sRGB:
          /* Change to 8-bit sRGB */
          png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB);
@@ -2860,6 +2857,11 @@ png_image_read_colormap(png_voidp argument)
          if (png_ptr->bit_depth > 8)
             png_set_scale_16(png_ptr);
          break;
+
+#ifdef __GNUC__
+      default:
+         png_error(png_ptr, "bad data option (internal error)");
+#endif
    }
 
    if (cmap_entries > 256 || cmap_entries > image->colormap_entries)
@@ -3410,10 +3412,6 @@ png_image_read_background(png_voidp argument)
     */
    switch (info_ptr->bit_depth)
    {
-      default:
-         png_error(png_ptr, "unexpected bit depth");
-         break;
-
       case 8:
          /* 8-bit sRGB gray values with an alpha channel; the alpha channel is
           * to be removed by composing on a background: either the row if
@@ -3631,6 +3629,11 @@ png_image_read_background(png_voidp argument)
             }
          }
          break;
+
+#ifdef __GNUC__
+      default:
+         png_error(png_ptr, "unexpected bit depth");
+#endif
    }
 
    return 1;
diff --git a/src/3rdparty/libpng/pngrio.c b/src/3rdparty/libpng/pngrio.c
index bb5c825109c3e4adf0748c94e725dd419901921b..38f7fd49d68ef354ee5559fe1223c70952392e4d 100644
--- a/src/3rdparty/libpng/pngrio.c
+++ b/src/3rdparty/libpng/pngrio.c
@@ -26,7 +26,7 @@
  * reads from a file pointer.  Note that this routine sometimes gets called
  * with very small lengths, so you should implement some kind of simple
  * buffering if you are using unbuffered reads.  This should never be asked
- * to read more than 64K on a 16 bit machine.
+ * to read more than 64K on a 16-bit machine.
  */
 void /* PRIVATE */
 png_read_data(png_structrp png_ptr, png_bytep data, png_size_t length)
diff --git a/src/3rdparty/libpng/pngrtran.c b/src/3rdparty/libpng/pngrtran.c
index cad7a8daa59e92094aa7879d6fca63fdff7c4ea0..f129ef129c03cb6cba43162979732c77e571da5e 100644
--- a/src/3rdparty/libpng/pngrtran.c
+++ b/src/3rdparty/libpng/pngrtran.c
@@ -1,7 +1,7 @@
 
 /* pngrtran.c - transforms the data in a row for PNG readers
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.19 [November 12, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -976,7 +976,6 @@ png_set_rgb_to_gray_fixed(png_structrp png_ptr, int error_action,
 
       default:
          png_error(png_ptr, "invalid error action to rgb_to_gray");
-         break;
    }
 
    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
@@ -1997,7 +1996,7 @@ png_read_transform_info(png_structrp png_ptr, png_inforp info_ptr)
 #     endif
 
 #  else
-      /* No 16 bit support: force chopping 16-bit input down to 8, in this case
+      /* No 16-bit support: force chopping 16-bit input down to 8, in this case
        * the app program can chose if both APIs are available by setting the
        * correct scaling to use.
        */
@@ -2098,10 +2097,10 @@ png_read_transform_info(png_structrp png_ptr, png_inforp info_ptr)
 defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
    if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0)
    {
-      if (info_ptr->bit_depth < png_ptr->user_transform_depth)
+      if (png_ptr->user_transform_depth != 0)
          info_ptr->bit_depth = png_ptr->user_transform_depth;
 
-      if (info_ptr->channels < png_ptr->user_transform_channels)
+      if (png_ptr->user_transform_channels != 0)
          info_ptr->channels = png_ptr->user_transform_channels;
    }
 #endif
@@ -2382,8 +2381,8 @@ png_do_scale_16_to_8(png_row_infop row_info, png_bytep row)
 
       while (sp < ep)
       {
-         /* The input is an array of 16 bit components, these must be scaled to
-          * 8 bits each.  For a 16 bit value V the required value (from the PNG
+         /* The input is an array of 16-bit components, these must be scaled to
+          * 8 bits each.  For a 16-bit value V the required value (from the PNG
           * specification) is:
           *
           *    (V * 255) / 65535
@@ -2404,7 +2403,7 @@ png_do_scale_16_to_8(png_row_infop row_info, png_bytep row)
           *
           * The approximate differs from the exact answer only when (vlo-vhi) is
           * 128; it then gives a correction of +1 when the exact correction is
-          * 0.  This gives 128 errors.  The exact answer (correct for all 16 bit
+          * 0.  This gives 128 errors.  The exact answer (correct for all 16-bit
           * input values) is:
           *
           *    error = (vlo-vhi+128)*65535 >> 24;
@@ -3148,9 +3147,9 @@ png_do_rgb_to_gray(png_structrp png_ptr, png_row_infop row_info, png_bytep row)
                if (red != green || red != blue)
                   rgb_error |= 1;
 
-               /* From 1.5.5 in the 16 bit case do the accurate conversion even
+               /* From 1.5.5 in the 16-bit case do the accurate conversion even
                 * in the 'fast' case - this is because this is where the code
-                * ends up when handling linear 16 bit data.
+                * ends up when handling linear 16-bit data.
                 */
                gray16  = (png_uint_16)((rc*red + gc*green + bc*blue + 16384) >>
                   15);
@@ -3315,7 +3314,7 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structrp png_ptr)
                         if ((png_uint_16)((*sp >> shift) & 0x0f)
                             == png_ptr->trans_color.gray)
                         {
-                           unsigned int tmp = *sp & (0xf0f >> (4 - shift));
+                           unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
                            tmp |= png_ptr->background.gray << shift;
                            *sp = (png_byte)(tmp & 0xff);
                         }
@@ -3325,7 +3324,7 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structrp png_ptr)
                            unsigned int p = (*sp >> shift) & 0x0f;
                            unsigned int g = (gamma_table[p | (p << 4)] >> 4) &
                               0x0f;
-                           unsigned int tmp = *sp & (0xf0f >> (4 - shift));
+                           unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
                            tmp |= g << shift;
                            *sp = (png_byte)(tmp & 0xff);
                         }
@@ -3351,7 +3350,7 @@ png_do_compose(png_row_infop row_info, png_bytep row, png_structrp png_ptr)
                         if ((png_uint_16)((*sp >> shift) & 0x0f)
                             == png_ptr->trans_color.gray)
                         {
-                           unsigned int tmp = *sp & (0xf0f >> (4 - shift));
+                           unsigned int tmp = *sp & (0x0f0f >> (4 - shift));
                            tmp |= png_ptr->background.gray << shift;
                            *sp = (png_byte)(tmp & 0xff);
                         }
@@ -4460,7 +4459,7 @@ png_do_expand(png_row_infop row_info, png_bytep row,
 
                for (i = 0; i < row_width; i++)
                {
-                  if (*sp == gray)
+                  if ((*sp & 0xffU) == gray)
                      *dp-- = 0;
 
                   else
@@ -4478,7 +4477,8 @@ png_do_expand(png_row_infop row_info, png_bytep row,
                dp = row + (row_info->rowbytes << 1) - 1;
                for (i = 0; i < row_width; i++)
                {
-                  if (*(sp - 1) == gray_high && *(sp) == gray_low)
+                  if ((*(sp - 1) & 0xffU) == gray_high &&
+                      (*(sp) & 0xffU) == gray_low)
                   {
                      *dp-- = 0;
                      *dp-- = 0;
diff --git a/src/3rdparty/libpng/pngrutil.c b/src/3rdparty/libpng/pngrutil.c
index 6c5c37526bc5bc8608fdd62c44922189e4be1298..ee584a8c406383970396d15acab052fd76fefac6 100644
--- a/src/3rdparty/libpng/pngrutil.c
+++ b/src/3rdparty/libpng/pngrutil.c
@@ -1,7 +1,7 @@
 
 /* pngrutil.c - utilities to read a PNG file
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.19 [November 12, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -89,7 +89,13 @@ png_get_int_32)(png_const_bytep buf)
       return uval;
 
    uval = (uval ^ 0xffffffff) + 1;  /* 2's complement: -x = ~x+1 */
-   return -(png_int_32)uval;
+   if ((uval & 0x80000000) == 0) /* no overflow */
+       return -(png_int_32)uval;
+   /* The following has to be safe; this function only gets called on PNG data
+    * and if we get here that data is invalid.  0 is the most safe value and
+    * if not then an attacker would surely just generate a PNG with 0 instead.
+    */
+   return 0;
 }
 
 /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
@@ -98,7 +104,7 @@ png_get_uint_16)(png_const_bytep buf)
 {
    /* ANSI-C requires an int value to accomodate at least 16 bits so this
     * works and allows the compiler not to worry about possible narrowing
-    * on 32 bit systems.  (Pre-ANSI systems did not make integers smaller
+    * on 32-bit systems.  (Pre-ANSI systems did not make integers smaller
     * than 16 bits either.)
     */
    unsigned int val =
@@ -341,7 +347,7 @@ png_inflate_claim(png_structrp png_ptr, png_uint_32 owner)
        * are minimal.
        */
       (void)png_safecat(msg, (sizeof msg), 4, " using zstream");
-#if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
+#if PNG_RELEASE_BUILD
       png_chunk_warning(png_ptr, msg);
       png_ptr->zowner = 0;
 #else
@@ -575,7 +581,7 @@ png_decompress_chunk(png_structrp png_ptr,
     */
    png_alloc_size_t limit = PNG_SIZE_MAX;
 
-# ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED
+# ifdef PNG_SET_USER_LIMITS_SUPPORTED
    if (png_ptr->user_chunk_malloc_max > 0 &&
        png_ptr->user_chunk_malloc_max < limit)
       limit = png_ptr->user_chunk_malloc_max;
@@ -670,7 +676,6 @@ png_decompress_chunk(png_structrp png_ptr,
                    * success)
                    */
                   png_free(png_ptr, text);
-                  text = NULL;
 
                   /* This really is very benign, but it's still an error because
                    * the extra space may otherwise be used as a Trojan Horse.
@@ -867,7 +872,7 @@ void /* PRIVATE */
 png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
 {
    png_color palette[PNG_MAX_PALETTE_LENGTH];
-   int num, i;
+   int max_palette_length, num, i;
 #ifdef PNG_POINTER_INDEXING_SUPPORTED
    png_colorp pal_ptr;
 #endif
@@ -928,6 +933,19 @@ png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
    /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */
    num = (int)length / 3;
 
+   /* If the palette has 256 or fewer entries but is too large for the bit
+    * depth, we don't issue an error, to preserve the behavior of previous
+    * libpng versions. We silently truncate the unused extra palette entries
+    * here.
+    */
+   if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
+      max_palette_length = (1 << png_ptr->bit_depth);
+   else
+      max_palette_length = PNG_MAX_PALETTE_LENGTH;
+
+   if (num > max_palette_length)
+      num = max_palette_length;
+
 #ifdef PNG_POINTER_INDEXING_SUPPORTED
    for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
    {
@@ -960,7 +978,7 @@ png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
    if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
 #endif
    {
-      png_crc_finish(png_ptr, 0);
+      png_crc_finish(png_ptr, (int) length - num * 3);
    }
 
 #ifndef PNG_READ_OPT_PLTE_SUPPORTED
@@ -1147,11 +1165,13 @@ png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
       return;
 
    for (i=0; i<truelen; ++i)
+   {
       if (buf[i] == 0 || buf[i] > sample_depth)
       {
          png_chunk_benign_error(png_ptr, "invalid");
          return;
       }
+   }
 
    if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0)
    {
@@ -1462,10 +1482,10 @@ png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
                                     finished = 1;
 
 #                                   ifdef PNG_sRGB_SUPPORTED
-                                       /* Check for a match against sRGB */
-                                       png_icc_set_sRGB(png_ptr,
-                                          &png_ptr->colorspace, profile,
-                                          png_ptr->zstream.adler);
+                                    /* Check for a match against sRGB */
+                                    png_icc_set_sRGB(png_ptr,
+                                       &png_ptr->colorspace, profile,
+                                       png_ptr->zstream.adler);
 #                                   endif
 
                                     /* Steal the profile for info_ptr. */
@@ -1675,8 +1695,8 @@ png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
 
    if (dl > max_dl)
    {
-       png_warning(png_ptr, "sPLT chunk too long");
-       return;
+      png_warning(png_ptr, "sPLT chunk too long");
+      return;
    }
 
    new_palette.nentries = (png_int_32)(data_length / entry_size);
@@ -1686,8 +1706,8 @@ png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
 
    if (new_palette.entries == NULL)
    {
-       png_warning(png_ptr, "sPLT chunk requires too much memory");
-       return;
+      png_warning(png_ptr, "sPLT chunk requires too much memory");
+      return;
    }
 
 #ifdef PNG_POINTER_INDEXING_SUPPORTED
@@ -1817,7 +1837,8 @@ png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
          return;
       }
 
-      if (length > png_ptr->num_palette || length > PNG_MAX_PALETTE_LENGTH ||
+      if (length > (unsigned int) png_ptr->num_palette ||
+         length > (unsigned int) PNG_MAX_PALETTE_LENGTH ||
          length == 0)
       {
          png_crc_finish(png_ptr, length);
@@ -1980,7 +2001,8 @@ png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length)
 
    num = length / 2 ;
 
-   if (num != png_ptr->num_palette || num > PNG_MAX_PALETTE_LENGTH)
+   if (num != (unsigned int) png_ptr->num_palette ||
+       num > (unsigned int) PNG_MAX_PALETTE_LENGTH)
    {
       png_crc_finish(png_ptr, length);
       png_chunk_benign_error(png_ptr, "invalid");
@@ -2715,14 +2737,14 @@ png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length)
       png_ptr->unknown_chunk.data = NULL;
    }
 
-#  ifdef PNG_SET_CHUNK_MALLOC_LIMIT_SUPPORTED
-      if (png_ptr->user_chunk_malloc_max > 0 &&
-          png_ptr->user_chunk_malloc_max < limit)
-         limit = png_ptr->user_chunk_malloc_max;
+#  ifdef PNG_SET_USER_LIMITS_SUPPORTED
+   if (png_ptr->user_chunk_malloc_max > 0 &&
+       png_ptr->user_chunk_malloc_max < limit)
+      limit = png_ptr->user_chunk_malloc_max;
 
 #  elif PNG_USER_CHUNK_MALLOC_MAX > 0
-      if (PNG_USER_CHUNK_MALLOC_MAX < limit)
-         limit = PNG_USER_CHUNK_MALLOC_MAX;
+   if (PNG_USER_CHUNK_MALLOC_MAX < limit)
+      limit = PNG_USER_CHUNK_MALLOC_MAX;
 #  endif
 
    if (length <= limit)
@@ -2785,7 +2807,7 @@ png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
     */
 #  ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
 #     ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
-         keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
+   keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name);
 #     endif
 #  endif
 
@@ -2794,153 +2816,153 @@ png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr,
     * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
     */
 #  ifdef PNG_READ_USER_CHUNKS_SUPPORTED
-      /* The user callback takes precedence over the chunk keep value, but the
-       * keep value is still required to validate a save of a critical chunk.
-       */
-      if (png_ptr->read_user_chunk_fn != NULL)
+   /* The user callback takes precedence over the chunk keep value, but the
+    * keep value is still required to validate a save of a critical chunk.
+    */
+   if (png_ptr->read_user_chunk_fn != NULL)
+   {
+      if (png_cache_unknown_chunk(png_ptr, length) != 0)
       {
-         if (png_cache_unknown_chunk(png_ptr, length) != 0)
+         /* Callback to user unknown chunk handler */
+         int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
+            &png_ptr->unknown_chunk);
+
+         /* ret is:
+          * negative: An error occurred; png_chunk_error will be called.
+          *     zero: The chunk was not handled, the chunk will be discarded
+          *           unless png_set_keep_unknown_chunks has been used to set
+          *           a 'keep' behavior for this particular chunk, in which
+          *           case that will be used.  A critical chunk will cause an
+          *           error at this point unless it is to be saved.
+          * positive: The chunk was handled, libpng will ignore/discard it.
+          */
+         if (ret < 0)
+            png_chunk_error(png_ptr, "error in user chunk");
+
+         else if (ret == 0)
          {
-            /* Callback to user unknown chunk handler */
-            int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr,
-               &png_ptr->unknown_chunk);
-
-            /* ret is:
-             * negative: An error occurred; png_chunk_error will be called.
-             *     zero: The chunk was not handled, the chunk will be discarded
-             *           unless png_set_keep_unknown_chunks has been used to set
-             *           a 'keep' behavior for this particular chunk, in which
-             *           case that will be used.  A critical chunk will cause an
-             *           error at this point unless it is to be saved.
-             * positive: The chunk was handled, libpng will ignore/discard it.
+            /* If the keep value is 'default' or 'never' override it, but
+             * still error out on critical chunks unless the keep value is
+             * 'always'  While this is weird it is the behavior in 1.4.12.
+             * A possible improvement would be to obey the value set for the
+             * chunk, but this would be an API change that would probably
+             * damage some applications.
+             *
+             * The png_app_warning below catches the case that matters, where
+             * the application has not set specific save or ignore for this
+             * chunk or global save or ignore.
              */
-            if (ret < 0)
-               png_chunk_error(png_ptr, "error in user chunk");
-
-            else if (ret == 0)
+            if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
             {
-               /* If the keep value is 'default' or 'never' override it, but
-                * still error out on critical chunks unless the keep value is
-                * 'always'  While this is weird it is the behavior in 1.4.12.
-                * A possible improvement would be to obey the value set for the
-                * chunk, but this would be an API change that would probably
-                * damage some applications.
-                *
-                * The png_app_warning below catches the case that matters, where
-                * the application has not set specific save or ignore for this
-                * chunk or global save or ignore.
-                */
-               if (keep < PNG_HANDLE_CHUNK_IF_SAFE)
+#              ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
+               if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
                {
-#                 ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
-                     if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE)
-                     {
-                        png_chunk_warning(png_ptr, "Saving unknown chunk:");
-                        png_app_warning(png_ptr,
-                           "forcing save of an unhandled chunk;"
-                           " please call png_set_keep_unknown_chunks");
-                           /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
-                     }
-#                 endif
-                  keep = PNG_HANDLE_CHUNK_IF_SAFE;
+                  png_chunk_warning(png_ptr, "Saving unknown chunk:");
+                  png_app_warning(png_ptr,
+                     "forcing save of an unhandled chunk;"
+                     " please call png_set_keep_unknown_chunks");
+                     /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */
                }
-            }
-
-            else /* chunk was handled */
-            {
-               handled = 1;
-               /* Critical chunks can be safely discarded at this point. */
-               keep = PNG_HANDLE_CHUNK_NEVER;
+#              endif
+               keep = PNG_HANDLE_CHUNK_IF_SAFE;
             }
          }
 
-         else
-            keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
+         else /* chunk was handled */
+         {
+            handled = 1;
+            /* Critical chunks can be safely discarded at this point. */
+            keep = PNG_HANDLE_CHUNK_NEVER;
+         }
       }
 
       else
-         /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
+         keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */
+   }
+
+   else
+   /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */
 #  endif /* READ_USER_CHUNKS */
 
 #  ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED
-      {
-         /* keep is currently just the per-chunk setting, if there was no
-          * setting change it to the global default now (not that this may
-          * still be AS_DEFAULT) then obtain the cache of the chunk if required,
-          * if not simply skip the chunk.
-          */
-         if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
-            keep = png_ptr->unknown_default;
-
-         if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
-            (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
-             PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
-         {
-            if (png_cache_unknown_chunk(png_ptr, length) == 0)
-               keep = PNG_HANDLE_CHUNK_NEVER;
-         }
+   {
+      /* keep is currently just the per-chunk setting, if there was no
+       * setting change it to the global default now (not that this may
+       * still be AS_DEFAULT) then obtain the cache of the chunk if required,
+       * if not simply skip the chunk.
+       */
+      if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT)
+         keep = png_ptr->unknown_default;
 
-         else
-            png_crc_finish(png_ptr, length);
+      if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
+         (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
+          PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
+      {
+         if (png_cache_unknown_chunk(png_ptr, length) == 0)
+            keep = PNG_HANDLE_CHUNK_NEVER;
       }
+
+      else
+         png_crc_finish(png_ptr, length);
+   }
 #  else
 #     ifndef PNG_READ_USER_CHUNKS_SUPPORTED
 #        error no method to support READ_UNKNOWN_CHUNKS
 #     endif
 
-      {
-         /* If here there is no read callback pointer set and no support is
-          * compiled in to just save the unknown chunks, so simply skip this
-          * chunk.  If 'keep' is something other than AS_DEFAULT or NEVER then
-          * the app has erroneously asked for unknown chunk saving when there
-          * is no support.
-          */
-         if (keep > PNG_HANDLE_CHUNK_NEVER)
-            png_app_error(png_ptr, "no unknown chunk support available");
+   {
+      /* If here there is no read callback pointer set and no support is
+       * compiled in to just save the unknown chunks, so simply skip this
+       * chunk.  If 'keep' is something other than AS_DEFAULT or NEVER then
+       * the app has erroneously asked for unknown chunk saving when there
+       * is no support.
+       */
+      if (keep > PNG_HANDLE_CHUNK_NEVER)
+         png_app_error(png_ptr, "no unknown chunk support available");
 
-         png_crc_finish(png_ptr, length);
-      }
+      png_crc_finish(png_ptr, length);
+   }
 #  endif
 
 #  ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
-      /* Now store the chunk in the chunk list if appropriate, and if the limits
-       * permit it.
-       */
-      if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
-         (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
-          PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
-      {
-#     ifdef PNG_USER_LIMITS_SUPPORTED
-         switch (png_ptr->user_chunk_cache_max)
-         {
-            case 2:
-               png_ptr->user_chunk_cache_max = 1;
-               png_chunk_benign_error(png_ptr, "no space in chunk cache");
-               /* FALL THROUGH */
-            case 1:
-               /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
-                * chunk being skipped, now there will be a hard error below.
-                */
-               break;
-
-            default: /* not at limit */
-               --(png_ptr->user_chunk_cache_max);
-               /* FALL THROUGH */
-            case 0: /* no limit */
-#     endif /* USER_LIMITS */
-               /* Here when the limit isn't reached or when limits are compiled
-                * out; store the chunk.
-                */
-               png_set_unknown_chunks(png_ptr, info_ptr,
-                  &png_ptr->unknown_chunk, 1);
-               handled = 1;
+   /* Now store the chunk in the chunk list if appropriate, and if the limits
+    * permit it.
+    */
+   if (keep == PNG_HANDLE_CHUNK_ALWAYS ||
+      (keep == PNG_HANDLE_CHUNK_IF_SAFE &&
+       PNG_CHUNK_ANCILLARY(png_ptr->chunk_name)))
+   {
 #     ifdef PNG_USER_LIMITS_SUPPORTED
-               break;
-         }
-#     endif
+      switch (png_ptr->user_chunk_cache_max)
+      {
+         case 2:
+            png_ptr->user_chunk_cache_max = 1;
+            png_chunk_benign_error(png_ptr, "no space in chunk cache");
+            /* FALL THROUGH */
+         case 1:
+            /* NOTE: prior to 1.6.0 this case resulted in an unknown critical
+             * chunk being skipped, now there will be a hard error below.
+             */
+            break;
+
+         default: /* not at limit */
+            --(png_ptr->user_chunk_cache_max);
+            /* FALL THROUGH */
+         case 0: /* no limit */
+#  endif /* USER_LIMITS */
+            /* Here when the limit isn't reached or when limits are compiled
+             * out; store the chunk.
+             */
+            png_set_unknown_chunks(png_ptr, info_ptr,
+               &png_ptr->unknown_chunk, 1);
+            handled = 1;
+#  ifdef PNG_USER_LIMITS_SUPPORTED
+            break;
       }
+#  endif
+   }
 #  else /* no store support: the chunk must be handled by the user callback */
-      PNG_UNUSED(info_ptr)
+   PNG_UNUSED(info_ptr)
 #  endif
 
    /* Regardless of the error handling below the cached data (if any) can be
@@ -3042,13 +3064,13 @@ png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
       end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1;
       end_byte = *end_ptr;
 #     ifdef PNG_READ_PACKSWAP_SUPPORTED
-         if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
-            /* little-endian byte */
-            end_mask = 0xff << end_mask;
+      if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
+         /* little-endian byte */
+         end_mask = 0xff << end_mask;
 
-         else /* big-endian byte */
+      else /* big-endian byte */
 #     endif
-         end_mask = 0xff >> end_mask;
+      end_mask = 0xff >> end_mask;
       /* end_mask is now the bits to *keep* from the destination row */
    }
 
@@ -3206,12 +3228,12 @@ png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display)
          png_uint_32 mask;
 
 #        ifdef PNG_READ_PACKSWAP_SUPPORTED
-            if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
-               mask = MASK(pass, pixel_depth, display, 0);
+         if ((png_ptr->transformations & PNG_PACKSWAP) != 0)
+            mask = MASK(pass, pixel_depth, display, 0);
 
-            else
+         else
 #        endif
-            mask = MASK(pass, pixel_depth, display, 1);
+         mask = MASK(pass, pixel_depth, display, 1);
 
          for (;;)
          {
@@ -3812,15 +3834,15 @@ png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row,
       p = b - c;
       pc = a - c;
 
-#     ifdef PNG_USE_ABS
-         pa = abs(p);
-         pb = abs(pc);
-         pc = abs(p + pc);
-#     else
-         pa = p < 0 ? -p : p;
-         pb = pc < 0 ? -pc : pc;
-         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
-#     endif
+#ifdef PNG_USE_ABS
+      pa = abs(p);
+      pb = abs(pc);
+      pc = abs(p + pc);
+#else
+      pa = p < 0 ? -p : p;
+      pb = pc < 0 ? -pc : pc;
+      pc = (p + pc) < 0 ? -(p + pc) : p + pc;
+#endif
 
       /* Find the best predictor, the least of pa, pb, pc favoring the earlier
        * ones in the case of a tie.
@@ -3867,15 +3889,15 @@ png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row,
       p = b - c;
       pc = a - c;
 
-#     ifdef PNG_USE_ABS
-         pa = abs(p);
-         pb = abs(pc);
-         pc = abs(p + pc);
-#     else
-         pa = p < 0 ? -p : p;
-         pb = pc < 0 ? -pc : pc;
-         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
-#     endif
+#ifdef PNG_USE_ABS
+      pa = abs(p);
+      pb = abs(pc);
+      pc = abs(p + pc);
+#else
+      pa = p < 0 ? -p : p;
+      pb = pc < 0 ? -pc : pc;
+      pc = (p + pc) < 0 ? -(p + pc) : p + pc;
+#endif
 
       if (pb < pa) pa = pb, a = b;
       if (pc < pa) a = c;
@@ -4280,18 +4302,18 @@ png_read_start_row(png_structrp png_ptr)
 #ifdef PNG_READ_EXPAND_16_SUPPORTED
    if ((png_ptr->transformations & PNG_EXPAND_16) != 0)
    {
-#     ifdef PNG_READ_EXPAND_SUPPORTED
-         /* In fact it is an error if it isn't supported, but checking is
-          * the safe way.
-          */
-         if ((png_ptr->transformations & PNG_EXPAND) != 0)
-         {
-            if (png_ptr->bit_depth < 16)
-               max_pixel_depth *= 2;
-         }
-         else
-#     endif
-         png_ptr->transformations &= ~PNG_EXPAND_16;
+#  ifdef PNG_READ_EXPAND_SUPPORTED
+      /* In fact it is an error if it isn't supported, but checking is
+       * the safe way.
+       */
+      if ((png_ptr->transformations & PNG_EXPAND) != 0)
+      {
+         if (png_ptr->bit_depth < 16)
+            max_pixel_depth *= 2;
+      }
+      else
+#  endif
+      png_ptr->transformations &= ~PNG_EXPAND_16;
    }
 #endif
 
diff --git a/src/3rdparty/libpng/pngset.c b/src/3rdparty/libpng/pngset.c
index fce30391682a63d31e75b129e13e4249822c459d..05a2134dbba856443bed06e70da6fe0fa622b5e7 100644
--- a/src/3rdparty/libpng/pngset.c
+++ b/src/3rdparty/libpng/pngset.c
@@ -1,7 +1,7 @@
 
 /* pngset.c - storage of image information into info struct
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.19 [November 12, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -123,12 +123,12 @@ png_set_cHRM_XYZ(png_const_structrp png_ptr, png_inforp info_ptr, double red_X,
       png_fixed(png_ptr, red_X, "cHRM Red X"),
       png_fixed(png_ptr, red_Y, "cHRM Red Y"),
       png_fixed(png_ptr, red_Z, "cHRM Red Z"),
-      png_fixed(png_ptr, green_X, "cHRM Red X"),
-      png_fixed(png_ptr, green_Y, "cHRM Red Y"),
-      png_fixed(png_ptr, green_Z, "cHRM Red Z"),
-      png_fixed(png_ptr, blue_X, "cHRM Red X"),
-      png_fixed(png_ptr, blue_Y, "cHRM Red Y"),
-      png_fixed(png_ptr, blue_Z, "cHRM Red Z"));
+      png_fixed(png_ptr, green_X, "cHRM Green X"),
+      png_fixed(png_ptr, green_Y, "cHRM Green Y"),
+      png_fixed(png_ptr, green_Z, "cHRM Green Z"),
+      png_fixed(png_ptr, blue_X, "cHRM Blue X"),
+      png_fixed(png_ptr, blue_Y, "cHRM Blue Y"),
+      png_fixed(png_ptr, blue_Z, "cHRM Blue Z"));
 }
 #  endif /* FLOATING_POINT */
 
@@ -513,12 +513,17 @@ png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr,
     png_const_colorp palette, int num_palette)
 {
 
+   png_uint_32 max_palette_length;
+
    png_debug1(1, "in %s storage function", "PLTE");
 
    if (png_ptr == NULL || info_ptr == NULL)
       return;
 
-   if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
+   max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
+      (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
+
+   if (num_palette < 0 || num_palette > (int) max_palette_length)
    {
       if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
          png_error(png_ptr, "Invalid palette length");
@@ -551,8 +556,8 @@ png_set_PLTE(png_structrp png_ptr, png_inforp info_ptr,
    png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
 
    /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
-    * of num_palette entries, in case of an invalid PNG file that has
-    * too-large sample values.
+    * of num_palette entries, in case of an invalid PNG file or incorrect
+    * call to png_set_PLTE() with too-large sample values.
     */
    png_ptr->palette = png_voidcast(png_colorp, png_calloc(png_ptr,
        PNG_MAX_PALETTE_LENGTH * (sizeof (png_color))));
@@ -673,7 +678,6 @@ png_set_iCCP(png_const_structrp png_ptr, png_inforp info_ptr,
    if (new_iccp_profile == NULL)
    {
       png_free(png_ptr, new_iccp_name);
-      new_iccp_name = NULL;
       png_benign_error(png_ptr,
           "Insufficient memory to process iCCP profile");
 
@@ -710,7 +714,7 @@ png_set_text_2(png_const_structrp png_ptr, png_inforp info_ptr,
 {
    int i;
 
-   png_debug1(1, "in %lx storage function", png_ptr == NULL ? "unexpected" :
+   png_debug1(1, "in %lx storage function", png_ptr == NULL ? 0xabadca11U :
       (unsigned long)png_ptr->chunk_name);
 
    if (png_ptr == NULL || info_ptr == NULL || num_text <= 0 || text_ptr == NULL)
@@ -1522,6 +1526,9 @@ png_set_compression_buffer_size(png_structrp png_ptr, png_size_t size)
          }
 
 #ifndef __COVERITY__
+         /* Some compilers complain that this is always false.  However, it
+          * can be true when integer overflow happens.
+          */
          if (size > ZLIB_IO_MAX)
          {
             png_warning(png_ptr,
@@ -1566,7 +1573,7 @@ png_set_user_limits (png_structrp png_ptr, png_uint_32 user_width_max,
 {
    /* Images with dimensions larger than these limits will be
     * rejected by png_set_IHDR().  To accept any PNG datastream
-    * regardless of dimensions, set both limits to 0x7ffffffL.
+    * regardless of dimensions, set both limits to 0x7ffffff.
     */
    if (png_ptr == NULL)
       return;
diff --git a/src/3rdparty/libpng/pngstruct.h b/src/3rdparty/libpng/pngstruct.h
index 8420d09972b6046edfc103ec77e4de9d84b23954..c8c0e46e8b01e8b3acb452ab0ee1d662b91792b3 100644
--- a/src/3rdparty/libpng/pngstruct.h
+++ b/src/3rdparty/libpng/pngstruct.h
@@ -1,8 +1,8 @@
 
 /* pngstruct.h - header file for PNG reference library
  *
- * Last changed in libpng 1.6.1 [March 28, 2013]
- * Copyright (c) 1998-2013 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.18 [July 23, 2015]
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -219,16 +219,18 @@ struct png_struct_def
    png_uint_32 row_number;    /* current row in interlace pass */
    png_uint_32 chunk_name;    /* PNG_CHUNK() id of current chunk */
    png_bytep prev_row;        /* buffer to save previous (unfiltered) row.
-                               * This is a pointer into big_prev_row
+                               * While reading this is a pointer into
+                               * big_prev_row; while writing it is separately
+                               * allocated if needed.
                                */
    png_bytep row_buf;         /* buffer to save current (unfiltered) row.
-                               * This is a pointer into big_row_buf
+                               * While reading, this is a pointer into
+                               * big_row_buf; while writing it is separately
+                               * allocated.
                                */
-#ifdef PNG_WRITE_SUPPORTED
-   png_bytep sub_row;         /* buffer to save "sub" row when filtering */
-   png_bytep up_row;          /* buffer to save "up" row when filtering */
-   png_bytep avg_row;         /* buffer to save "avg" row when filtering */
-   png_bytep paeth_row;       /* buffer to save "Paeth" row when filtering */
+#ifdef PNG_WRITE_FILTER_SUPPORTED
+   png_bytep try_row;    /* buffer to save trial row when filtering */
+   png_bytep tst_row;    /* buffer to save best trial row when filtering */
 #endif
    png_size_t info_rowbytes;  /* Added in 1.5.4: cache of updated row bytes */
 
@@ -346,17 +348,7 @@ struct png_struct_def
    png_bytep quantize_index; /* index translation for palette files */
 #endif
 
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-   png_byte heuristic_method;        /* heuristic for row filter selection */
-   png_byte num_prev_filters;        /* number of weights for previous rows */
-   png_bytep prev_filters;           /* filter type(s) of previous row(s) */
-   png_uint_16p filter_weights;      /* weight(s) for previous line(s) */
-   png_uint_16p inv_filter_weights;  /* 1/weight(s) for previous line(s) */
-   png_uint_16p filter_costs;        /* relative filter calculation cost */
-   png_uint_16p inv_filter_costs;    /* 1/relative filter calculation cost */
-#endif
-
-   /* Options */
+/* Options */
 #ifdef PNG_SET_OPTION_SUPPORTED
    png_byte options;           /* On/off state (up to 4 options) */
 #endif
diff --git a/src/3rdparty/libpng/pngtrans.c b/src/3rdparty/libpng/pngtrans.c
index cd3a79b6fa49ed6e0e8a4260e4f1ca9894648949..0c0d92d8fd6dd3666a13dd6f0a4b8af00f6b201a 100644
--- a/src/3rdparty/libpng/pngtrans.c
+++ b/src/3rdparty/libpng/pngtrans.c
@@ -1,7 +1,7 @@
 
 /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.18 [July 23, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -30,7 +30,7 @@ png_set_bgr(png_structrp png_ptr)
 #endif
 
 #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
-/* Turn on 16 bit byte swapping */
+/* Turn on 16-bit byte swapping */
 void PNGAPI
 png_set_swap(png_structrp png_ptr)
 {
@@ -313,7 +313,7 @@ png_do_invert(png_row_infop row_info, png_bytep row)
 
 #ifdef PNG_16BIT_SUPPORTED
 #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
-/* Swaps byte order on 16 bit depth images */
+/* Swaps byte order on 16-bit depth images */
 void /* PRIVATE */
 png_do_swap(png_row_infop row_info, png_bytep row)
 {
@@ -704,7 +704,7 @@ png_do_check_palette_indexes(png_structrp png_ptr, png_row_infop row_info)
              */
             for (; rp > png_ptr->row_buf; rp--)
             {
-              if (*rp >> padding != 0)
+              if ((*rp >> padding) != 0)
                  png_ptr->num_palette_max = 1;
               padding = 0;
             }
diff --git a/src/3rdparty/libpng/pngwio.c b/src/3rdparty/libpng/pngwio.c
index 0a40948aab50ef928bfa5de6ae0522eceb58decf..db76e6b8d788924dafaf0a2ffba772bdc91a2a98 100644
--- a/src/3rdparty/libpng/pngwio.c
+++ b/src/3rdparty/libpng/pngwio.c
@@ -26,7 +26,7 @@
  * writes to a file pointer.  Note that this routine sometimes gets called
  * with very small lengths, so you should implement some kind of simple
  * buffering if you are using unbuffered writes.  This should never be asked
- * to write more than 64K on a 16 bit machine.
+ * to write more than 64K on a 16-bit machine.
  */
 
 void /* PRIVATE */
diff --git a/src/3rdparty/libpng/pngwrite.c b/src/3rdparty/libpng/pngwrite.c
index e3c203496ec758048d6b77b77b4e9e95b805d91f..0d4ee9f7ae0ea156f0757d444232ce4df8e2b796 100644
--- a/src/3rdparty/libpng/pngwrite.c
+++ b/src/3rdparty/libpng/pngwrite.c
@@ -1,7 +1,7 @@
 
 /* pngwrite.c - general routines to write a PNG file
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.19 [November 12, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -90,43 +90,44 @@ png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr)
 
    if ((png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE) == 0)
    {
-   /* Write PNG signature */
-   png_write_sig(png_ptr);
+      /* Write PNG signature */
+      png_write_sig(png_ptr);
 
 #ifdef PNG_MNG_FEATURES_SUPPORTED
-   if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \
-       png_ptr->mng_features_permitted != 0)
-   {
-      png_warning(png_ptr, "MNG features are not allowed in a PNG datastream");
-      png_ptr->mng_features_permitted = 0;
-   }
+      if ((png_ptr->mode & PNG_HAVE_PNG_SIGNATURE) != 0 && \
+          png_ptr->mng_features_permitted != 0)
+      {
+         png_warning(png_ptr,
+             "MNG features are not allowed in a PNG datastream");
+         png_ptr->mng_features_permitted = 0;
+      }
 #endif
 
-   /* Write IHDR information. */
-   png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
-       info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
-       info_ptr->filter_type,
+      /* Write IHDR information. */
+      png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
+          info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
+          info_ptr->filter_type,
 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
-       info_ptr->interlace_type
+          info_ptr->interlace_type
 #else
-       0
+          0
 #endif
-      );
+         );
 
-   /* The rest of these check to see if the valid field has the appropriate
-    * flag set, and if it does, writes the chunk.
-    *
-    * 1.6.0: COLORSPACE support controls the writing of these chunks too, and
-    * the chunks will be written if the WRITE routine is there and information
-    * is available in the COLORSPACE.  (See png_colorspace_sync_info in png.c
-    * for where the valid flags get set.)
-    *
-    * Under certain circumstances the colorspace can be invalidated without
-    * syncing the info_struct 'valid' flags; this happens if libpng detects and
-    * error and calls png_error while the color space is being set, yet the
-    * application continues writing the PNG.  So check the 'invalid' flag here
-    * too.
-    */
+      /* The rest of these check to see if the valid field has the appropriate
+       * flag set, and if it does, writes the chunk.
+       *
+       * 1.6.0: COLORSPACE support controls the writing of these chunks too, and
+       * the chunks will be written if the WRITE routine is there and
+       * information * is available in the COLORSPACE. (See
+       * png_colorspace_sync_info in png.c for where the valid flags get set.)
+       *
+       * Under certain circumstances the colorspace can be invalidated without
+       * syncing the info_struct 'valid' flags; this happens if libpng detects
+       * an error and calls png_error while the color space is being set, yet
+       * the application continues writing the PNG.  So check the 'invalid'
+       * flag here too.
+       */
 #ifdef PNG_GAMMA_SUPPORTED
 #  ifdef PNG_WRITE_gAMA_SUPPORTED
       if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
@@ -137,50 +138,50 @@ png_write_info_before_PLTE(png_structrp png_ptr, png_const_inforp info_ptr)
 #endif
 
 #ifdef PNG_COLORSPACE_SUPPORTED
-   /* Write only one of sRGB or an ICC profile.  If a profile was supplied
-    * and it matches one of the known sRGB ones issue a warning.
-    */
+      /* Write only one of sRGB or an ICC profile.  If a profile was supplied
+       * and it matches one of the known sRGB ones issue a warning.
+       */
 #  ifdef PNG_WRITE_iCCP_SUPPORTED
-      if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
-          (info_ptr->valid & PNG_INFO_iCCP) != 0)
-      {
-#        ifdef PNG_WRITE_sRGB_SUPPORTED
-            if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
-               png_app_warning(png_ptr,
-                  "profile matches sRGB but writing iCCP instead");
-#        endif
-
-         png_write_iCCP(png_ptr, info_ptr->iccp_name,
-            info_ptr->iccp_profile);
-      }
+         if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
+             (info_ptr->valid & PNG_INFO_iCCP) != 0)
+         {
+#    ifdef PNG_WRITE_sRGB_SUPPORTED
+               if ((info_ptr->valid & PNG_INFO_sRGB) != 0)
+                  png_app_warning(png_ptr,
+                     "profile matches sRGB but writing iCCP instead");
+#     endif
+
+            png_write_iCCP(png_ptr, info_ptr->iccp_name,
+               info_ptr->iccp_profile);
+         }
 #     ifdef PNG_WRITE_sRGB_SUPPORTED
          else
 #     endif
 #  endif
 
 #  ifdef PNG_WRITE_sRGB_SUPPORTED
-      if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
-          (info_ptr->valid & PNG_INFO_sRGB) != 0)
-         png_write_sRGB(png_ptr, info_ptr->colorspace.rendering_intent);
+         if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
+             (info_ptr->valid & PNG_INFO_sRGB) != 0)
+            png_write_sRGB(png_ptr, info_ptr->colorspace.rendering_intent);
 #  endif /* WRITE_sRGB */
 #endif /* COLORSPACE */
 
 #ifdef PNG_WRITE_sBIT_SUPPORTED
-   if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
-      png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
+         if ((info_ptr->valid & PNG_INFO_sBIT) != 0)
+            png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
 #endif
 
 #ifdef PNG_COLORSPACE_SUPPORTED
 #  ifdef PNG_WRITE_cHRM_SUPPORTED
-      if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
-         (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0 &&
-         (info_ptr->valid & PNG_INFO_cHRM) != 0)
-         png_write_cHRM_fixed(png_ptr, &info_ptr->colorspace.end_points_xy);
+         if ((info_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) == 0 &&
+             (info_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0 &&
+             (info_ptr->valid & PNG_INFO_cHRM) != 0)
+            png_write_cHRM_fixed(png_ptr, &info_ptr->colorspace.end_points_xy);
 #  endif
 #endif
 
 #ifdef PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
-      write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
+         write_unknown_chunks(png_ptr, info_ptr, PNG_HAVE_IHDR);
 #endif
 
       png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
@@ -205,7 +206,7 @@ png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
       png_write_PLTE(png_ptr, info_ptr->palette,
           (png_uint_32)info_ptr->num_palette);
 
-   else if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) !=0)
+   else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
       png_error(png_ptr, "Valid palette required for paletted images");
 
 #ifdef PNG_WRITE_tRNS_SUPPORTED
@@ -216,8 +217,13 @@ png_write_info(png_structrp png_ptr, png_const_inforp info_ptr)
       if ((png_ptr->transformations & PNG_INVERT_ALPHA) != 0 &&
           info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
       {
-         int j;
-         for (j = 0; j<(int)info_ptr->num_trans; j++)
+         int j, jend;
+
+         jend = info_ptr->num_trans;
+         if (jend > PNG_MAX_PALETTE_LENGTH)
+            jend = PNG_MAX_PALETTE_LENGTH;
+
+         for (j = 0; j<jend; ++j)
             info_ptr->trans_alpha[j] =
                (png_byte)(255 - info_ptr->trans_alpha[j]);
       }
@@ -538,7 +544,7 @@ png_create_write_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr,
       /* App warnings are warnings in release (or release candidate) builds but
        * are errors during development.
        */
-#if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
+#if PNG_RELEASE_BUILD
       png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN;
 #endif
 
@@ -849,7 +855,7 @@ png_write_row(png_structrp png_ptr, png_const_bytep row)
     * which is also the output depth.
     */
    if (row_info.pixel_depth != png_ptr->pixel_depth ||
-      row_info.pixel_depth != png_ptr->transformed_pixel_depth)
+       row_info.pixel_depth != png_ptr->transformed_pixel_depth)
       png_error(png_ptr, "internal write transform logic error");
 
 #ifdef PNG_MNG_FEATURES_SUPPORTED
@@ -917,10 +923,6 @@ png_write_flush(png_structrp png_ptr)
 }
 #endif /* WRITE_FLUSH */
 
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-static void png_reset_filter_heuristics(png_structrp png_ptr);/* forward decl */
-#endif
-
 /* Free any memory used in png_ptr struct without freeing the struct itself. */
 static void
 png_write_destroy(png_structrp png_ptr)
@@ -937,24 +939,11 @@ png_write_destroy(png_structrp png_ptr)
    png_ptr->row_buf = NULL;
 #ifdef PNG_WRITE_FILTER_SUPPORTED
    png_free(png_ptr, png_ptr->prev_row);
-   png_free(png_ptr, png_ptr->sub_row);
-   png_free(png_ptr, png_ptr->up_row);
-   png_free(png_ptr, png_ptr->avg_row);
-   png_free(png_ptr, png_ptr->paeth_row);
+   png_free(png_ptr, png_ptr->try_row);
+   png_free(png_ptr, png_ptr->tst_row);
    png_ptr->prev_row = NULL;
-   png_ptr->sub_row = NULL;
-   png_ptr->up_row = NULL;
-   png_ptr->avg_row = NULL;
-   png_ptr->paeth_row = NULL;
-#endif
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-   /* Use this to save a little code space, it doesn't free the filter_costs */
-   png_reset_filter_heuristics(png_ptr);
-   png_free(png_ptr, png_ptr->filter_costs);
-   png_free(png_ptr, png_ptr->inv_filter_costs);
-   png_ptr->filter_costs = NULL;
-   png_ptr->inv_filter_costs = NULL;
+   png_ptr->try_row = NULL;
+   png_ptr->tst_row = NULL;
 #endif
 
 #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
@@ -1044,6 +1033,7 @@ png_set_filter(png_structrp png_ptr, int method, int filters)
 #endif /* WRITE_FILTER */
       }
 
+#ifdef PNG_WRITE_FILTER_SUPPORTED
       /* If we have allocated the row_buf, this means we have already started
        * with the image and we should have allocated all of the filter buffers
        * that have been selected.  If prev_row isn't already allocated, then
@@ -1052,203 +1042,76 @@ png_set_filter(png_structrp png_ptr, int method, int filters)
        * wants to start and stop using particular filters during compression,
        * it should start out with all of the filters, and then remove them
        * or add them back after the start of compression.
+       *
+       * NOTE: this is a nasty constraint on the code, because it means that the
+       * prev_row buffer must be maintained even if there are currently no
+       * 'prev_row' requiring filters active.
        */
       if (png_ptr->row_buf != NULL)
       {
-#ifdef PNG_WRITE_FILTER_SUPPORTED
-         if ((png_ptr->do_filter & PNG_FILTER_SUB) != 0 &&
-             png_ptr->sub_row == NULL)
-         {
-            png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
-                (png_ptr->rowbytes + 1));
-            png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
-         }
+         int num_filters;
+         png_alloc_size_t buf_size;
 
-         if ((png_ptr->do_filter & PNG_FILTER_UP) != 0 &&
-              png_ptr->up_row == NULL)
-         {
-            if (png_ptr->prev_row == NULL)
-            {
-               png_warning(png_ptr, "Can't add Up filter after starting");
-               png_ptr->do_filter = (png_byte)(png_ptr->do_filter &
-                   ~PNG_FILTER_UP);
-            }
+         /* Repeat the checks in png_write_start_row; 1 pixel high or wide
+          * images cannot benefit from certain filters.  If this isn't done here
+          * the check below will fire on 1 pixel high images.
+          */
+         if (png_ptr->height == 1)
+            filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
 
-            else
-            {
-               png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
-                   (png_ptr->rowbytes + 1));
-               png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
-            }
-         }
+         if (png_ptr->width == 1)
+            filters &= ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
 
-         if ((png_ptr->do_filter & PNG_FILTER_AVG) != 0 &&
-              png_ptr->avg_row == NULL)
+         if ((filters & (PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH)) != 0
+            && png_ptr->prev_row == NULL)
          {
-            if (png_ptr->prev_row == NULL)
-            {
-               png_warning(png_ptr, "Can't add Average filter after starting");
-               png_ptr->do_filter = (png_byte)(png_ptr->do_filter &
-                   ~PNG_FILTER_AVG);
-            }
-
-            else
-            {
-               png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
-                   (png_ptr->rowbytes + 1));
-               png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
-            }
+            /* This is the error case, however it is benign - the previous row
+             * is not available so the filter can't be used.  Just warn here.
+             */
+            png_app_warning(png_ptr,
+               "png_set_filter: UP/AVG/PAETH cannot be added after start");
+            filters &= ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
          }
 
-         if ((png_ptr->do_filter & PNG_FILTER_PAETH) != 0 &&
-             png_ptr->paeth_row == NULL)
-         {
-            if (png_ptr->prev_row == NULL)
-            {
-               png_warning(png_ptr, "Can't add Paeth filter after starting");
-               png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
-            }
+         num_filters = 0;
 
-            else
-            {
-               png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
-                   (png_ptr->rowbytes + 1));
-               png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
-            }
-         }
+         if (filters & PNG_FILTER_SUB)
+            num_filters++;
 
-         if (png_ptr->do_filter == PNG_NO_FILTERS)
-#endif /* WRITE_FILTER */
-            png_ptr->do_filter = PNG_FILTER_NONE;
-      }
-   }
-   else
-      png_error(png_ptr, "Unknown custom filter method");
-}
+         if (filters & PNG_FILTER_UP)
+            num_filters++;
 
-/* This allows us to influence the way in which libpng chooses the "best"
- * filter for the current scanline.  While the "minimum-sum-of-absolute-
- * differences metric is relatively fast and effective, there is some
- * question as to whether it can be improved upon by trying to keep the
- * filtered data going to zlib more consistent, hopefully resulting in
- * better compression.
- */
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED      /* GRR 970116 */
-/* Convenience reset API. */
-static void
-png_reset_filter_heuristics(png_structrp png_ptr)
-{
-   /* Clear out any old values in the 'weights' - this must be done because if
-    * the app calls set_filter_heuristics multiple times with different
-    * 'num_weights' values we would otherwise potentially have wrong sized
-    * arrays.
-    */
-   png_ptr->num_prev_filters = 0;
-   png_ptr->heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
-   if (png_ptr->prev_filters != NULL)
-   {
-      png_bytep old = png_ptr->prev_filters;
-      png_ptr->prev_filters = NULL;
-      png_free(png_ptr, old);
-   }
-   if (png_ptr->filter_weights != NULL)
-   {
-      png_uint_16p old = png_ptr->filter_weights;
-      png_ptr->filter_weights = NULL;
-      png_free(png_ptr, old);
-   }
-
-   if (png_ptr->inv_filter_weights != NULL)
-   {
-      png_uint_16p old = png_ptr->inv_filter_weights;
-      png_ptr->inv_filter_weights = NULL;
-      png_free(png_ptr, old);
-   }
-
-   /* Leave the filter_costs - this array is fixed size. */
-}
-
-static int
-png_init_filter_heuristics(png_structrp png_ptr, int heuristic_method,
-   int num_weights)
-{
-   if (png_ptr == NULL)
-      return 0;
+         if (filters & PNG_FILTER_AVG)
+            num_filters++;
 
-   /* Clear out the arrays */
-   png_reset_filter_heuristics(png_ptr);
+         if (filters & PNG_FILTER_PAETH)
+            num_filters++;
 
-   /* Check arguments; the 'reset' function makes the correct settings for the
-    * unweighted case, but we must handle the weight case by initializing the
-    * arrays for the caller.
-    */
-   if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-   {
-      int i;
-
-      if (num_weights > 0)
-      {
-         png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
-             (png_uint_32)((sizeof (png_byte)) * num_weights));
-
-         /* To make sure that the weighting starts out fairly */
-         for (i = 0; i < num_weights; i++)
-         {
-            png_ptr->prev_filters[i] = 255;
-         }
-
-         png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
-             (png_uint_32)((sizeof (png_uint_16)) * num_weights));
+         /* Allocate needed row buffers if they have not already been
+          * allocated.
+          */
+         buf_size = PNG_ROWBYTES(png_ptr->usr_channels * png_ptr->usr_bit_depth,
+             png_ptr->width) + 1;
 
-         png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
-             (png_uint_32)((sizeof (png_uint_16)) * num_weights));
+         if (png_ptr->try_row == NULL)
+            png_ptr->try_row = png_voidcast(png_bytep,
+               png_malloc(png_ptr, buf_size));
 
-         for (i = 0; i < num_weights; i++)
+         if (num_filters > 1)
          {
-            png_ptr->inv_filter_weights[i] =
-            png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
+            if (png_ptr->tst_row == NULL)
+               png_ptr->tst_row = png_voidcast(png_bytep,
+                  png_malloc(png_ptr, buf_size));
          }
-
-         /* Safe to set this now */
-         png_ptr->num_prev_filters = (png_byte)num_weights;
       }
-
-      /* If, in the future, there are other filter methods, this would
-       * need to be based on png_ptr->filter.
-       */
-      if (png_ptr->filter_costs == NULL)
-      {
-         png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
-             (png_uint_32)((sizeof (png_uint_16)) * PNG_FILTER_VALUE_LAST));
-
-         png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
-             (png_uint_32)((sizeof (png_uint_16)) * PNG_FILTER_VALUE_LAST));
-      }
-
-      for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
-      {
-         png_ptr->inv_filter_costs[i] =
-         png_ptr->filter_costs[i] = PNG_COST_FACTOR;
-      }
-
-      /* All the arrays are inited, safe to set this: */
-      png_ptr->heuristic_method = PNG_FILTER_HEURISTIC_WEIGHTED;
-
-      /* Return the 'ok' code. */
-      return 1;
-   }
-   else if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT ||
-      heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
-   {
-      return 1;
+      png_ptr->do_filter = (png_byte)filters;
+#endif
    }
    else
-   {
-      png_warning(png_ptr, "Unknown filter heuristic method");
-      return 0;
-   }
+      png_error(png_ptr, "Unknown custom filter method");
 }
 
+#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED /* DEPRECATED */
 /* Provide floating and fixed point APIs */
 #ifdef PNG_FLOATING_POINT_SUPPORTED
 void PNGAPI
@@ -1256,52 +1119,11 @@ png_set_filter_heuristics(png_structrp png_ptr, int heuristic_method,
     int num_weights, png_const_doublep filter_weights,
     png_const_doublep filter_costs)
 {
-   png_debug(1, "in png_set_filter_heuristics");
-
-   /* The internal API allocates all the arrays and ensures that the elements of
-    * those arrays are set to the default value.
-    */
-   if (png_init_filter_heuristics(png_ptr, heuristic_method, num_weights) == 0)
-      return;
-
-   /* If using the weighted method copy in the weights. */
-   if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-   {
-      int i;
-      for (i = 0; i < num_weights; i++)
-      {
-         if (filter_weights[i] <= 0.0)
-         {
-            png_ptr->inv_filter_weights[i] =
-            png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
-         }
-
-         else
-         {
-            png_ptr->inv_filter_weights[i] =
-                (png_uint_16)(PNG_WEIGHT_FACTOR*filter_weights[i]+.5);
-
-            png_ptr->filter_weights[i] =
-                (png_uint_16)(PNG_WEIGHT_FACTOR/filter_weights[i]+.5);
-         }
-      }
-
-      /* Here is where we set the relative costs of the different filters.  We
-       * should take the desired compression level into account when setting
-       * the costs, so that Paeth, for instance, has a high relative cost at low
-       * compression levels, while it has a lower relative cost at higher
-       * compression settings.  The filter types are in order of increasing
-       * relative cost, so it would be possible to do this with an algorithm.
-       */
-      for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) if (filter_costs[i] >= 1.0)
-      {
-         png_ptr->inv_filter_costs[i] =
-             (png_uint_16)(PNG_COST_FACTOR / filter_costs[i] + .5);
-
-         png_ptr->filter_costs[i] =
-             (png_uint_16)(PNG_COST_FACTOR * filter_costs[i] + .5);
-      }
-   }
+   PNG_UNUSED(png_ptr)
+   PNG_UNUSED(heuristic_method)
+   PNG_UNUSED(num_weights)
+   PNG_UNUSED(filter_weights)
+   PNG_UNUSED(filter_costs)
 }
 #endif /* FLOATING_POINT */
 
@@ -1311,63 +1133,11 @@ png_set_filter_heuristics_fixed(png_structrp png_ptr, int heuristic_method,
     int num_weights, png_const_fixed_point_p filter_weights,
     png_const_fixed_point_p filter_costs)
 {
-   png_debug(1, "in png_set_filter_heuristics_fixed");
-
-   /* The internal API allocates all the arrays and ensures that the elements of
-    * those arrays are set to the default value.
-    */
-   if (png_init_filter_heuristics(png_ptr, heuristic_method, num_weights) == 0)
-      return;
-
-   /* If using the weighted method copy in the weights. */
-   if (heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-   {
-      int i;
-      for (i = 0; i < num_weights; i++)
-      {
-         if (filter_weights[i] <= 0)
-         {
-            png_ptr->inv_filter_weights[i] =
-            png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
-         }
-
-         else
-         {
-            png_ptr->inv_filter_weights[i] = (png_uint_16)
-               ((PNG_WEIGHT_FACTOR*filter_weights[i]+PNG_FP_HALF)/PNG_FP_1);
-
-            png_ptr->filter_weights[i] = (png_uint_16)((PNG_WEIGHT_FACTOR*
-               PNG_FP_1+(filter_weights[i]/2))/filter_weights[i]);
-         }
-      }
-
-      /* Here is where we set the relative costs of the different filters.  We
-       * should take the desired compression level into account when setting
-       * the costs, so that Paeth, for instance, has a high relative cost at low
-       * compression levels, while it has a lower relative cost at higher
-       * compression settings.  The filter types are in order of increasing
-       * relative cost, so it would be possible to do this with an algorithm.
-       */
-      for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
-         if (filter_costs[i] >= PNG_FP_1)
-      {
-         png_uint_32 tmp;
-
-         /* Use a 32 bit unsigned temporary here because otherwise the
-          * intermediate value will be a 32 bit *signed* integer (ANSI rules)
-          * and this will get the wrong answer on division.
-          */
-         tmp = PNG_COST_FACTOR*PNG_FP_1 + (filter_costs[i]/2);
-         tmp /= filter_costs[i];
-
-         png_ptr->inv_filter_costs[i] = (png_uint_16)tmp;
-
-         tmp = PNG_COST_FACTOR * filter_costs[i] + PNG_FP_HALF;
-         tmp /= PNG_FP_1;
-
-         png_ptr->filter_costs[i] = (png_uint_16)tmp;
-      }
-   }
+   PNG_UNUSED(png_ptr)
+   PNG_UNUSED(heuristic_method)
+   PNG_UNUSED(num_weights)
+   PNG_UNUSED(filter_weights)
+   PNG_UNUSED(filter_costs)
 }
 #endif /* FIXED_POINT */
 #endif /* WRITE_WEIGHTED_FILTER */
@@ -1616,14 +1386,14 @@ png_write_png(png_structrp png_ptr, png_inforp info_ptr,
     * alpha channel.
     */
    if ((transforms & (PNG_TRANSFORM_STRIP_FILLER_AFTER|
-      PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
+       PNG_TRANSFORM_STRIP_FILLER_BEFORE)) != 0)
    {
 #ifdef PNG_WRITE_FILLER_SUPPORTED
       if ((transforms & PNG_TRANSFORM_STRIP_FILLER_AFTER) != 0)
       {
          if ((transforms & PNG_TRANSFORM_STRIP_FILLER_BEFORE) != 0)
             png_app_error(png_ptr,
-               "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
+                "PNG_TRANSFORM_STRIP_FILLER: BEFORE+AFTER not supported");
 
          /* Continue if ignored - this is the pre-1.6.10 behavior */
          png_set_filler(png_ptr, 0, PNG_FILLER_AFTER);
@@ -1652,7 +1422,7 @@ png_write_png(png_structrp png_ptr, png_inforp info_ptr,
       png_app_error(png_ptr, "PNG_TRANSFORM_SWAP_ENDIAN not supported");
 #endif
 
-   /* Swap bits of 1, 2, 4 bit packed pixel formats */
+   /* Swap bits of 1-bit, 2-bit, 4-bit packed pixel formats */
    if ((transforms & PNG_TRANSFORM_PACKSWAP) != 0)
 #ifdef PNG_WRITE_PACKSWAP_SUPPORTED
       png_set_packswap(png_ptr);
@@ -1682,13 +1452,13 @@ png_write_png(png_structrp png_ptr, png_inforp info_ptr,
 
 
 #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
-#ifdef PNG_STDIO_SUPPORTED /* currently required for png_image_write_* */
+# ifdef PNG_STDIO_SUPPORTED /* currently required for png_image_write_* */
 /* Initialize the write structure - general purpose utility. */
 static int
 png_image_write_init(png_imagep image)
 {
    png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, image,
-          png_safe_error, png_safe_warning);
+       png_safe_error, png_safe_warning);
 
    if (png_ptr != NULL)
    {
@@ -1697,7 +1467,7 @@ png_image_write_init(png_imagep image)
       if (info_ptr != NULL)
       {
          png_controlp control = png_voidcast(png_controlp,
-            png_malloc_warn(png_ptr, (sizeof *control)));
+             png_malloc_warn(png_ptr, (sizeof *control)));
 
          if (control != NULL)
          {
@@ -1744,12 +1514,12 @@ static int
 png_write_image_16bit(png_voidp argument)
 {
    png_image_write_control *display = png_voidcast(png_image_write_control*,
-      argument);
+       argument);
    png_imagep image = display->image;
    png_structrp png_ptr = image->opaque->png_ptr;
 
    png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
-      display->first_row);
+       display->first_row);
    png_uint_16p output_row = png_voidcast(png_uint_16p, display->local_row);
    png_uint_16p row_end;
    const int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
@@ -1758,17 +1528,18 @@ png_write_image_16bit(png_voidp argument)
 
    if ((image->format & PNG_FORMAT_FLAG_ALPHA) != 0)
    {
-#     ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
-         if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
-         {
-            aindex = -1;
-            ++input_row; /* To point to the first component */
-            ++output_row;
-         }
-
+#   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
+      if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
+      {
+         aindex = -1;
+         ++input_row; /* To point to the first component */
+         ++output_row;
+      }
          else
-#     endif
+            aindex = channels;
+#     else
          aindex = channels;
+#     endif
    }
 
    else
@@ -1850,7 +1621,7 @@ png_write_image_16bit(png_voidp argument)
  * calculation can be done to 15 bits of accuracy; however, the output needs to
  * be scaled in the range 0..255*65535, so include that scaling here.
  */
-#define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+(alpha>>1))/alpha)
+#   define UNP_RECIPROCAL(alpha) ((((0xffff*0xff)<<7)+(alpha>>1))/alpha)
 
 static png_byte
 png_unpremultiply(png_uint_32 component, png_uint_32 alpha,
@@ -1901,12 +1672,12 @@ static int
 png_write_image_8bit(png_voidp argument)
 {
    png_image_write_control *display = png_voidcast(png_image_write_control*,
-      argument);
+       argument);
    png_imagep image = display->image;
    png_structrp png_ptr = image->opaque->png_ptr;
 
    png_const_uint_16p input_row = png_voidcast(png_const_uint_16p,
-      display->first_row);
+       display->first_row);
    png_bytep output_row = png_voidcast(png_bytep, display->local_row);
    png_uint_32 y = image->height;
    const int channels = (image->format & PNG_FORMAT_FLAG_COLOR) != 0 ? 3 : 1;
@@ -1916,17 +1687,17 @@ png_write_image_8bit(png_voidp argument)
       png_bytep row_end;
       int aindex;
 
-#     ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
-         if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
-         {
-            aindex = -1;
-            ++input_row; /* To point to the first component */
-            ++output_row;
-         }
+#   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
+      if ((image->format & PNG_FORMAT_FLAG_AFIRST) != 0)
+      {
+         aindex = -1;
+         ++input_row; /* To point to the first component */
+         ++output_row;
+      }
 
-         else
-#     endif
-         aindex = channels;
+      else
+#   endif
+      aindex = channels;
 
       /* Use row_end in place of a loop counter: */
       row_end = output_row + image->width * (channels+1);
@@ -1960,7 +1731,7 @@ png_write_image_8bit(png_voidp argument)
          } /* while out_ptr < row_end */
 
          png_write_row(png_ptr, png_voidcast(png_const_bytep,
-            display->local_row));
+             display->local_row));
          input_row += display->row_bytes/(sizeof (png_uint_16));
       } /* while y */
    }
@@ -1999,25 +1770,25 @@ png_image_set_PLTE(png_image_write_control *display)
    const png_imagep image = display->image;
    const void *cmap = display->colormap;
    const int entries = image->colormap_entries > 256 ? 256 :
-      (int)image->colormap_entries;
+       (int)image->colormap_entries;
 
    /* NOTE: the caller must check for cmap != NULL and entries != 0 */
    const png_uint_32 format = image->format;
    const int channels = PNG_IMAGE_SAMPLE_CHANNELS(format);
 
-#  if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
+#   if defined(PNG_FORMAT_BGR_SUPPORTED) &&\
       defined(PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED)
       const int afirst = (format & PNG_FORMAT_FLAG_AFIRST) != 0 &&
-         (format & PNG_FORMAT_FLAG_ALPHA) != 0;
-#  else
+          (format & PNG_FORMAT_FLAG_ALPHA) != 0;
+#   else
 #     define afirst 0
-#  endif
+#   endif
 
-#  ifdef PNG_FORMAT_BGR_SUPPORTED
+#   ifdef PNG_FORMAT_BGR_SUPPORTED
       const int bgr = (format & PNG_FORMAT_FLAG_BGR) != 0 ? 2 : 0;
-#  else
+#   else
 #     define bgr 0
-#  endif
+#   endif
 
    int i, num_trans;
    png_color palette[256];
@@ -2042,11 +1813,11 @@ png_image_set_PLTE(png_image_write_control *display)
             if (channels >= 3) /* RGB */
             {
                palette[i].blue = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
-                  entry[(2 ^ bgr)]);
+                   entry[(2 ^ bgr)]);
                palette[i].green = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
-                  entry[1]);
+                   entry[1]);
                palette[i].red = (png_byte)PNG_sRGB_FROM_LINEAR(255 *
-                  entry[bgr]);
+                   entry[bgr]);
             }
 
             else /* Gray */
@@ -2122,12 +1893,12 @@ png_image_set_PLTE(png_image_write_control *display)
       }
    }
 
-#  ifdef afirst
+#   ifdef afirst
 #     undef afirst
-#  endif
-#  ifdef bgr
+#   endif
+#   ifdef bgr
 #     undef bgr
-#  endif
+#   endif
 
    png_set_PLTE(image->opaque->png_ptr, image->opaque->info_ptr, palette,
       entries);
@@ -2155,10 +1926,10 @@ png_image_write_main(png_voidp argument)
    int alpha = !colormap && (format & PNG_FORMAT_FLAG_ALPHA);
    int write_16bit = linear && !colormap && (display->convert_to_8bit == 0);
 
-#  ifdef PNG_BENIGN_ERRORS_SUPPORTED
+#   ifdef PNG_BENIGN_ERRORS_SUPPORTED
       /* Make sure we error out on any bad situation */
       png_set_benign_errors(png_ptr, 0/*error*/);
-#  endif
+#   endif
 
    /* Default the 'row_stride' parameter if required. */
    if (display->row_stride == 0)
@@ -2227,7 +1998,7 @@ png_image_write_main(png_voidp argument)
    /* Now set up the data transformations (*after* the header is written),
     * remove the handled transformations from the 'format' flags for checking.
     *
-    * First check for a little endian system if writing 16 bit files.
+    * First check for a little endian system if writing 16-bit files.
     */
    if (write_16bit != 0)
    {
@@ -2237,23 +2008,23 @@ png_image_write_main(png_voidp argument)
          png_set_swap(png_ptr);
    }
 
-#  ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
+#   ifdef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
       if ((format & PNG_FORMAT_FLAG_BGR) != 0)
       {
          if (colormap == 0 && (format & PNG_FORMAT_FLAG_COLOR) != 0)
             png_set_bgr(png_ptr);
          format &= ~PNG_FORMAT_FLAG_BGR;
       }
-#  endif
+#   endif
 
-#  ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
+#   ifdef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
       if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
       {
          if (colormap == 0 && (format & PNG_FORMAT_FLAG_ALPHA) != 0)
             png_set_swap_alpha(png_ptr);
          format &= ~PNG_FORMAT_FLAG_AFIRST;
       }
-#  endif
+#   endif
 
    /* If there are 16 or fewer color-map entries we wrote a lower bit depth
     * above, but the application data is still byte packed.
@@ -2289,9 +2060,9 @@ png_image_write_main(png_voidp argument)
        * it about 50 times.  The speed-up in pngstest was about 10-20% of the
        * total (user) time on a heavily loaded system.
        */
-#ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
+#   ifdef PNG_WRITE_CUSTOMIZE_COMPRESSION_SUPPORTED
       png_set_compression_level(png_ptr, 3);
-#endif
+#   endif
    }
 
    /* Check for the cases that currently require a pre-transform on the row
@@ -2454,6 +2225,6 @@ png_image_write_to_file(png_imagep image, const char *file_name,
    else
       return 0;
 }
-#endif /* STDIO */
+# endif /* STDIO */
 #endif /* SIMPLIFIED_WRITE */
 #endif /* WRITE */
diff --git a/src/3rdparty/libpng/pngwtran.c b/src/3rdparty/libpng/pngwtran.c
index db82e27bcea5d874afc43d372ba9b6520791a123..5dc949157d410ba0edbeb07b9a06d82f203562c4 100644
--- a/src/3rdparty/libpng/pngwtran.c
+++ b/src/3rdparty/libpng/pngwtran.c
@@ -1,7 +1,7 @@
 
 /* pngwtran.c - transforms the data in a row for PNG writers
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.18 [July 23, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -71,7 +71,8 @@ png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
          case 2:
          {
             png_bytep sp, dp;
-            int shift, v;
+            unsigned int shift;
+            int v;
             png_uint_32 i;
             png_uint_32 row_width = row_info->width;
 
@@ -110,7 +111,8 @@ png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
          case 4:
          {
             png_bytep sp, dp;
-            int shift, v;
+            unsigned int shift;
+            int v;
             png_uint_32 i;
             png_uint_32 row_width = row_info->width;
 
@@ -422,7 +424,7 @@ png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
                *(dp++) = *(sp++);
                */
                sp+=3; dp = sp;
-               *(dp++) = (png_byte)(255 - *(sp++));
+               *dp = (png_byte)(255 - *(sp++));
             }
          }
 
@@ -446,7 +448,7 @@ png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
                */
                sp+=6; dp = sp;
                *(dp++) = (png_byte)(255 - *(sp++));
-               *(dp++) = (png_byte)(255 - *(sp++));
+               *dp     = (png_byte)(255 - *(sp++));
             }
          }
 #endif /* WRITE_16BIT */
@@ -484,7 +486,7 @@ png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
                */
                sp+=2; dp = sp;
                *(dp++) = (png_byte)(255 - *(sp++));
-               *(dp++) = (png_byte)(255 - *(sp++));
+               *dp     = (png_byte)(255 - *(sp++));
             }
          }
 #endif /* WRITE_16BIT */
diff --git a/src/3rdparty/libpng/pngwutil.c b/src/3rdparty/libpng/pngwutil.c
index b289671d12fd0f3e2175190cf922819e4882fb69..adc4729c24168bfe95730c604d1dd5e5c61b6846 100644
--- a/src/3rdparty/libpng/pngwutil.c
+++ b/src/3rdparty/libpng/pngwutil.c
@@ -1,7 +1,7 @@
 
 /* pngwutil.c - utilities to write a PNG file
  *
- * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Last changed in libpng 1.6.19 [November 12, 2015]
  * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
@@ -179,7 +179,7 @@ png_write_complete_chunk(png_structrp png_ptr, png_uint_32 chunk_name,
    if (png_ptr == NULL)
       return;
 
-   /* On 64 bit architectures 'length' may not fit in a png_uint_32. */
+   /* On 64-bit architectures 'length' may not fit in a png_uint_32. */
    if (length > PNG_UINT_31_MAX)
       png_error(png_ptr, "length exceeds PNG maximum");
 
@@ -308,7 +308,7 @@ png_deflate_claim(png_structrp png_ptr, png_uint_32 owner,
        */
       (void)png_safecat(msg, (sizeof msg), 10, " using zstream");
 #endif
-#if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC
+#if PNG_RELEASE_BUILD
          png_warning(png_ptr, msg);
 
          /* Attempt sane error recovery */
@@ -922,17 +922,20 @@ void /* PRIVATE */
 png_write_PLTE(png_structrp png_ptr, png_const_colorp palette,
     png_uint_32 num_pal)
 {
-   png_uint_32 i;
+   png_uint_32 max_palette_length, i;
    png_const_colorp pal_ptr;
    png_byte buf[3];
 
    png_debug(1, "in png_write_PLTE");
 
+   max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ?
+      (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH;
+
    if ((
 #ifdef PNG_MNG_FEATURES_SUPPORTED
        (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0 &&
 #endif
-       num_pal == 0) || num_pal > 256)
+       num_pal == 0) || num_pal > max_palette_length)
    {
       if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
       {
@@ -1444,7 +1447,7 @@ png_write_tRNS(png_structrp png_ptr, png_const_bytep trans_alpha,
 
    else if (color_type == PNG_COLOR_TYPE_GRAY)
    {
-      /* One 16 bit value */
+      /* One 16-bit value */
       if (tran->gray >= (1 << png_ptr->bit_depth))
       {
          png_app_warning(png_ptr,
@@ -1459,7 +1462,7 @@ png_write_tRNS(png_structrp png_ptr, png_const_bytep trans_alpha,
 
    else if (color_type == PNG_COLOR_TYPE_RGB)
    {
-      /* Three 16 bit values */
+      /* Three 16-bit values */
       png_save_uint_16(buf, tran->red);
       png_save_uint_16(buf + 2, tran->green);
       png_save_uint_16(buf + 4, tran->blue);
@@ -1961,6 +1964,10 @@ png_write_start_row(png_structrp png_ptr)
    png_alloc_size_t buf_size;
    int usr_pixel_depth;
 
+#ifdef PNG_WRITE_FILTER_SUPPORTED
+   png_byte filters;
+#endif
+
    png_debug(1, "in png_write_start_row");
 
    usr_pixel_depth = png_ptr->usr_channels * png_ptr->usr_bit_depth;
@@ -1971,50 +1978,54 @@ png_write_start_row(png_structrp png_ptr)
    png_ptr->maximum_pixel_depth = (png_byte)usr_pixel_depth;
 
    /* Set up row buffer */
-   png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, buf_size);
+   png_ptr->row_buf = png_voidcast(png_bytep, png_malloc(png_ptr, buf_size));
 
    png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
 
 #ifdef PNG_WRITE_FILTER_SUPPORTED
-   /* Set up filtering buffer, if using this filter */
-   if (png_ptr->do_filter & PNG_FILTER_SUB)
-   {
-      png_ptr->sub_row = (png_bytep)png_malloc(png_ptr, png_ptr->rowbytes + 1);
+   filters = png_ptr->do_filter;
 
-      png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
-   }
+   if (png_ptr->height == 1)
+      filters &= 0xff & ~(PNG_FILTER_UP|PNG_FILTER_AVG|PNG_FILTER_PAETH);
+
+   if (png_ptr->width == 1)
+      filters &= 0xff & ~(PNG_FILTER_SUB|PNG_FILTER_AVG|PNG_FILTER_PAETH);
+
+   if (filters == 0)
+      filters = PNG_FILTER_NONE;
 
-   /* We only need to keep the previous row if we are using one of these. */
-   if ((png_ptr->do_filter &
-      (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) != 0)
+   png_ptr->do_filter = filters;
+
+   if (((filters & (PNG_FILTER_SUB | PNG_FILTER_UP | PNG_FILTER_AVG |
+       PNG_FILTER_PAETH)) != 0) && png_ptr->try_row == NULL)
    {
-      /* Set up previous row buffer */
-      png_ptr->prev_row = (png_bytep)png_calloc(png_ptr, buf_size);
+      int num_filters = 0;
 
-      if ((png_ptr->do_filter & PNG_FILTER_UP) != 0)
-      {
-         png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
-            png_ptr->rowbytes + 1);
+      png_ptr->try_row = png_voidcast(png_bytep, png_malloc(png_ptr, buf_size));
 
-         png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
-      }
+      if (filters & PNG_FILTER_SUB)
+         num_filters++;
 
-      if ((png_ptr->do_filter & PNG_FILTER_AVG) != 0)
-      {
-         png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
-             png_ptr->rowbytes + 1);
+      if (filters & PNG_FILTER_UP)
+         num_filters++;
 
-         png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
-      }
+      if (filters & PNG_FILTER_AVG)
+         num_filters++;
 
-      if ((png_ptr->do_filter & PNG_FILTER_PAETH) != 0)
-      {
-         png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
-             png_ptr->rowbytes + 1);
+      if (filters & PNG_FILTER_PAETH)
+         num_filters++;
 
-         png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
-      }
+      if (num_filters > 1)
+         png_ptr->tst_row = png_voidcast(png_bytep, png_malloc(png_ptr,
+             buf_size));
    }
+
+   /* We only need to keep the previous row if we are using one of the following
+    * filters.
+    */
+   if ((filters & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH)) != 0)
+      png_ptr->prev_row = png_voidcast(png_bytep,
+         png_calloc(png_ptr, buf_size));
 #endif /* WRITE_FILTER */
 
 #ifdef PNG_WRITE_INTERLACING_SUPPORTED
@@ -2160,7 +2171,7 @@ png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
          {
             png_bytep sp;
             png_bytep dp;
-            int shift;
+            unsigned int shift;
             int d;
             int value;
             png_uint_32 i;
@@ -2198,7 +2209,7 @@ png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
          {
             png_bytep sp;
             png_bytep dp;
-            int shift;
+            unsigned int shift;
             int d;
             int value;
             png_uint_32 i;
@@ -2235,7 +2246,7 @@ png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
          {
             png_bytep sp;
             png_bytep dp;
-            int shift;
+            unsigned int shift;
             int d;
             int value;
             png_uint_32 i;
@@ -2310,6 +2321,7 @@ png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
 }
 #endif
 
+
 /* This filters the row, chooses which filter to use, if it has not already
  * been specified by the application, and then writes the row out with the
  * chosen filter.
@@ -2318,42 +2330,172 @@ static void /* PRIVATE */
 png_write_filtered_row(png_structrp png_ptr, png_bytep filtered_row,
    png_size_t row_bytes);
 
-#define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
-#define PNG_HISHIFT 10
-#define PNG_LOMASK ((png_uint_32)0xffffL)
-#define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
+#ifdef PNG_WRITE_FILTER_SUPPORTED
+static png_size_t /* PRIVATE */
+png_setup_sub_row(png_structrp png_ptr, const png_uint_32 bpp,
+    const png_size_t row_bytes, const png_size_t lmins)
+{
+   png_bytep rp, dp, lp;
+   png_size_t i;
+   png_size_t sum = 0;
+   int v;
+
+   png_ptr->try_row[0] = PNG_FILTER_VALUE_SUB;
+
+   for (i = 0, rp = png_ptr->row_buf + 1, dp = png_ptr->try_row + 1; i < bpp;
+        i++, rp++, dp++)
+   {
+      v = *dp = *rp;
+      sum += (v < 128) ? v : 256 - v;
+   }
+
+   for (lp = png_ptr->row_buf + 1; i < row_bytes;
+      i++, rp++, lp++, dp++)
+   {
+      v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
+      sum += (v < 128) ? v : 256 - v;
+
+      if (sum > lmins)  /* We are already worse, don't continue. */
+        break;
+   }
+
+   return (sum);
+}
+
+static png_size_t /* PRIVATE */
+png_setup_up_row(png_structrp png_ptr, const png_size_t row_bytes,
+    const png_size_t lmins)
+{
+   png_bytep rp, dp, pp;
+   png_size_t i;
+   png_size_t sum = 0;
+   int v;
+
+   png_ptr->try_row[0] = PNG_FILTER_VALUE_UP;
+
+   for (i = 0, rp = png_ptr->row_buf + 1, dp = png_ptr->try_row + 1,
+       pp = png_ptr->prev_row + 1; i < row_bytes;
+       i++, rp++, pp++, dp++)
+   {
+      v = *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
+      sum += (v < 128) ? v : 256 - v;
+
+      if (sum > lmins)  /* We are already worse, don't continue. */
+        break;
+   }
+
+   return (sum);
+}
+
+static png_size_t /* PRIVATE */
+png_setup_avg_row(png_structrp png_ptr, const png_uint_32 bpp,
+      const png_size_t row_bytes, const png_size_t lmins)
+{
+   png_bytep rp, dp, pp, lp;
+   png_uint_32 i;
+   png_size_t sum = 0;
+   int v;
+
+   png_ptr->try_row[0] = PNG_FILTER_VALUE_AVG;
+
+   for (i = 0, rp = png_ptr->row_buf + 1, dp = png_ptr->try_row + 1,
+        pp = png_ptr->prev_row + 1; i < bpp; i++)
+   {
+      v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
+
+      sum += (v < 128) ? v : 256 - v;
+   }
+
+   for (lp = png_ptr->row_buf + 1; i < row_bytes; i++)
+   {
+      v = *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
+          & 0xff);
+
+      sum += (v < 128) ? v : 256 - v;
+
+      if (sum > lmins)  /* We are already worse, don't continue. */
+        break;
+   }
+
+   return (sum);
+}
+
+static png_size_t /* PRIVATE */
+png_setup_paeth_row(png_structrp png_ptr, const png_uint_32 bpp,
+    const png_size_t row_bytes, const png_size_t lmins)
+{
+   png_bytep rp, dp, pp, cp, lp;
+   png_size_t i;
+   png_size_t sum = 0;
+   int v;
+
+   png_ptr->try_row[0] = PNG_FILTER_VALUE_PAETH;
+
+   for (i = 0, rp = png_ptr->row_buf + 1, dp = png_ptr->try_row + 1,
+       pp = png_ptr->prev_row + 1; i < bpp; i++)
+   {
+      v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
+
+      sum += (v < 128) ? v : 256 - v;
+   }
+
+   for (lp = png_ptr->row_buf + 1, cp = png_ptr->prev_row + 1; i < row_bytes;
+        i++)
+   {
+      int a, b, c, pa, pb, pc, p;
+
+      b = *pp++;
+      c = *cp++;
+      a = *lp++;
+
+      p = b - c;
+      pc = a - c;
+
+#ifdef PNG_USE_ABS
+      pa = abs(p);
+      pb = abs(pc);
+      pc = abs(p + pc);
+#else
+      pa = p < 0 ? -p : p;
+      pb = pc < 0 ? -pc : pc;
+      pc = (p + pc) < 0 ? -(p + pc) : p + pc;
+#endif
+
+      p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
+
+      v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
+
+      sum += (v < 128) ? v : 256 - v;
+
+      if (sum > lmins)  /* We are already worse, don't continue. */
+        break;
+   }
+
+   return (sum);
+}
+#endif /* WRITE_FILTER */
+
 void /* PRIVATE */
 png_write_find_filter(png_structrp png_ptr, png_row_infop row_info)
 {
-   png_bytep best_row;
-#ifdef PNG_WRITE_FILTER_SUPPORTED
-   png_bytep prev_row, row_buf;
-   png_uint_32 mins, bpp;
+#ifndef PNG_WRITE_FILTER_SUPPORTED
+   png_write_filtered_row(png_ptr, png_ptr->row_buf, row_info->rowbytes+1);
+#else
    png_byte filter_to_do = png_ptr->do_filter;
+   png_bytep row_buf;
+   png_bytep best_row;
+   png_uint_32 bpp;
+   png_size_t mins;
    png_size_t row_bytes = row_info->rowbytes;
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-   int num_p_filters = png_ptr->num_prev_filters;
-#endif
 
    png_debug(1, "in png_write_find_filter");
 
-#ifndef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-  if (png_ptr->row_number == 0 && filter_to_do == PNG_ALL_FILTERS)
-  {
-     /* These will never be selected so we need not test them. */
-     filter_to_do &= ~(PNG_FILTER_UP | PNG_FILTER_PAETH);
-  }
-#endif
-
    /* Find out how many bytes offset each pixel is */
    bpp = (row_info->pixel_depth + 7) >> 3;
 
-   prev_row = png_ptr->prev_row;
-#endif
-   best_row = png_ptr->row_buf;
-#ifdef PNG_WRITE_FILTER_SUPPORTED
-   row_buf = best_row;
-   mins = PNG_MAXSUM;
+   row_buf = png_ptr->row_buf;
+   mins = PNG_SIZE_MAX - 256/* so we can detect potential overflow of the
+                               running sum */;
 
    /* The prediction method we use is to find which method provides the
     * smallest value when summing the absolute values of the distances
@@ -2383,57 +2525,37 @@ png_write_find_filter(png_structrp png_ptr, png_row_infop row_info)
    /* We don't need to test the 'no filter' case if this is the only filter
     * that has been chosen, as it doesn't actually do anything to the data.
     */
+   best_row = png_ptr->row_buf;
+
+
    if ((filter_to_do & PNG_FILTER_NONE) != 0 && filter_to_do != PNG_FILTER_NONE)
    {
       png_bytep rp;
-      png_uint_32 sum = 0;
+      png_size_t sum = 0;
       png_size_t i;
       int v;
 
-      for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
+      if (PNG_SIZE_MAX/128 <= row_bytes)
       {
-         v = *rp;
-         sum += (v < 128) ? v : 256 - v;
-      }
+         for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
+         {
+            /* Check for overflow */
+            if (sum > PNG_SIZE_MAX/128 - 256)
+               break;
 
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
+            v = *rp;
+            sum += (v < 128) ? v : 256 - v;
+         }
+      }
+      else /* Overflow is not possible */
       {
-         png_uint_32 sumhi, sumlo;
-         int j;
-         sumlo = sum & PNG_LOMASK;
-         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
-
-         /* Reduce the sum if we match any of the previous rows */
-         for (j = 0; j < num_p_filters; j++)
+         for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
          {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
-            {
-               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
+            v = *rp;
+            sum += (v < 128) ? v : 256 - v;
          }
-
-         /* Factor in the cost of this filter (this is here for completeness,
-          * but it makes no sense to have a "cost" for the NONE filter, as
-          * it has the minimum possible computational cost - none).
-          */
-         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
-             PNG_COST_SHIFT;
-
-         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
-             PNG_COST_SHIFT;
-
-         if (sumhi > PNG_HIMASK)
-            sum = PNG_MAXSUM;
-
-         else
-            sum = (sumhi << PNG_HISHIFT) + sumlo;
       }
-#endif
+
       mins = sum;
    }
 
@@ -2441,553 +2563,109 @@ png_write_find_filter(png_structrp png_ptr, png_row_infop row_info)
    if (filter_to_do == PNG_FILTER_SUB)
    /* It's the only filter so no testing is needed */
    {
-      png_bytep rp, lp, dp;
-      png_size_t i;
-
-      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
-           i++, rp++, dp++)
-      {
-         *dp = *rp;
-      }
-
-      for (lp = row_buf + 1; i < row_bytes;
-         i++, rp++, lp++, dp++)
-      {
-         *dp = (png_byte)((int)*rp - (int)*lp);
-      }
-
-      best_row = png_ptr->sub_row;
+      (void) png_setup_sub_row(png_ptr, bpp, row_bytes, mins); 
+      best_row = png_ptr->try_row;
    }
 
    else if ((filter_to_do & PNG_FILTER_SUB) != 0)
    {
-      png_bytep rp, dp, lp;
-      png_uint_32 sum = 0, lmins = mins;
-      png_size_t i;
-      int v;
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      /* We temporarily increase the "minimum sum" by the factor we
-       * would reduce the sum of this filter, so that we can do the
-       * early exit comparison without scaling the sum each time.
-       */
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-      {
-         int j;
-         png_uint_32 lmhi, lmlo;
-         lmlo = lmins & PNG_LOMASK;
-         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
-
-         for (j = 0; j < num_p_filters; j++)
-         {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
-            {
-               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
-         }
-
-         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
-             PNG_COST_SHIFT;
-
-         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
-             PNG_COST_SHIFT;
+      png_size_t sum;
+      png_size_t lmins = mins;
 
-         if (lmhi > PNG_HIMASK)
-            lmins = PNG_MAXSUM;
-
-         else
-            lmins = (lmhi << PNG_HISHIFT) + lmlo;
-      }
-#endif
-
-      for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
-           i++, rp++, dp++)
-      {
-         v = *dp = *rp;
-
-         sum += (v < 128) ? v : 256 - v;
-      }
-
-      for (lp = row_buf + 1; i < row_bytes;
-         i++, rp++, lp++, dp++)
-      {
-         v = *dp = (png_byte)((int)*rp - (int)*lp);
-
-         sum += (v < 128) ? v : 256 - v;
-
-         if (sum > lmins)  /* We are already worse, don't continue. */
-            break;
-      }
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-      {
-         int j;
-         png_uint_32 sumhi, sumlo;
-         sumlo = sum & PNG_LOMASK;
-         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
-
-         for (j = 0; j < num_p_filters; j++)
-         {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
-            {
-               sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
-         }
-
-         sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
-             PNG_COST_SHIFT;
-
-         sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
-             PNG_COST_SHIFT;
-
-         if (sumhi > PNG_HIMASK)
-            sum = PNG_MAXSUM;
-
-         else
-            sum = (sumhi << PNG_HISHIFT) + sumlo;
-      }
-#endif
+      sum = png_setup_sub_row(png_ptr, bpp, row_bytes, lmins); 
 
       if (sum < mins)
       {
          mins = sum;
-         best_row = png_ptr->sub_row;
+         best_row = png_ptr->try_row;
+         if (png_ptr->tst_row != NULL)
+         {
+            png_ptr->try_row = png_ptr->tst_row;
+            png_ptr->tst_row = best_row;
+         }
       }
    }
 
    /* Up filter */
    if (filter_to_do == PNG_FILTER_UP)
    {
-      png_bytep rp, dp, pp;
-      png_size_t i;
-
-      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
-          pp = prev_row + 1; i < row_bytes;
-          i++, rp++, pp++, dp++)
-      {
-         *dp = (png_byte)((int)*rp - (int)*pp);
-      }
-
-      best_row = png_ptr->up_row;
+      (void) png_setup_up_row(png_ptr, row_bytes, mins);
+      best_row = png_ptr->try_row;
    }
 
    else if ((filter_to_do & PNG_FILTER_UP) != 0)
    {
-      png_bytep rp, dp, pp;
-      png_uint_32 sum = 0, lmins = mins;
-      png_size_t i;
-      int v;
-
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-      {
-         int j;
-         png_uint_32 lmhi, lmlo;
-         lmlo = lmins & PNG_LOMASK;
-         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
-
-         for (j = 0; j < num_p_filters; j++)
-         {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
-            {
-               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
-         }
-
-         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
-             PNG_COST_SHIFT;
-
-         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
-             PNG_COST_SHIFT;
-
-         if (lmhi > PNG_HIMASK)
-            lmins = PNG_MAXSUM;
-
-         else
-            lmins = (lmhi << PNG_HISHIFT) + lmlo;
-      }
-#endif
-
-      for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
-          pp = prev_row + 1; i < row_bytes; i++)
-      {
-         v = *dp++ = (png_byte)((int)*rp++ - (int)*pp++);
+      png_size_t sum;
+      png_size_t lmins = mins;
 
-         sum += (v < 128) ? v : 256 - v;
-
-         if (sum > lmins)  /* We are already worse, don't continue. */
-            break;
-      }
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-      {
-         int j;
-         png_uint_32 sumhi, sumlo;
-         sumlo = sum & PNG_LOMASK;
-         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
-
-         for (j = 0; j < num_p_filters; j++)
-         {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
-            {
-               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
-         }
-
-         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
-             PNG_COST_SHIFT;
-
-         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
-             PNG_COST_SHIFT;
-
-         if (sumhi > PNG_HIMASK)
-            sum = PNG_MAXSUM;
-
-         else
-            sum = (sumhi << PNG_HISHIFT) + sumlo;
-      }
-#endif
+      sum = png_setup_up_row(png_ptr, row_bytes, lmins); 
 
       if (sum < mins)
       {
          mins = sum;
-         best_row = png_ptr->up_row;
+         best_row = png_ptr->try_row;
+         if (png_ptr->tst_row != NULL)
+         {
+            png_ptr->try_row = png_ptr->tst_row;
+            png_ptr->tst_row = best_row;
+         }
       }
    }
 
    /* Avg filter */
    if (filter_to_do == PNG_FILTER_AVG)
    {
-      png_bytep rp, dp, pp, lp;
-      png_uint_32 i;
-
-      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
-           pp = prev_row + 1; i < bpp; i++)
-      {
-         *dp++ = (png_byte)((int)*rp++ - ((int)*pp++ / 2));
-      }
-
-      for (lp = row_buf + 1; i < row_bytes; i++)
-      {
-         *dp++ =
-             (png_byte)((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2));
-      }
-      best_row = png_ptr->avg_row;
+      (void) png_setup_avg_row(png_ptr, bpp, row_bytes, mins);
+      best_row = png_ptr->try_row;
    }
 
    else if ((filter_to_do & PNG_FILTER_AVG) != 0)
    {
-      png_bytep rp, dp, pp, lp;
-      png_uint_32 sum = 0, lmins = mins;
-      png_size_t i;
-      int v;
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-      {
-         int j;
-         png_uint_32 lmhi, lmlo;
-         lmlo = lmins & PNG_LOMASK;
-         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
-
-         for (j = 0; j < num_p_filters; j++)
-         {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
-            {
-               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
-         }
-
-         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
-             PNG_COST_SHIFT;
-
-         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
-             PNG_COST_SHIFT;
-
-         if (lmhi > PNG_HIMASK)
-            lmins = PNG_MAXSUM;
-
-         else
-            lmins = (lmhi << PNG_HISHIFT) + lmlo;
-      }
-#endif
-
-      for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
-           pp = prev_row + 1; i < bpp; i++)
-      {
-         v = *dp++ = (png_byte)((int)*rp++ - ((int)*pp++ / 2));
-
-         sum += (v < 128) ? v : 256 - v;
-      }
-
-      for (lp = row_buf + 1; i < row_bytes; i++)
-      {
-         v = *dp++ =
-             (png_byte)(((int)*rp++ - ((int)*pp++ + (int)*lp++) / 2));
-
-         sum += (v < 128) ? v : 256 - v;
-
-         if (sum > lmins)  /* We are already worse, don't continue. */
-            break;
-      }
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-      {
-         int j;
-         png_uint_32 sumhi, sumlo;
-         sumlo = sum & PNG_LOMASK;
-         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
-
-         for (j = 0; j < num_p_filters; j++)
-         {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
-            {
-               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
-         }
-
-         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
-             PNG_COST_SHIFT;
+      png_size_t sum;
+      png_size_t lmins = mins;
 
-         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
-             PNG_COST_SHIFT;
-
-         if (sumhi > PNG_HIMASK)
-            sum = PNG_MAXSUM;
-
-         else
-            sum = (sumhi << PNG_HISHIFT) + sumlo;
-      }
-#endif
+      sum= png_setup_avg_row(png_ptr, bpp, row_bytes, lmins);
 
       if (sum < mins)
       {
          mins = sum;
-         best_row = png_ptr->avg_row;
+         best_row = png_ptr->try_row;
+         if (png_ptr->tst_row != NULL)
+         {
+            png_ptr->try_row = png_ptr->tst_row;
+            png_ptr->tst_row = best_row;
+         }
       }
    }
 
    /* Paeth filter */
    if ((filter_to_do == PNG_FILTER_PAETH) != 0)
    {
-      png_bytep rp, dp, pp, cp, lp;
-      png_size_t i;
-
-      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
-          pp = prev_row + 1; i < bpp; i++)
-      {
-         *dp++ = (png_byte)((int)*rp++ - (int)*pp++);
-      }
-
-      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
-      {
-         int a, b, c, pa, pb, pc, p;
-
-         b = *pp++;
-         c = *cp++;
-         a = *lp++;
-
-         p = b - c;
-         pc = a - c;
-
-#ifdef PNG_USE_ABS
-         pa = abs(p);
-         pb = abs(pc);
-         pc = abs(p + pc);
-#else
-         pa = p < 0 ? -p : p;
-         pb = pc < 0 ? -pc : pc;
-         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
-#endif
-
-         p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
-
-         *dp++ = (png_byte)((int)*rp++ - p);
-      }
-      best_row = png_ptr->paeth_row;
+      (void) png_setup_paeth_row(png_ptr, bpp, row_bytes, mins);
+      best_row = png_ptr->try_row;
    }
 
    else if ((filter_to_do & PNG_FILTER_PAETH) != 0)
    {
-      png_bytep rp, dp, pp, cp, lp;
-      png_uint_32 sum = 0, lmins = mins;
-      png_size_t i;
-      int v;
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
-      {
-         int j;
-         png_uint_32 lmhi, lmlo;
-         lmlo = lmins & PNG_LOMASK;
-         lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
-
-         for (j = 0; j < num_p_filters; j++)
-         {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
-            {
-               lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
-         }
-
-         lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
-             PNG_COST_SHIFT;
-
-         lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
-             PNG_COST_SHIFT;
-
-         if (lmhi > PNG_HIMASK)
-            lmins = PNG_MAXSUM;
-
-         else
-            lmins = (lmhi << PNG_HISHIFT) + lmlo;
-      }
-#endif
-
-      for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
-          pp = prev_row + 1; i < bpp; i++)
-      {
-         v = *dp++ = (png_byte)((int)*rp++ - (int)*pp++);
+      png_size_t sum;
+      png_size_t lmins = mins;
 
-         sum += (v < 128) ? v : 256 - v;
-      }
-
-      for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
-      {
-         int a, b, c, pa, pb, pc, p;
+      sum = png_setup_paeth_row(png_ptr, bpp, row_bytes, lmins);
 
-         b = *pp++;
-         c = *cp++;
-         a = *lp++;
-
-#ifndef PNG_SLOW_PAETH
-         p = b - c;
-         pc = a - c;
-#ifdef PNG_USE_ABS
-         pa = abs(p);
-         pb = abs(pc);
-         pc = abs(p + pc);
-#else
-         pa = p < 0 ? -p : p;
-         pb = pc < 0 ? -pc : pc;
-         pc = (p + pc) < 0 ? -(p + pc) : p + pc;
-#endif
-         p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
-#else /* SLOW_PAETH */
-         p = a + b - c;
-         pa = abs(p - a);
-         pb = abs(p - b);
-         pc = abs(p - c);
-
-         if (pa <= pb && pa <= pc)
-            p = a;
-
-         else if (pb <= pc)
-            p = b;
-
-         else
-            p = c;
-#endif /* SLOW_PAETH */
-
-         v = *dp++ = (png_byte)((int)*rp++ - p);
-
-         sum += (v < 128) ? v : 256 - v;
-
-         if (sum > lmins)  /* We are already worse, don't continue. */
-            break;
-      }
-
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-      if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
+      if (sum < mins)
       {
-         int j;
-         png_uint_32 sumhi, sumlo;
-         sumlo = sum & PNG_LOMASK;
-         sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
-
-         for (j = 0; j < num_p_filters; j++)
+         best_row = png_ptr->try_row;
+         if (png_ptr->tst_row != NULL)
          {
-            if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
-            {
-               sumlo = (sumlo * png_ptr->filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-
-               sumhi = (sumhi * png_ptr->filter_weights[j]) >>
-                   PNG_WEIGHT_SHIFT;
-            }
+            png_ptr->try_row = png_ptr->tst_row;
+            png_ptr->tst_row = best_row;
          }
-
-         sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
-             PNG_COST_SHIFT;
-
-         sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
-             PNG_COST_SHIFT;
-
-         if (sumhi > PNG_HIMASK)
-            sum = PNG_MAXSUM;
-
-         else
-            sum = (sumhi << PNG_HISHIFT) + sumlo;
-      }
-#endif
-
-      if (sum < mins)
-      {
-         best_row = png_ptr->paeth_row;
       }
    }
-#endif /* WRITE_FILTER */
 
    /* Do the actual writing of the filtered row data from the chosen filter. */
    png_write_filtered_row(png_ptr, best_row, row_info->rowbytes+1);
 
-#ifdef PNG_WRITE_FILTER_SUPPORTED
-#ifdef PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
-   /* Save the type of filter we picked this time for future calculations */
-   if (png_ptr->num_prev_filters > 0)
-   {
-      int j;
-
-      for (j = 1; j < num_p_filters; j++)
-      {
-         png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
-      }
-
-      png_ptr->prev_filters[j] = best_row[0];
-   }
-#endif
 #endif /* WRITE_FILTER */
 }
 
diff --git a/src/3rdparty/libpng/qtpatches.diff b/src/3rdparty/libpng/qtpatches.diff
index 1fb9b3f0c06277d8ef56ed7886ade5449688d09f..82ee104545570c173f37bcd40ef30bf03cc4aa9f 100644
--- a/src/3rdparty/libpng/qtpatches.diff
+++ b/src/3rdparty/libpng/qtpatches.diff
@@ -1,34 +1,5 @@
-diff --git a/src/3rdparty/libpng/pnglibconf.h b/src/3rdparty/libpng/pnglibconf.h
-index b4ec3c3..f0fdcf8 100644
---- a/src/3rdparty/libpng/pnglibconf.h
-+++ b/src/3rdparty/libpng/pnglibconf.h
-@@ -27,7 +27,9 @@
- #define PNG_CHECK_FOR_INVALID_INDEX_SUPPORTED
- #define PNG_COLORSPACE_SUPPORTED
- #define PNG_CONSOLE_IO_SUPPORTED
-+#ifndef _WIN32_WCE
- #define PNG_CONVERT_tIME_SUPPORTED
-+#endif
- #define PNG_EASY_ACCESS_SUPPORTED
- /*#undef PNG_ERROR_NUMBERS_SUPPORTED*/
- #define PNG_ERROR_TEXT_SUPPORTED
-@@ -106,12 +108,14 @@
- #define PNG_SET_OPTION_SUPPORTED
- #define PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
- #define PNG_SET_USER_LIMITS_SUPPORTED
-+#ifndef _WIN32_WCE
- #define PNG_SIMPLIFIED_READ_AFIRST_SUPPORTED
- #define PNG_SIMPLIFIED_READ_BGR_SUPPORTED
- #define PNG_SIMPLIFIED_READ_SUPPORTED
- #define PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED
- #define PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED
- #define PNG_SIMPLIFIED_WRITE_SUPPORTED
-+#endif
- #define PNG_STDIO_SUPPORTED
- #define PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
- #define PNG_TEXT_SUPPORTED
 diff --git a/src/3rdparty/libpng/pngpriv.h b/src/3rdparty/libpng/pngpriv.h
-index 5980a3f..7185444 100644
+index c466d4b..f7a4547 100644
 --- a/src/3rdparty/libpng/pngpriv.h
 +++ b/src/3rdparty/libpng/pngpriv.h
 @@ -23,6 +23,12 @@
@@ -44,7 +15,7 @@ index 5980a3f..7185444 100644
  /* Feature Test Macros.  The following are defined here to ensure that correctly
   * implemented libraries reveal the APIs libpng needs to build and hide those
   * that are not needed and potentially damaging to the compilation.
-@@ -215,6 +221,11 @@
+@@ -219,6 +225,11 @@
  #  endif
  #endif /* Setting PNG_BUILD_DLL if required */
  
@@ -56,7 +27,7 @@ index 5980a3f..7185444 100644
  /* See pngconf.h for more details: the builder of the library may set this on
   * the command line to the right thing for the specific compilation system or it
   * may be automagically set above (at present we know of no system where it does
-@@ -426,6 +437,9 @@
+@@ -447,6 +458,9 @@
  #if defined(WIN32) || defined(_Windows) || defined(_WINDOWS) || \
      defined(_WIN32) || defined(__WIN32__)
  #  include <windows.h>  /* defines _WINDOWS_ macro */
@@ -66,7 +37,7 @@ index 5980a3f..7185444 100644
  #endif
  #endif /* PNG_VERSION_INFO_ONLY */
  
-@@ -436,7 +450,7 @@
+@@ -457,7 +471,7 @@
  
  /* Memory model/platform independent fns */
  #ifndef PNG_ABORT
diff --git a/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java b/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
index dd5a7b4fec0a5169172244cd33cc55cdc6ad1bc6..ac77de0babed8b7904014753c98b7abdcf53fb22 100644
--- a/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
+++ b/src/android/jar/src/org/qtproject/qt5/android/QtActivityDelegate.java
@@ -42,6 +42,7 @@ import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.res.Configuration;
 import android.graphics.drawable.ColorDrawable;
+import android.graphics.Rect;
 import android.net.LocalServerSocket;
 import android.net.LocalSocket;
 import android.os.Build;
@@ -67,7 +68,6 @@ import android.view.ViewGroup;
 import android.view.WindowManager;
 import android.view.inputmethod.InputMethodManager;
 import android.view.ViewTreeObserver;
-import android.graphics.Rect;
 
 import java.io.BufferedReader;
 import java.io.DataOutputStream;
@@ -125,6 +125,9 @@ public class QtActivityDelegate
     private boolean m_keyboardIsVisible = false;
     public boolean m_backKeyPressedSent = false;
     private long m_showHideTimeStamp = System.nanoTime();
+    private int m_portraitKeyboardHeight = 0;
+    private int m_landscapeKeyboardHeight = 0;
+    private int m_probeKeyboardHeightDelay = 50; // ms
 
     public void setFullScreen(boolean enterFullScreen)
     {
@@ -247,19 +250,26 @@ public class QtActivityDelegate
         }, 5);
     }
 
-    public void showSoftwareKeyboard(int x, int y, int width, int height, int inputHints, int enterKeyType)
+    public void showSoftwareKeyboard(final int x, final int y, final int width, final int height, final int inputHints, final int enterKeyType)
     {
         if (m_imm == null)
             return;
 
+        DisplayMetrics metrics = new DisplayMetrics();
+        m_activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
+
+        // If the screen is in portrait mode than we estimate that keyboard height will not be higher than 2/5 of the screen.
+        // else than we estimate that keyboard height will not be higher than 2/3 of the screen
+        final int visibleHeight;
+        if (metrics.widthPixels < metrics.heightPixels)
+            visibleHeight = m_portraitKeyboardHeight != 0 ? m_portraitKeyboardHeight : metrics.heightPixels * 3 / 5;
+        else
+            visibleHeight = m_landscapeKeyboardHeight != 0 ? m_landscapeKeyboardHeight : metrics.heightPixels / 3;
+
         if (m_softInputMode != 0) {
             m_activity.getWindow().setSoftInputMode(m_softInputMode);
-            // softInputIsHidden is true if SOFT_INPUT_STATE_HIDDEN or SOFT_INPUT_STATE_ALWAYS_HIDDEN is set.
-            final boolean softInputIsHidden = (m_softInputMode & WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) != 0;
-            if (softInputIsHidden)
-               return;
         } else {
-            if (height > m_layout.getHeight() * 2 / 3)
+            if (height > visibleHeight)
                 m_activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
             else
                 m_activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
@@ -366,6 +376,38 @@ public class QtActivityDelegate
                                 //FALLTHROUGH
                             case InputMethodManager.RESULT_UNCHANGED_SHOWN:
                                 setKeyboardVisibility(true, System.nanoTime());
+                                if (m_softInputMode == 0) {
+                                    // probe for real keyboard height
+                                    m_layout.postDelayed(new Runnable() {
+                                            @Override
+                                            public void run() {
+                                                if (!m_keyboardIsVisible)
+                                                    return;
+                                                DisplayMetrics metrics = new DisplayMetrics();
+                                                m_activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
+                                                Rect r = new Rect();
+                                                m_activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
+                                                if (metrics.heightPixels != r.bottom) {
+                                                    if (metrics.widthPixels > metrics.heightPixels) { // landscape
+                                                        if (m_landscapeKeyboardHeight != r.bottom) {
+                                                            m_landscapeKeyboardHeight = r.bottom;
+                                                            showSoftwareKeyboard(x, y, width, height, inputHints, enterKeyType);
+                                                        }
+                                                    } else {
+                                                        if (m_portraitKeyboardHeight != r.bottom) {
+                                                            m_portraitKeyboardHeight = r.bottom;
+                                                            showSoftwareKeyboard(x, y, width, height, inputHints, enterKeyType);
+                                                        }
+                                                    }
+                                                } else {
+                                                    // no luck ?
+                                                    // maybe the delay was too short, so let's make it longer
+                                                    if (m_probeKeyboardHeightDelay < 1000)
+                                                        m_probeKeyboardHeightDelay *= 2;
+                                                }
+                                            }
+                                        }, m_probeKeyboardHeightDelay);
+                                    }
                                 break;
                             case InputMethodManager.RESULT_HIDDEN:
                             case InputMethodManager.RESULT_UNCHANGED_HIDDEN:
diff --git a/src/android/jar/src/org/qtproject/qt5/android/QtNative.java b/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
index 2349ea6db1003e25372ece17ee60f8f743ef56ef..14da281a76fa042813acf2392ea5c84afdbda33a 100644
--- a/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
+++ b/src/android/jar/src/org/qtproject/qt5/android/QtNative.java
@@ -214,6 +214,16 @@ public class QtNative
         });
     }
 
+    private static void setViewVisibility(final View view, final boolean visible)
+    {
+        runAction(new Runnable() {
+            @Override
+            public void run() {
+                view.setVisibility(visible ? View.VISIBLE : View.GONE);
+            }
+        });
+    }
+
     public static boolean startApplication(String params,
                                            String environment,
                                            String mainLibrary,
diff --git a/src/android/java/src/org/qtproject/qt5/android/bindings/QtActivity.java b/src/android/java/src/org/qtproject/qt5/android/bindings/QtActivity.java
index 146d6b34f28e1b87ab2d4efa5ebac3ba227736df..f370b4f66792ff49ef74df81fcf50d5604f2fb80 100644
--- a/src/android/java/src/org/qtproject/qt5/android/bindings/QtActivity.java
+++ b/src/android/java/src/org/qtproject/qt5/android/bindings/QtActivity.java
@@ -454,7 +454,7 @@ public class QtActivity extends Activity
     {
         ArrayList<String> libs = new ArrayList<String>();
 
-        String dataDir = getApplicationInfo().dataDir + "/";
+        String libsDir = getApplicationInfo().nativeLibraryDir + "/";
 
         long packageVersion = -1;
         try {
@@ -489,7 +489,7 @@ public class QtActivity extends Activity
 
                 for (String bundledImportBinary : list) {
                     String[] split = bundledImportBinary.split(":");
-                    String sourceFileName = dataDir + "lib/" + split[0];
+                    String sourceFileName = libsDir + split[0];
                     String destinationFileName = pluginsPrefix + split[1];
                     createBundledBinary(sourceFileName, destinationFileName);
                 }
diff --git a/src/concurrent/qtconcurrentiteratekernel.cpp b/src/concurrent/qtconcurrentiteratekernel.cpp
index 70fa7209b4d854cef4ab5fa6a49353bf8df6e696..ea7737bd67ad7936300c408dc12cc055b63c25f1 100644
--- a/src/concurrent/qtconcurrentiteratekernel.cpp
+++ b/src/concurrent/qtconcurrentiteratekernel.cpp
@@ -190,6 +190,58 @@ int BlockSizeManager::blockSize()
     return m_blockSize;
 }
 
+/*! \internal
+
+*/
+BlockSizeManagerV2::BlockSizeManagerV2(int iterationCount)
+    : maxBlockSize(iterationCount / (QThreadPool::globalInstance()->maxThreadCount() * 2)),
+      beforeUser(0), afterUser(0),
+      m_blockSize(1)
+{ }
+
+// Records the time before user code.
+void BlockSizeManagerV2::timeBeforeUser()
+{
+    if (blockSizeMaxed())
+        return;
+
+    beforeUser = getticks();
+    controlPartElapsed.addValue(elapsed(beforeUser, afterUser));
+}
+
+ // Records the time after user code and adjust the block size if we are spending
+ // to much time in the for control code compared with the user code.
+void BlockSizeManagerV2::timeAfterUser()
+{
+    if (blockSizeMaxed())
+        return;
+
+    afterUser = getticks();
+    userPartElapsed.addValue(elapsed(afterUser, beforeUser));
+
+    if (controlPartElapsed.isMedianValid() == false)
+        return;
+
+    if (controlPartElapsed.median() * TargetRatio < userPartElapsed.median())
+        return;
+
+    m_blockSize = qMin(m_blockSize * 2,  maxBlockSize);
+
+#ifdef QTCONCURRENT_FOR_DEBUG
+    qDebug() << QThread::currentThread() << "adjusting block size" << controlPartElapsed.median() << userPartElapsed.median() << m_blockSize;
+#endif
+
+    // Reset the medians after adjusting the block size so we get
+    // new measurements with the new block size.
+    controlPartElapsed.reset();
+    userPartElapsed.reset();
+}
+
+int BlockSizeManagerV2::blockSize()
+{
+    return m_blockSize;
+}
+
 } // namespace QtConcurrent
 
 QT_END_NAMESPACE
diff --git a/src/concurrent/qtconcurrentiteratekernel.h b/src/concurrent/qtconcurrentiteratekernel.h
index 32acf03338163db4a73fc3de03cd46335de8dc24..40e2c6c115e534e51cafc724479003f34ee6470a 100644
--- a/src/concurrent/qtconcurrentiteratekernel.h
+++ b/src/concurrent/qtconcurrentiteratekernel.h
@@ -82,6 +82,32 @@ private:
     Q_DISABLE_COPY(BlockSizeManager)
 };
 
+// ### Qt6: Replace BlockSizeManager with V2 implementation
+class Q_CONCURRENT_EXPORT BlockSizeManagerV2
+{
+public:
+    explicit BlockSizeManagerV2(int iterationCount);
+
+    void timeBeforeUser();
+    void timeAfterUser();
+    int blockSize();
+
+private:
+    inline bool blockSizeMaxed()
+    {
+        return (m_blockSize >= maxBlockSize);
+    }
+
+    const int maxBlockSize;
+    qint64 beforeUser;
+    qint64 afterUser;
+    MedianDouble controlPartElapsed;
+    MedianDouble userPartElapsed;
+    int m_blockSize;
+
+    Q_DISABLE_COPY(BlockSizeManagerV2)
+};
+
 template <typename T>
 class ResultReporter
 {
@@ -190,7 +216,7 @@ public:
 
     ThreadFunctionResult forThreadFunction()
     {
-        BlockSizeManager blockSizeManager(iterationCount);
+        BlockSizeManagerV2 blockSizeManager(iterationCount);
         ResultReporter<T> resultReporter(this);
 
         for(;;) {
diff --git a/src/concurrent/qtconcurrentmedian.h b/src/concurrent/qtconcurrentmedian.h
index 2ae7954b7a276a3a3e00b5228688bfe200c846d4..e35e2aec70c2a88b8f3945ce4ad82c61d93458e0 100644
--- a/src/concurrent/qtconcurrentmedian.h
+++ b/src/concurrent/qtconcurrentmedian.h
@@ -121,6 +121,72 @@ private:
     bool dirty;
 };
 
+// ### Qt6: Drop Median<double> in favor of this faster MedianDouble
+class MedianDouble
+{
+public:
+    enum { BufferSize = 7 };
+
+    MedianDouble()
+        : currentMedian(), currentIndex(0), valid(false), dirty(true)
+    {
+    }
+
+    void reset()
+    {
+        std::fill_n(values, static_cast<int>(BufferSize), 0.0);
+        currentIndex = 0;
+        valid = false;
+        dirty = true;
+    }
+
+    void addValue(double value)
+    {
+        ++currentIndex;
+        if (currentIndex == BufferSize) {
+            currentIndex = 0;
+            valid = true;
+        }
+
+        // Only update the cached median value when we have to, that
+        // is when the new value is on then other side of the median
+        // compared to the current value at the index.
+        const double currentIndexValue = values[currentIndex];
+        if ((currentIndexValue > currentMedian && currentMedian > value)
+            || (currentMedian > currentIndexValue && value > currentMedian)) {
+            dirty = true;
+        }
+
+        values[currentIndex] = value;
+    }
+
+    bool isMedianValid() const
+    {
+        return valid;
+    }
+
+    double median()
+    {
+        if (dirty) {
+            dirty = false;
+
+            double sorted[BufferSize];
+            ::memcpy(&sorted, &values, sizeof(sorted));
+            std::sort(sorted, sorted + static_cast<int>(BufferSize));
+            currentMedian = sorted[BufferSize / 2];
+        }
+
+        return currentMedian;
+    }
+
+private:
+    double values[BufferSize];
+    double currentMedian;
+    int currentIndex;
+    bool valid;
+    bool dirty;
+};
+
 } // namespace QtConcurrent
 
 #endif //Q_QDOC
diff --git a/src/corelib/codecs/qutfcodec.cpp b/src/corelib/codecs/qutfcodec.cpp
index a64b3d167e80a40e83392c916cb6141509260491..476990fb7af110b933a34e1b2c83312fe560920b 100644
--- a/src/corelib/codecs/qutfcodec.cpp
+++ b/src/corelib/codecs/qutfcodec.cpp
@@ -363,6 +363,7 @@ QString QUtf8::convertToUnicode(const char *chars, int len, QTextCodec::Converte
     // main body, stateless decoding
     res = 0;
     const uchar *nextAscii = src;
+    const uchar *start = src;
     while (res >= 0 && src < end) {
         if (src >= nextAscii && simdDecodeAscii(dst, nextAscii, src, end))
             break;
@@ -371,9 +372,11 @@ QString QUtf8::convertToUnicode(const char *chars, int len, QTextCodec::Converte
         res = QUtf8Functions::fromUtf8<QUtf8BaseTraits>(ch, dst, src, end);
         if (!headerdone && res >= 0) {
             headerdone = true;
-            // eat the UTF-8 BOM
-            if (dst[-1] == 0xfeff)
-                --dst;
+            if (src == start + 3) { // 3 == sizeof(utf8-bom)
+                // eat the UTF-8 BOM (it can only appear at the beginning of the string).
+                if (dst[-1] == 0xfeff)
+                    --dst;
+            }
         }
         if (res == QUtf8BaseTraits::Error) {
             res = 0;
diff --git a/src/corelib/doc/snippets/code/doc_src_containers.cpp b/src/corelib/doc/snippets/code/doc_src_containers.cpp
index 395e48bc893d101bda6dc16d3936070a59782f8d..5b0d82936756f01534c2a24b034ba0a6098bef30 100644
--- a/src/corelib/doc/snippets/code/doc_src_containers.cpp
+++ b/src/corelib/doc/snippets/code/doc_src_containers.cpp
@@ -156,10 +156,9 @@ for (i = list.begin(); i != list.end(); ++i)
 QList<QString> list;
 list << "A" << "B" << "C" << "D";
 
-QList<QString>::iterator i = list.end();
-while (i != list.begin()) {
-    --i;
-    *i = (*i).toLower();
+QList<QString>::reverse_iterator i;
+for (i = list.rbegin(); i != list.rend(); ++i)
+    *i = i->toLower();
 }
 //! [11]
 
diff --git a/src/corelib/doc/src/containers.qdoc b/src/corelib/doc/src/containers.qdoc
index 0ae3817ac742b11cc4a951393859d7cda6ae1b07..988f72894611ba455fe430e12c3b27cf7ed0772c 100644
--- a/src/corelib/doc/src/containers.qdoc
+++ b/src/corelib/doc/src/containers.qdoc
@@ -472,9 +472,7 @@
 
     \image stliterators1.png
 
-    Iterating backward with an STL-style iterator requires us to
-    decrement the iterator \e before we access the item. This
-    requires a \c while loop:
+    Iterating backward with an STL-style iterator is done with reverse iterators:
 
     \snippet code/doc_src_containers.cpp 11
 
diff --git a/src/corelib/global/qcompilerdetection.h b/src/corelib/global/qcompilerdetection.h
index ba830977adc658fd3d8f34a250187d4577892e6c..b11237dce54f613c9a2b963dc5132bcb2e0d03d6 100644
--- a/src/corelib/global/qcompilerdetection.h
+++ b/src/corelib/global/qcompilerdetection.h
@@ -931,8 +931,8 @@
 // Older versions (QNX 650) do not support C++11 features
 // _HAS_* macros are set to 1 by toolchains that actually include
 // Dinkum C++11 libcpp.
-#  if !__GLIBCXX__
-#   if !_HAS_CPP0X
+#  if !defined(__GLIBCXX__)
+#   if !defined(_HAS_CPP0X) || !_HAS_CPP0X
 // Disable C++11 features that depend on library support
 #    undef Q_COMPILER_INITIALIZER_LISTS
 #    undef Q_COMPILER_RVALUE_REFS
@@ -940,10 +940,10 @@
 #    undef Q_COMPILER_UNICODE_STRINGS
 #    undef Q_COMPILER_NOEXCEPT
 #   endif // !_HAS_CPP0X
-#   if !_HAS_NULLPTR_T
+#   if !defined(_HAS_NULLPTR_T) || !_HAS_NULLPTR_T
 #    undef Q_COMPILER_NULLPTR
 #   endif //!_HAS_NULLPTR_T
-#   if !_HAS_CONSTEXPR
+#   if !defined(_HAS_CONSTEXPR) || !_HAS_CONSTEXPR
 // The libcpp is missing constexpr keywords on important functions like std::numeric_limits<>::min()
 // Disable constexpr support on QNX even if the compiler supports it
 #    undef Q_COMPILER_CONSTEXPR
diff --git a/src/corelib/global/qversiontagging.h b/src/corelib/global/qversiontagging.h
index 4a1c01c89dd2591bc0b4d5cc0a15ddd123ea9da3..d6b4a656003e0d0688db826dc44b314465da7ed6 100644
--- a/src/corelib/global/qversiontagging.h
+++ b/src/corelib/global/qversiontagging.h
@@ -46,7 +46,7 @@ QT_BEGIN_NAMESPACE
  * qt_version_tag symbol that is present in QtCore. Such symbol is versioned,
  * so the linker will automatically pull the current Qt version and add it to
  * the ELF header of the library/application. The assembly produces one section
- * called ".qtversion" containing two pointer-sized values. The first is a
+ * called ".qtversion" containing two 32-bit values. The first is a
  * relocation to the qt_version_tag symbol (which is what causes the ELF
  * version to get used). The second value is the current Qt version at the time
  * of compilation.
@@ -58,10 +58,12 @@ QT_BEGIN_NAMESPACE
 // don't make tags in QtCore, bootstrapped systems or if the user asked not to
 #elif defined(Q_CC_GNU) && !defined(Q_OS_ANDROID)
 #  if defined(Q_PROCESSOR_X86) && (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD_KERNEL))
-#    ifdef __LP64__
-#      define QT_VERSION_TAG_RELOC(sym) ".quad " QT_STRINGIFY(QT_MANGLE_NAMESPACE(sym)) "@GOTPCREL\n"
-#    elif defined(Q_PROCESSOR_X86_64)   // x32
-#      define QT_VERSION_TAG_RELOC(sym) ".long " QT_STRINGIFY(QT_MANGLE_NAMESPACE(sym)) "@GOTPCREL\n"
+#    if defined(Q_PROCESSOR_X86_64)   // x86-64 or x32
+#      if defined(__code_model_large__)
+#        define QT_VERSION_TAG_RELOC(sym) ".quad " QT_STRINGIFY(QT_MANGLE_NAMESPACE(sym)) "@GOT\n"
+#      else
+#        define QT_VERSION_TAG_RELOC(sym) ".long " QT_STRINGIFY(QT_MANGLE_NAMESPACE(sym)) "@GOTPCREL\n"
+#      endif
 #    else                               // x86
 #      define QT_VERSION_TAG_RELOC(sym) ".long " QT_STRINGIFY(QT_MANGLE_NAMESPACE(sym)) "@GOT\n"
 #    endif
diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp
index 4d2b36632f5f41d348eb465c23365ec0d1931a7e..2c2bdd579eb5498298ab2c9ef7681aa3c49db2ec 100644
--- a/src/corelib/io/qdir.cpp
+++ b/src/corelib/io/qdir.cpp
@@ -152,7 +152,11 @@ inline void QDirPrivate::setPath(const QString &path)
     if (p.endsWith(QLatin1Char('/'))
             && p.length() > 1
 #if defined(Q_OS_WIN)
+#  if defined (Q_OS_WINRT)
+        && (!(p.toLower() == QDir::rootPath().toLower()))
+#  else
         && (!(p.length() == 3 && p.at(1).unicode() == ':' && p.at(0).isLetter()))
+#  endif
 #endif
     ) {
             p.truncate(p.length() - 1);
@@ -885,6 +889,9 @@ bool QDir::cd(const QString &dirName)
 #if defined (Q_OS_UNIX)
             //After cleanPath() if path is "/.." or starts with "/../" it means trying to cd above root.
             if (newPath.startsWith(QLatin1String("/../")) || newPath == QLatin1String("/.."))
+#elif defined (Q_OS_WINRT)
+            const QString rootPath = QDir::rootPath();
+            if (newPath.size() < rootPath.size() && rootPath.startsWith(newPath))
 #else
             /*
               cleanPath() already took care of replacing '\' with '/'.
@@ -2187,7 +2194,11 @@ QString QDir::cleanPath(const QString &path)
     // Strip away last slash except for root directories
     if (ret.length() > 1 && ret.endsWith(QLatin1Char('/'))) {
 #if defined (Q_OS_WIN)
+#  if defined(Q_OS_WINRT)
+        if (!((ret.length() == 3 || ret.length() == QDir::rootPath().length()) && ret.at(1) == QLatin1Char(':')))
+#  else
         if (!(ret.length() == 3 && ret.at(1) == QLatin1Char(':')))
+#  endif
 #endif
             ret.chop(1);
     }
diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp
index ce1684a943e107a73387751637a96b88146f6c43..4474fd3f52a489d9a209902d49ba373c5507792b 100644
--- a/src/corelib/io/qfile.cpp
+++ b/src/corelib/io/qfile.cpp
@@ -747,7 +747,7 @@ QFile::copy(const QString &newName)
         qWarning("QFile::copy: Empty or null file name");
         return false;
     }
-    if (QFile(newName).exists()) {
+    if (QFile::exists(newName)) {
         // ### Race condition. If a file is moved in after this, it /will/ be
         // overwritten. On Unix, the proper solution is to use hardlinks:
         // return ::link(old, new) && ::remove(old); See also rename().
diff --git a/src/corelib/io/qfiledevice.cpp b/src/corelib/io/qfiledevice.cpp
index 4c5ed0aef6619c94b0e7ca2e353a29c07bca5514..8531d325234d9c021ef43e9664974d0d0dcd20b0 100644
--- a/src/corelib/io/qfiledevice.cpp
+++ b/src/corelib/io/qfiledevice.cpp
@@ -560,7 +560,7 @@ qint64 QFileDevice::writeData(const char *data, qint64 len)
     char *writePointer = d->writeBuffer.reserve(len);
     if (len == 1)
         *writePointer = *data;
-    else
+    else if (len)
         ::memcpy(writePointer, data, len);
     return len;
 }
diff --git a/src/corelib/io/qfileinfo.cpp b/src/corelib/io/qfileinfo.cpp
index 51b39b1114f05b1bc7644fa2ba185f2ad773f858..dd194594c92b5759910c7e24cd00579e9068be6d 100644
--- a/src/corelib/io/qfileinfo.cpp
+++ b/src/corelib/io/qfileinfo.cpp
@@ -1095,7 +1095,7 @@ bool QFileInfo::isRoot() const
         return true;
     if (d->fileEngine == 0) {
         if (d->fileEntry.isRoot()) {
-#if defined(Q_OS_WIN)
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
             //the path is a drive root, but the drive may not exist
             //for backward compatibility, return true only if the drive exists
             if (!d->cache_enabled || !d->metaData.hasFlags(QFileSystemMetaData::ExistsAttribute))
diff --git a/src/corelib/io/qfileselector.cpp b/src/corelib/io/qfileselector.cpp
index 85d9b0bfcbaf543ae0d40230f5f9343232d27417..52ac414645115e300295283e8c8b8318ebc15ecf 100644
--- a/src/corelib/io/qfileselector.cpp
+++ b/src/corelib/io/qfileselector.cpp
@@ -227,9 +227,9 @@ QString QFileSelector::select(const QString &filePath) const
 
 static bool isLocalScheme(const QString &file)
 {
-    bool local = file == QStringLiteral("qrc");
+    bool local = file == QLatin1String("qrc");
 #ifdef Q_OS_ANDROID
-    local |= file == QStringLiteral("assets");
+    local |= file == QLatin1String("assets");
 #endif
     return local;
 }
@@ -248,9 +248,16 @@ QUrl QFileSelector::select(const QUrl &filePath) const
         return filePath;
     QUrl ret(filePath);
     if (isLocalScheme(filePath.scheme())) {
-        QString equivalentPath = QLatin1Char(':') + filePath.path();
+        QLatin1String scheme(":");
+#ifdef Q_OS_ANDROID
+        // use other scheme because ":" means "qrc" here
+        if (filePath.scheme() == QLatin1String("assets"))
+            scheme = QLatin1String("assets:");
+#endif
+
+        QString equivalentPath = scheme + filePath.path();
         QString selectedPath = d->select(equivalentPath);
-        ret.setPath(selectedPath.remove(0, 1));
+        ret.setPath(selectedPath.remove(0, scheme.size()));
     } else {
         ret = QUrl::fromLocalFile(d->select(ret.toLocalFile()));
     }
diff --git a/src/corelib/io/qfilesystemengine_win.cpp b/src/corelib/io/qfilesystemengine_win.cpp
index 379095a83da6b5fd2dd4fe9dd6e5be8ee78308f7..f1a60190943474680f11e51a9aec871c916792d9 100644
--- a/src/corelib/io/qfilesystemengine_win.cpp
+++ b/src/corelib/io/qfilesystemengine_win.cpp
@@ -78,6 +78,11 @@ using namespace Microsoft::WRL::Wrappers;
 using namespace ABI::Windows::Foundation;
 using namespace ABI::Windows::Storage;
 using namespace ABI::Windows::ApplicationModel;
+
+#if _MSC_VER < 1900
+#define Q_OS_WINRT_WIN81
+#endif
+
 #endif // Q_OS_WINRT
 
 #ifndef SPI_GETPLATFORMTYPE
@@ -522,7 +527,7 @@ QString QFileSystemEngine::nativeAbsoluteFilePath(const QString &path)
 {
     // can be //server or //server/share
     QString absPath;
-#if !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
+#if !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT_WIN81)
     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);
@@ -532,6 +537,16 @@ QString QFileSystemEngine::nativeAbsoluteFilePath(const QString &path)
     }
     if (retLen != 0)
         absPath = QString::fromWCharArray(buf.data(), retLen);
+#  if defined(Q_OS_WINRT)
+    // Win32 returns eg C:/ as root directory with a trailing /.
+    // WinRT returns the sandbox root without /.
+    // Also C:/../.. returns C:/ on Win32, while for WinRT it steps outside the package
+    // and goes beyond package root. Hence force the engine to stay inside
+    // the package.
+    const QString rootPath = QDir::toNativeSeparators(QDir::rootPath());
+    if (absPath.size() < rootPath.size() && rootPath.startsWith(absPath))
+        absPath = rootPath;
+#  endif // Q_OS_WINRT
 #elif !defined(Q_OS_WINCE)
     if (QDir::isRelativePath(path))
         absPath = QDir::toNativeSeparators(QDir::cleanPath(QDir::currentPath() + QLatin1Char('/') + path));
@@ -569,7 +584,7 @@ QFileSystemEntry QFileSystemEngine::absoluteName(const QFileSystemEntry &entry)
         ret = entry.filePath();
 #endif
     } else {
-#ifndef Q_OS_WINRT
+#ifndef Q_OS_WINRT_WIN81
         ret = QDir::cleanPath(QDir::currentPath() + QLatin1Char('/') + entry.filePath());
 #else
         // Some WinRT APIs do not support absolute paths (due to sandboxing).
@@ -1218,8 +1233,8 @@ QString QFileSystemEngine::rootPath()
     if (FAILED(item->get_Path(finalWinPath.GetAddressOf())))
         return ret;
 
-    ret = QDir::fromNativeSeparators(QString::fromWCharArray(finalWinPath.GetRawBuffer(nullptr)));
-
+    const QString qtWinPath = QDir::fromNativeSeparators(QString::fromWCharArray(finalWinPath.GetRawBuffer(nullptr)));
+    ret = qtWinPath.endsWith(QLatin1Char('/')) ? qtWinPath : qtWinPath + QLatin1Char('/');
 #else
     QString ret = QString::fromLatin1(qgetenv("SystemDrive"));
     if (ret.isEmpty())
@@ -1337,7 +1352,7 @@ bool QFileSystemEngine::setCurrentPath(const QFileSystemEntry &entry)
     if(!(meta.exists() && meta.isDirectory()))
         return false;
 
-#if !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
+#if !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT_WIN81)
     //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;
@@ -1350,7 +1365,7 @@ bool QFileSystemEngine::setCurrentPath(const QFileSystemEntry &entry)
 QFileSystemEntry QFileSystemEngine::currentPath()
 {
     QString ret;
-#if !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
+#if !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT_WIN81)
     DWORD size = 0;
     wchar_t currentName[PATH_MAX];
     size = ::GetCurrentDirectory(PATH_MAX, currentName);
@@ -1366,17 +1381,17 @@ QFileSystemEntry QFileSystemEngine::currentPath()
     }
     if (ret.length() >= 2 && ret[1] == QLatin1Char(':'))
         ret[0] = ret.at(0).toUpper(); // Force uppercase drive letters.
-#else // !Q_OS_WINCE && !Q_OS_WINRT
+#else // !Q_OS_WINCE && !Q_OS_WINRT_WIN81
     //TODO - a race condition exists when using currentPath / setCurrentPath from multiple threads
     if (qfsPrivateCurrentDir.isEmpty())
-#ifndef Q_OS_WINRT
+#ifndef Q_OS_WINRT_WIN81
         qfsPrivateCurrentDir = QCoreApplication::applicationDirPath();
 #else
         qfsPrivateCurrentDir = QDir::rootPath();
 #endif
 
     ret = qfsPrivateCurrentDir;
-#endif // Q_OS_WINCE || Q_OS_WINRT
+#endif // Q_OS_WINCE || Q_OS_WINRT_WIN81
     return QFileSystemEntry(ret, QFileSystemEntry::FromNativePath());
 }
 
diff --git a/src/corelib/io/qfilesystementry.cpp b/src/corelib/io/qfilesystementry.cpp
index 709970e3acc39545eea34d0c10b9921486951379..c590d81f7a292a01b2f48f752d8785ee1f40df13 100644
--- a/src/corelib/io/qfilesystementry.cpp
+++ b/src/corelib/io/qfilesystementry.cpp
@@ -166,6 +166,12 @@ void QFileSystemEntry::resolveNativeFilePath() const
             m_nativeFilePath.remove(0,1);
         if (m_nativeFilePath.isEmpty())
             m_nativeFilePath.append(QLatin1Char('.'));
+        // WinRT/MSVC2015 allows a maximum of 256 characters for a filepath
+        // unless //?/ is prepended which extends the rule to have a maximum
+        // of 256 characters in the filename plus the preprending path
+#if _MSC_VER >= 1900
+        m_nativeFilePath.prepend("\\\\?\\");
+#endif
 #endif
     }
 }
@@ -283,9 +289,13 @@ bool QFileSystemEntry::isAbsolute() const
 bool QFileSystemEntry::isDriveRoot() const
 {
     resolveFilePath();
+#ifndef Q_OS_WINRT
     return (m_filePath.length() == 3
            && m_filePath.at(0).isLetter() && m_filePath.at(1) == QLatin1Char(':')
            && m_filePath.at(2) == QLatin1Char('/'));
+#else // !Q_OS_WINRT
+    return m_filePath == QDir::rootPath();
+#endif // !Q_OS_WINRT
 }
 #endif
 
diff --git a/src/corelib/io/qfilesystemiterator_win.cpp b/src/corelib/io/qfilesystemiterator_win.cpp
index 6351a3559d717a5dbb1b0bc6e525c7ee1081e3cf..d7fed87222658e15c6a3a4fc3f5cbd849855a4ee 100644
--- a/src/corelib/io/qfilesystemiterator_win.cpp
+++ b/src/corelib/io/qfilesystemiterator_win.cpp
@@ -67,7 +67,8 @@ QFileSystemIterator::QFileSystemIterator(const QFileSystemEntry &entry, QDir::Fi
     if (!nativePath.endsWith(QLatin1Char('\\')))
         nativePath.append(QLatin1Char('\\'));
     nativePath.append(QLatin1Char('*'));
-#ifdef Q_OS_WINRT
+    // In MSVC2015+ case we prepend //?/ for longer file-name support
+#if defined(Q_OS_WINRT) && _MSC_VER < 1900
     if (nativePath.startsWith(QLatin1Char('\\')))
         nativePath.remove(0, 1);
 #endif
diff --git a/src/corelib/io/qfsfileengine.cpp b/src/corelib/io/qfsfileengine.cpp
index 429c40da1a9813f65f58e1e1602e510a59596a34..10e116a23aa9e9bcec59f9f0565436fe7f57debc 100644
--- a/src/corelib/io/qfsfileengine.cpp
+++ b/src/corelib/io/qfsfileengine.cpp
@@ -724,29 +724,33 @@ qint64 QFSFileEnginePrivate::writeFdFh(const char *data, qint64 len)
 
     qint64 writtenBytes = 0;
 
-    if (fh) {
-        // Buffered stdlib mode.
-
-        size_t result;
-        do {
-            result = fwrite(data + writtenBytes, 1, size_t(len - writtenBytes), fh);
-            writtenBytes += result;
-        } while (result == 0 ? errno == EINTR : writtenBytes < len);
+    if (len) { // avoid passing nullptr to fwrite() or QT_WRITE() (UB)
 
-    } else if (fd != -1) {
-        // Unbuffered stdio mode.
+        if (fh) {
+            // Buffered stdlib mode.
+
+            size_t result;
+            do {
+                result = fwrite(data + writtenBytes, 1, size_t(len - writtenBytes), fh);
+                writtenBytes += result;
+            } while (result == 0 ? errno == EINTR : writtenBytes < len);
+
+        } else if (fd != -1) {
+            // Unbuffered stdio mode.
+
+            SignedIOType result;
+            do {
+                // calculate the chunk size
+                // on Windows or 32-bit no-largefile Unix, we'll need to read in chunks
+                // we limit to the size of the signed type, otherwise we could get a negative number as a result
+                quint64 wantedBytes = quint64(len) - quint64(writtenBytes);
+                UnsignedIOType chunkSize = std::numeric_limits<SignedIOType>::max();
+                if (chunkSize > wantedBytes)
+                    chunkSize = wantedBytes;
+                result = QT_WRITE(fd, data + writtenBytes, chunkSize);
+            } while (result > 0 && (writtenBytes += result) < len);
+        }
 
-        SignedIOType result;
-        do {
-            // calculate the chunk size
-            // on Windows or 32-bit no-largefile Unix, we'll need to read in chunks
-            // we limit to the size of the signed type, otherwise we could get a negative number as a result
-            quint64 wantedBytes = quint64(len) - quint64(writtenBytes);
-            UnsignedIOType chunkSize = std::numeric_limits<SignedIOType>::max();
-            if (chunkSize > wantedBytes)
-                chunkSize = wantedBytes;
-            result = QT_WRITE(fd, data + writtenBytes, chunkSize);
-        } while (result > 0 && (writtenBytes += result) < len);
     }
 
     if (len &&  writtenBytes == 0) {
diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp
index cfd50955a6a8f3d6c3e630ef99acd2da72c05c5b..886d526fb17a714a8669e498aa71fd46ba87f9ed 100644
--- a/src/corelib/io/qfsfileengine_win.cpp
+++ b/src/corelib/io/qfsfileengine_win.cpp
@@ -1037,7 +1037,7 @@ uchar *QFSFileEnginePrivate::map(qint64 offset, qint64 size,
                                       offsetHi, offsetLo, size + extra);
 #else
     LPVOID mapAddress = ::MapViewOfFileFromApp(mapHandle, access,
-                                               (ULONG64(offsetHi) << 32) + offsetLo, size);
+                                               (ULONG64(offsetHi) << 32) + offsetLo, size + extra);
 #endif
     if (mapAddress) {
         uchar *address = extra + static_cast<uchar*>(mapAddress);
diff --git a/src/corelib/io/qiodevice_p.h b/src/corelib/io/qiodevice_p.h
index 56a89ab680ac52da218cf0207b2115c1e6dab162..6ab1de27e0424e6673beae6bb813a2467096f85b 100644
--- a/src/corelib/io/qiodevice_p.h
+++ b/src/corelib/io/qiodevice_p.h
@@ -102,14 +102,17 @@ public:
     }
     qint64 read(char* target, qint64 size) {
         qint64 r = qMin(size, len);
-        memcpy(target, first, r);
-        len -= r;
-        first += r;
+        if (r) {
+            memcpy(target, first, r);
+            len -= r;
+            first += r;
+        }
         return r;
     }
     qint64 peek(char* target, qint64 size) {
         qint64 r = qMin(size, len);
-        memcpy(target, first, r);
+        if (r)
+            memcpy(target, first, r);
         return r;
     }
     char* reserve(qint64 size) {
@@ -141,7 +144,7 @@ public:
         return r;
     }
     bool canReadLine() const {
-        return memchr(first, '\n', len);
+        return first && memchr(first, '\n', len);
     }
     void ungetChar(char c) {
         if (first == buf) {
@@ -172,7 +175,8 @@ private:
         if (newCapacity > capacity) {
             // allocate more space
             char* newBuf = new char[newCapacity];
-            memmove(newBuf + moveOffset, first, len);
+            if (first)
+                memmove(newBuf + moveOffset, first, len);
             delete [] buf;
             buf = newBuf;
             capacity = newCapacity;
diff --git a/src/corelib/io/qlockfile_p.h b/src/corelib/io/qlockfile_p.h
index 168062f4674f8a68d3b2b56c6e36972849c1cd9b..48b642abd021f75d2850c8b46f564b3433e449d8 100644
--- a/src/corelib/io/qlockfile_p.h
+++ b/src/corelib/io/qlockfile_p.h
@@ -78,7 +78,7 @@ public:
     static QString processNameByPid(qint64 pid);
 
 #ifdef Q_OS_UNIX
-    static int checkFcntlWorksAfterFlock();
+    static int checkFcntlWorksAfterFlock(const QString &fn);
 #endif
 
     QString fileName;
diff --git a/src/corelib/io/qlockfile_unix.cpp b/src/corelib/io/qlockfile_unix.cpp
index 365f3e07ab8ea2b80841eec8ccdf75a94fe3f4b4..623968b86976830d3a4b37a886b778666cf2fbb4 100644
--- a/src/corelib/io/qlockfile_unix.cpp
+++ b/src/corelib/io/qlockfile_unix.cpp
@@ -39,6 +39,10 @@
 #include "QtCore/qfileinfo.h"
 #include "QtCore/qdebug.h"
 #include "QtCore/qdatetime.h"
+#include "QtCore/qfileinfo.h"
+#include "QtCore/qcache.h"
+#include "QtCore/qglobalstatic.h"
+#include "QtCore/qmutex.h"
 
 #include "private/qcore_unix_p.h" // qt_safe_open
 #include "private/qabstractfileengine_p.h"
@@ -89,10 +93,10 @@ static qint64 qt_write_loop(int fd, const char *data, qint64 len)
     return pos;
 }
 
-int QLockFilePrivate::checkFcntlWorksAfterFlock()
+int QLockFilePrivate::checkFcntlWorksAfterFlock(const QString &fn)
 {
 #ifndef QT_NO_TEMPORARYFILE
-    QTemporaryFile file;
+    QTemporaryFile file(fn);
     if (!file.open())
         return 0;
     const int fd = file.d_func()->engine()->handle();
@@ -114,24 +118,34 @@ int QLockFilePrivate::checkFcntlWorksAfterFlock()
 #endif
 }
 
-static QBasicAtomicInt fcntlOK = Q_BASIC_ATOMIC_INITIALIZER(-1);
+// Cache the result of checkFcntlWorksAfterFlock for each directory a lock
+// file is created in because in some filesystems, like NFS, both locks
+// are the same.  This does not take into account a filesystem changing.
+// QCache is set to hold a maximum of 10 entries, this is to avoid unbounded
+// growth, this is caching directories of files and it is assumed a low number
+// will be sufficient.
+typedef QCache<QString, bool> CacheType;
+Q_GLOBAL_STATIC_WITH_ARGS(CacheType, fcntlOK, (10));
+static QBasicMutex fcntlLock;
 
 /*!
   \internal
   Checks that the OS isn't using POSIX locks to emulate flock().
   OS X is one of those.
 */
-static bool fcntlWorksAfterFlock()
+static bool fcntlWorksAfterFlock(const QString &fn)
 {
-    int value = fcntlOK.load();
-    if (Q_UNLIKELY(value == -1)) {
-        value = QLockFilePrivate::checkFcntlWorksAfterFlock();
-        fcntlOK.store(value);
+    QMutexLocker lock(&fcntlLock);
+    bool *worksPtr = fcntlOK->object(fn);
+    if (!worksPtr) {
+        worksPtr = new bool(QLockFilePrivate::checkFcntlWorksAfterFlock(fn));
+        fcntlOK->insert(fn, worksPtr);
     }
-    return value == 1;
+
+    return *worksPtr;
 }
 
-static bool setNativeLocks(int fd)
+static bool setNativeLocks(const QString &fileName, int fd)
 {
 #if defined(LOCK_EX) && defined(LOCK_NB)
     if (flock(fd, LOCK_EX | LOCK_NB) == -1) // other threads, and other processes on a local fs
@@ -143,8 +157,10 @@ static bool setNativeLocks(int fd)
     flockData.l_start = 0;
     flockData.l_len = 0; // 0 = entire file
     flockData.l_pid = getpid();
-    if (fcntlWorksAfterFlock() && fcntl(fd, F_SETLK, &flockData) == -1) // for networked filesystems
+    if (fcntlWorksAfterFlock(QDir::cleanPath(QFileInfo(fileName).absolutePath()) + QString('/'))
+        && fcntl(fd, F_SETLK, &flockData) == -1) { // for networked filesystems
         return false;
+    }
     return true;
 }
 
@@ -171,7 +187,7 @@ QLockFile::LockError QLockFilePrivate::tryLock_sys()
         }
     }
     // Ensure nobody else can delete the file while we have it
-    if (!setNativeLocks(fd)) {
+    if (!setNativeLocks(fileName, fd)) {
         const int errnoSaved = errno;
         qWarning() << "setNativeLocks failed:" << qt_error_string(errnoSaved);
     }
@@ -202,7 +218,7 @@ bool QLockFilePrivate::removeStaleLock()
     const int fd = qt_safe_open(lockFileName.constData(), O_WRONLY, 0644);
     if (fd < 0) // gone already?
         return false;
-    bool success = setNativeLocks(fd) && (::unlink(lockFileName) == 0);
+    bool success = setNativeLocks(fileName, fd) && (::unlink(lockFileName) == 0);
     close(fd);
     return success;
 }
diff --git a/src/corelib/io/qsettings.cpp b/src/corelib/io/qsettings.cpp
index 0c44582af8e02e415d4e21513b8c848789cadf76..1c7ceed3c19cefa89f695bbd29a1d1a73d5ffd84 100644
--- a/src/corelib/io/qsettings.cpp
+++ b/src/corelib/io/qsettings.cpp
@@ -1410,13 +1410,17 @@ void QConfFileSettingsPrivate::syncConfFile(int confFileNo)
         Concurrent read and write are not a problem because the writing operation is atomic.
     */
     QLockFile lockFile(confFile->name + QLatin1String(".lock"));
+#endif
     if (!readOnly) {
-        if (!confFile->isWritable() || !lockFile.lock() ) {
+        if (!confFile->isWritable()
+#ifndef QT_BOOTSTRAPPED
+            || !lockFile.lock()
+#endif
+            ) {
             setStatus(QSettings::AccessError);
             return;
         }
     }
-#endif
 
     /*
         We hold the lock. Let's reread the file if it has changed
diff --git a/src/corelib/io/qurl.cpp b/src/corelib/io/qurl.cpp
index 775a870a27175929df754462ac385ae355b004a4..b51119c7ad5283ee636b739fb4ea065e69f2e0d9 100644
--- a/src/corelib/io/qurl.cpp
+++ b/src/corelib/io/qurl.cpp
@@ -556,6 +556,7 @@ public:
     inline bool hasFragment() const { return sectionIsPresent & Fragment; }
 
     inline bool isLocalFile() const { return flags & IsLocalFile; }
+    QString toLocalFile(QUrl::FormattingOptions options) const;
 
     QString mergePaths(const QString &relativePath) const;
 
@@ -1460,6 +1461,33 @@ inline void QUrlPrivate::parse(const QString &url, QUrl::ParsingMode parsingMode
         validateComponent(Fragment, url, hash + 1, len);
 }
 
+QString QUrlPrivate::toLocalFile(QUrl::FormattingOptions options) const
+{
+    QString tmp;
+    QString ourPath;
+    appendPath(ourPath, options, QUrlPrivate::Path);
+
+    // magic for shared drive on windows
+    if (!host.isEmpty()) {
+        tmp = QStringLiteral("//") + host;
+#ifdef Q_OS_WIN // QTBUG-42346, WebDAV is visible as local file on Windows only.
+        if (scheme == webDavScheme())
+            tmp += webDavSslTag();
+#endif
+        if (!ourPath.isEmpty() && !ourPath.startsWith(QLatin1Char('/')))
+            tmp += QLatin1Char('/');
+        tmp += ourPath;
+    } else {
+        tmp = ourPath;
+#ifdef Q_OS_WIN
+        // magic for drives on windows
+        if (ourPath.length() > 2 && ourPath.at(0) == QLatin1Char('/') && ourPath.at(2) == QLatin1Char(':'))
+            tmp.remove(0, 1);
+#endif
+    }
+    return tmp;
+}
+
 /*
     From http://www.ietf.org/rfc/rfc3986.txt, 5.2.3: Merge paths
 
@@ -3257,7 +3285,7 @@ QString QUrl::toString(FormattingOptions options) const
             && (!d->hasQuery() || options.testFlag(QUrl::RemoveQuery))
             && (!d->hasFragment() || options.testFlag(QUrl::RemoveFragment))
             && isLocalFile()) {
-        return path(options);
+        return d->toLocalFile(options);
     }
 
     QString url;
@@ -3820,28 +3848,7 @@ QString QUrl::toLocalFile() const
     if (!isLocalFile())
         return QString();
 
-    QString tmp;
-    QString ourPath = path(QUrl::FullyDecoded);
-
-    // magic for shared drive on windows
-    if (!d->host.isEmpty()) {
-        tmp = QStringLiteral("//") + host();
-#ifdef Q_OS_WIN // QTBUG-42346, WebDAV is visible as local file on Windows only.
-        if (scheme() == webDavScheme())
-            tmp += webDavSslTag();
-#endif
-        if (!ourPath.isEmpty() && !ourPath.startsWith(QLatin1Char('/')))
-            tmp += QLatin1Char('/');
-        tmp += ourPath;
-    } else {
-        tmp = ourPath;
-#ifdef Q_OS_WIN
-        // magic for drives on windows
-        if (ourPath.length() > 2 && ourPath.at(0) == QLatin1Char('/') && ourPath.at(2) == QLatin1Char(':'))
-            tmp.remove(0, 1);
-#endif
-    }
-    return tmp;
+    return d->toLocalFile(QUrl::FullyDecoded);
 }
 
 /*!
diff --git a/src/corelib/io/qwinoverlappedionotifier.cpp b/src/corelib/io/qwinoverlappedionotifier.cpp
index c9de6671f7f6ff9fb727a9232198289abc796481..0cefa374fa840b6f3fb442c4474c776670076edc 100644
--- a/src/corelib/io/qwinoverlappedionotifier.cpp
+++ b/src/corelib/io/qwinoverlappedionotifier.cpp
@@ -364,7 +364,7 @@ bool QWinOverlappedIoNotifier::waitForNotified(int msecs, OVERLAPPED *overlapped
             return false;
         if (triggeredOverlapped == overlapped)
             return true;
-        msecs = qt_subtract_from_timeout(msecs, stopWatch.elapsed());
+        t = qt_subtract_from_timeout(msecs, stopWatch.elapsed());
         if (t == 0)
             return false;
     }
diff --git a/src/corelib/json/qjson_p.h b/src/corelib/json/qjson_p.h
index 35a16b0ef6b8a5cd777e1e4d9f3988787526c543..7f5a2d88a1fc75974927fb3015a339b9c1e18684 100644
--- a/src/corelib/json/qjson_p.h
+++ b/src/corelib/json/qjson_p.h
@@ -305,7 +305,7 @@ public:
     {
         d->length = str.length();
 #if Q_BYTE_ORDER == Q_BIG_ENDIAN
-        const qle_ushort *uc = (const qle_ushort *)str.unicode();
+        const ushort *uc = (const ushort *)str.unicode();
         for (int i = 0; i < str.length(); ++i)
             d->utf16[i] = uc[i];
 #else
diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp
index 5543d639b8ef8a13055596f3d20a199b9e3d49dc..8c62a49fafddefb5a7a2d6e1e1571c8cfef8bc3b 100644
--- a/src/corelib/kernel/qcoreapplication.cpp
+++ b/src/corelib/kernel/qcoreapplication.cpp
@@ -191,16 +191,18 @@ void QCoreApplicationPrivate::processCommandLineArguments()
 {
     int j = argc ? 1 : 0;
     for (int i = 1; i < argc; ++i) {
-        if (argv[i] && *argv[i] != '-') {
+        if (!argv[i])
+            continue;
+        if (*argv[i] != '-') {
             argv[j++] = argv[i];
             continue;
         }
-        QByteArray arg = argv[i];
-        if (arg.startsWith("--"))
-            arg.remove(0, 1);
-        if (arg.startsWith("-qmljsdebugger=")) {
-            qmljs_debug_arguments = QString::fromLocal8Bit(arg.right(arg.length() - 15));
-        } else if (arg == "-qmljsdebugger" && i < argc - 1) {
+        const char *arg = argv[i];
+        if (arg[1] == '-') // startsWith("--")
+            ++arg;
+        if (strncmp(arg, "-qmljsdebugger=", 15) == 0) {
+            qmljs_debug_arguments = QString::fromLocal8Bit(arg + 15);
+        } else if (strcmp(arg, "-qmljsdebugger") == 0 && i < argc - 1) {
             ++i;
             qmljs_debug_arguments = QString::fromLocal8Bit(argv[i]);
         } else {
diff --git a/src/corelib/kernel/qeventdispatcher_win.cpp b/src/corelib/kernel/qeventdispatcher_win.cpp
index bb091e9f6d39b0b9b1eff84e4082797bb9b55570..1a14500bd4259541854e951c1af1abccdbb0f401 100644
--- a/src/corelib/kernel/qeventdispatcher_win.cpp
+++ b/src/corelib/kernel/qeventdispatcher_win.cpp
@@ -78,6 +78,7 @@ extern uint qGlobalPostedEventsCount();
 enum {
     WM_QT_SOCKETNOTIFIER = WM_USER,
     WM_QT_SENDPOSTEDEVENTS = WM_USER + 1,
+    WM_QT_ACTIVATENOTIFIERS = WM_USER + 2,
     SendPostedEventsWindowsTimerId = ~1u
 };
 
@@ -308,7 +309,7 @@ static void resolveTimerAPI()
 QEventDispatcherWin32Private::QEventDispatcherWin32Private()
     : threadId(GetCurrentThreadId()), interrupt(false), closingDown(false), internalHwnd(0),
       getMessageHook(0), serialNumber(0), lastSerialNumber(0), sendPostedEventsWindowsTimerId(0),
-      wakeUps(0)
+      wakeUps(0), activateNotifiersPosted(false)
 {
     resolveTimerAPI();
 }
@@ -392,6 +393,7 @@ LRESULT QT_WIN_CALLBACK qt_internal_proc(HWND hwnd, UINT message, WPARAM wp, LPA
             if (sn) {
                 d->doWsaAsyncSelect(sn->fd, 0);
                 d->active_fd[sn->fd].selected = false;
+                d->postActivateSocketNotifiers();
                 if (type < 3) {
                     QEvent event(QEvent::SockAct);
                     QCoreApplication::sendEvent(sn->obj, &event);
@@ -402,6 +404,20 @@ LRESULT QT_WIN_CALLBACK qt_internal_proc(HWND hwnd, UINT message, WPARAM wp, LPA
             }
         }
         return 0;
+    } else if (message == WM_QT_ACTIVATENOTIFIERS) {
+        Q_ASSERT(d != 0);
+
+        // register all socket notifiers
+        for (QSFDict::iterator it = d->active_fd.begin(), end = d->active_fd.end();
+             it != end; ++it) {
+            QSockFd &sd = it.value();
+            if (!sd.selected) {
+                d->doWsaAsyncSelect(it.key(), sd.event);
+                sd.selected = true;
+            }
+        }
+        d->activateNotifiersPosted = false;
+        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
@@ -642,6 +658,12 @@ void QEventDispatcherWin32Private::doWsaAsyncSelect(int socket, long event)
     WSAAsyncSelect(socket, internalHwnd, event ? int(WM_QT_SOCKETNOTIFIER) : 0, event);
 }
 
+void QEventDispatcherWin32Private::postActivateSocketNotifiers()
+{
+    if (!activateNotifiersPosted)
+        activateNotifiersPosted = PostMessage(internalHwnd, WM_QT_ACTIVATENOTIFIERS, 0, 0);
+}
+
 void QEventDispatcherWin32::createInternalHwnd()
 {
     Q_D(QEventDispatcherWin32);
@@ -760,16 +782,6 @@ bool QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags)
                         d->queuedSocketEvents.append(msg);
                         continue;
                     }
-                } else if (!(flags & QEventLoop::ExcludeSocketNotifiers)) {
-                    // register all socket notifiers
-                    for (QSFDict::iterator it = d->active_fd.begin(), end = d->active_fd.end();
-                         it != end; ++it) {
-                        QSockFd &sd = it.value();
-                        if (!sd.selected) {
-                            d->doWsaAsyncSelect(it.key(), sd.event);
-                            sd.selected = true;
-                        }
-                    }
                 }
             }
             if (!haveMessage) {
@@ -890,6 +902,8 @@ void QEventDispatcherWin32::registerSocketNotifier(QSocketNotifier *notifier)
                  "same socket %d and type %s", sockfd, t[type]);
     }
 
+    createInternalHwnd();
+
     QSockNot *sn = new QSockNot;
     sn->obj = notifier;
     sn->fd  = sockfd;
@@ -914,6 +928,8 @@ void QEventDispatcherWin32::registerSocketNotifier(QSocketNotifier *notifier)
     } else {
         d->active_fd.insert(sockfd, QSockFd(event));
     }
+
+    d->postActivateSocketNotifiers();
 }
 
 void QEventDispatcherWin32::unregisterSocketNotifier(QSocketNotifier *notifier)
@@ -939,10 +955,12 @@ void QEventDispatcherWin32::unregisterSocketNotifier(QSocketNotifier *notifier)
             d->doWsaAsyncSelect(sockfd, 0);
         const long event[3] = { FD_READ | FD_CLOSE | FD_ACCEPT, FD_WRITE | FD_CONNECT, FD_OOB };
         sd.event ^= event[type];
-        if (sd.event == 0)
+        if (sd.event == 0) {
             d->active_fd.erase(it);
-        else
+        } else if (sd.selected) {
             sd.selected = false;
+            d->postActivateSocketNotifiers();
+        }
     }
 
     QSNDict *sn_vec[3] = { &d->sn_read, &d->sn_write, &d->sn_except };
diff --git a/src/corelib/kernel/qeventdispatcher_win_p.h b/src/corelib/kernel/qeventdispatcher_win_p.h
index 8578110ee43b58aabeb4da97f7c8e0ff38576483..9a53e067302dceeae7c21c99e844bfa7ed7b4104 100644
--- a/src/corelib/kernel/qeventdispatcher_win_p.h
+++ b/src/corelib/kernel/qeventdispatcher_win_p.h
@@ -178,7 +178,9 @@ public:
     QSNDict sn_write;
     QSNDict sn_except;
     QSFDict active_fd;
+    bool activateNotifiersPosted;
     void doWsaAsyncSelect(int socket, long event);
+    void postActivateSocketNotifiers();
 
     QList<QWinEventNotifier *> winEventNotifierList;
     void activateEventNotifier(QWinEventNotifier * wen);
diff --git a/src/corelib/kernel/qsignalmapper.cpp b/src/corelib/kernel/qsignalmapper.cpp
index 00aa31383fbb9bc5ec73f45d7d3e538f961be029..5e8ce0c2516c048b81efcc64f6bf05aeb2f707ce 100644
--- a/src/corelib/kernel/qsignalmapper.cpp
+++ b/src/corelib/kernel/qsignalmapper.cpp
@@ -220,6 +220,9 @@ QObject *QSignalMapper::mapping(QObject *object) const
     Removes all mappings for \a sender.
 
     This is done automatically when mapped objects are destroyed.
+
+    \note This does not disconnect any signals. If \a sender is not destroyed
+    then this will need to be done explicitly if required.
 */
 void QSignalMapper::removeMappings(QObject *sender)
 {
diff --git a/src/corelib/kernel/qvariant.cpp b/src/corelib/kernel/qvariant.cpp
index 3e6aefab2aae4f89eb48391623d69c9cb061122a..9298093f44f56251915b138743b619e7fde7682b 100644
--- a/src/corelib/kernel/qvariant.cpp
+++ b/src/corelib/kernel/qvariant.cpp
@@ -2891,6 +2891,7 @@ static const quint32 qCanConvertMatrix[QVariant::LastCoreType + 1] =
 
 /*QUuid*/         1 << QVariant::String
 };
+static const size_t qCanConvertMatrixMaximumTargetType = 8 * sizeof(*qCanConvertMatrix);
 
 #ifndef QT_BOOTSTRAPPED
 /*!
@@ -3140,8 +3141,9 @@ bool QVariant::canConvert(int targetTypeId) const
         case QMetaType::ULong:
         case QMetaType::Short:
         case QMetaType::UShort:
-            return qCanConvertMatrix[QVariant::Int] & (1 << currentType)
-                || currentType == QVariant::Int
+            return currentType == QVariant::Int
+                || (currentType < qCanConvertMatrixMaximumTargetType
+                    && qCanConvertMatrix[QVariant::Int] & (1U << currentType))
                 || QMetaType::typeFlags(currentType) & QMetaType::IsEnumeration;
         case QMetaType::QObjectStar:
             return canConvertMetaObject(currentType, targetTypeId, d.data.o);
@@ -3152,7 +3154,8 @@ bool QVariant::canConvert(int targetTypeId) const
 
     if (targetTypeId == String && currentType == StringList)
         return v_cast<QStringList>(&d)->count() == 1;
-    return qCanConvertMatrix[targetTypeId] & (1 << currentType);
+    return currentType < qCanConvertMatrixMaximumTargetType
+        && qCanConvertMatrix[targetTypeId] & (1U << currentType);
 }
 
 /*!
diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp
index 20d5ed890b0e5f68332d6e2360d2e88e21dad71e..63cf7672cfcfdc2e5c441436e98c8d951d4a0558 100644
--- a/src/corelib/statemachine/qstatemachine.cpp
+++ b/src/corelib/statemachine/qstatemachine.cpp
@@ -1891,12 +1891,14 @@ void QStateMachinePrivate::_q_process()
                 }
         }
         if (enabledTransitions.isEmpty()) {
-            processing = false;
-            stopProcessingReason = EventQueueEmpty;
-            noMicrostep();
+            if (isInternalEventQueueEmpty()) {
+                processing = false;
+                stopProcessingReason = EventQueueEmpty;
+                noMicrostep();
 #ifdef QSTATEMACHINE_DEBUG
-            qDebug() << q << ": no transitions enabled";
+                qDebug() << q << ": no transitions enabled";
 #endif
+            }
         } else {
             didChange = true;
             q->beginMicrostep(e);
diff --git a/src/corelib/thread/qexception.cpp b/src/corelib/thread/qexception.cpp
index 04a03b86233772de88df83398123531d26cc265d..cecd69c273b480c28c21a4cf335e06a13bfeb9cb 100644
--- a/src/corelib/thread/qexception.cpp
+++ b/src/corelib/thread/qexception.cpp
@@ -165,7 +165,7 @@ public:
 };
 
 ExceptionHolder::ExceptionHolder(QException *exception)
-: base(new Base(exception)) {}
+: base(exception ? new Base(exception) : Q_NULLPTR) {}
 
 ExceptionHolder::ExceptionHolder(const ExceptionHolder &other)
 : base(other.base)
@@ -181,6 +181,8 @@ ExceptionHolder::~ExceptionHolder()
 
 QException *ExceptionHolder::exception() const
 {
+    if (!base)
+        return Q_NULLPTR;
     return base->exception;
 }
 
diff --git a/src/corelib/thread/qorderedmutexlocker_p.h b/src/corelib/thread/qorderedmutexlocker_p.h
index c73a790820d413a6870512146c05851f88d0f0da..54887342e71ada627d3f6717e6c63312678be04e 100644
--- a/src/corelib/thread/qorderedmutexlocker_p.h
+++ b/src/corelib/thread/qorderedmutexlocker_p.h
@@ -47,6 +47,8 @@
 
 #include <QtCore/qmutex.h>
 
+#include <functional>
+
 QT_BEGIN_NAMESPACE
 
 /*
@@ -57,8 +59,8 @@ class QOrderedMutexLocker
 {
 public:
     QOrderedMutexLocker(QMutex *m1, QMutex *m2)
-        : mtx1((m1 == m2) ? m1 : (m1 < m2 ? m1 : m2)),
-          mtx2((m1 == m2) ?  0 : (m1 < m2 ? m2 : m1)),
+        : mtx1((m1 == m2) ? m1 : (std::less<QMutex *>()(m1, m2) ? m1 : m2)),
+          mtx2((m1 == m2) ?  0 : (std::less<QMutex *>()(m1, m2) ? m2 : m1)),
           locked(false)
     {
         relock();
diff --git a/src/corelib/tools/qdatetime.cpp b/src/corelib/tools/qdatetime.cpp
index 8943c8c6cd511a403acb41c124b73551f31e933c..054b6f3fbdbeba50b1b1290041fff546814c5309 100644
--- a/src/corelib/tools/qdatetime.cpp
+++ b/src/corelib/tools/qdatetime.cpp
@@ -93,14 +93,25 @@ static inline QDate fixedDate(int y, int m, int d)
     return result;
 }
 
+/*
+  Until C++11, rounding direction is implementation-defined.
+
+  For negative operands, implementations may chose to round down instead of
+  towards zero (truncation).  We only actually care about the case a < 0, as all
+  uses of floordiv have b > 0.  In this case, if rounding is down we have a % b
+  >= 0 and simple division works fine; but a % b = a - (a / b) * b always, so
+  rounding towards zero gives a % b <= 0; when < 0, we need to adjust.
+
+  Once we assume C++11, we can safely test a < 0 instead of a % b < 0.
+ */
 static inline qint64 floordiv(qint64 a, int b)
 {
-    return (a - (a < 0 ? b-1 : 0)) / b;
+    return (a - (a % b < 0 ? b - 1 : 0)) / b;
 }
 
 static inline int floordiv(int a, int b)
 {
-    return (a - (a < 0 ? b-1 : 0)) / b;
+    return (a - (a % b < 0 ? b - 1 : 0)) / b;
 }
 
 static inline qint64 julianDayFromDate(int year, int month, int day)
@@ -2696,10 +2707,11 @@ qint64 QDateTimePrivate::toMSecsSinceEpoch() const
     }
 
     case Qt::TimeZone:
-#ifndef QT_BOOTSTRAPPED
+#ifdef QT_BOOTSTRAPPED
+        break;
+#else
         return zoneMSecsToEpochMSecs(m_msecs, m_timeZone);
 #endif
-        break;
     }
     Q_UNREACHABLE();
     return 0;
@@ -3196,7 +3208,9 @@ QString QDateTime::timeZoneAbbreviation() const
     case Qt::OffsetFromUTC:
         return QTimeZonePrivate::utcQString() + toOffsetString(Qt::ISODate, d->m_offsetFromUtc);
     case Qt::TimeZone:
-#ifndef QT_BOOTSTRAPPED
+#ifdef QT_BOOTSTRAPPED
+        break;
+#else
         return d->m_timeZone.d->abbreviation(d->toMSecsSinceEpoch());
 #endif // QT_BOOTSTRAPPED
     case Qt::LocalTime:  {
@@ -3227,7 +3241,9 @@ bool QDateTime::isDaylightTime() const
     case Qt::OffsetFromUTC:
         return false;
     case Qt::TimeZone:
-#ifndef QT_BOOTSTRAPPED
+#ifdef QT_BOOTSTRAPPED
+        break;
+#else
         return d->m_timeZone.d->isDaylightTime(toMSecsSinceEpoch());
 #endif // QT_BOOTSTRAPPED
     case Qt::LocalTime: {
@@ -4824,10 +4840,8 @@ QDataStream &operator<<(QDataStream &out, const QDateTime &dateTime)
             out << (qint8)QDateTimePrivate::OffsetFromUTC;
             break;
         case Qt::TimeZone:
-#ifndef QT_BOOTSTRAPPED
             out << (qint8)QDateTimePrivate::TimeZone;
             break;
-#endif // QT_BOOTSTRAPPED
         case Qt::LocalTime:
             out << (qint8)QDateTimePrivate::LocalUnknown;
             break;
@@ -4900,10 +4914,11 @@ QDataStream &operator>>(QDataStream &in, QDateTime &dateTime)
             spec = Qt::OffsetFromUTC;
             break;
         case QDateTimePrivate::TimeZone:
-#ifndef QT_BOOTSTRAPPED
             spec = Qt::TimeZone;
+#ifndef QT_BOOTSTRAPPED
+            // FIXME: need to use a different constructor !
+#endif
             break;
-#endif // QT_BOOTSTRAPPED
         case QDateTimePrivate::LocalUnknown:
         case QDateTimePrivate::LocalStandard:
         case QDateTimePrivate::LocalDST:
@@ -4959,8 +4974,8 @@ QDebug operator<<(QDebug dbg, const QDateTime &date)
     case Qt::TimeZone:
 #ifndef QT_BOOTSTRAPPED
         dbg << ' ' << date.timeZone().id();
-        break;
 #endif // QT_BOOTSTRAPPED
+        break;
     case Qt::LocalTime:
         break;
     }
diff --git a/src/corelib/tools/qdatetimeparser.cpp b/src/corelib/tools/qdatetimeparser.cpp
index eaa695ef278f3f459a929dd7c57ba0fd1beaa188..9ca2e1ffc05e859568ad8400b1960bf0abd082dc 100644
--- a/src/corelib/tools/qdatetimeparser.cpp
+++ b/src/corelib/tools/qdatetimeparser.cpp
@@ -382,7 +382,7 @@ bool QDateTimeParser::parseFormat(const QString &newFormat)
             ++add;
             if (status != quote) {
                 status = quote;
-            } else if (newFormat.at(i - 1) != slash) {
+            } else if (i > 0 && newFormat.at(i - 1) != slash) {
                 status = zero;
             }
         } else if (status != quote) {
@@ -494,15 +494,15 @@ bool QDateTimeParser::parseFormat(const QString &newFormat)
     }
 
     if ((newDisplay & (AmPmSection|Hour12Section)) == Hour12Section) {
-        const int max = newSectionNodes.size();
-        for (int i=0; i<max; ++i) {
+        const int count = newSectionNodes.size();
+        for (int i = 0; i < count; ++i) {
             SectionNode &node = newSectionNodes[i];
             if (node.type == Hour12Section)
                 node.type = Hour24Section;
         }
     }
 
-    if (index < newFormat.size()) {
+    if (index < max) {
         appendSeparator(&newSeparators, newFormat, index, index - max, lastQuote);
     } else {
         newSeparators.append(QString());
@@ -765,8 +765,8 @@ int QDateTimeParser::parseSection(const QDateTime &currentValue, int sectionInde
             } else {
                 state = Intermediate;
             }
-            break; }
-        // fall through
+            break;
+        } // else: fall through
     case DaySection:
     case YearSection:
     case YearSection2Digits:
@@ -889,17 +889,17 @@ QDateTimeParser::StateNode QDateTimeParser::parse(QString &input, int &cursorPos
 
     QDTPDEBUG << "parse" << input;
     {
-        int year, month, day, hour12, hour, minute, second, msec, ampm, dayofweek, year2digits;
+        int year, month, day;
         currentValue.date().getDate(&year, &month, &day);
-        year2digits = year % 100;
-        hour = currentValue.time().hour();
-        hour12 = -1;
-        minute = currentValue.time().minute();
-        second = currentValue.time().second();
-        msec = currentValue.time().msec();
-        dayofweek = currentValue.date().dayOfWeek();
-
-        ampm = -1;
+        int year2digits = year % 100;
+        int hour = currentValue.time().hour();
+        int hour12 = -1;
+        int minute = currentValue.time().minute();
+        int second = currentValue.time().second();
+        int msec = currentValue.time().msec();
+        int dayofweek = currentValue.date().dayOfWeek();
+
+        int ampm = -1;
         Sections isSet = NoSection;
         int num;
         State tmpstate;
diff --git a/src/corelib/tools/qsharedpointer.h b/src/corelib/tools/qsharedpointer.h
index 279ec36a2839891b6ef8ac658741cd8fb51fd1e2..af42d069917c18e201aee14fff282675d74dbd7f 100644
--- a/src/corelib/tools/qsharedpointer.h
+++ b/src/corelib/tools/qsharedpointer.h
@@ -108,11 +108,11 @@ public:
 
     ~QWeakPointer();
 
-    QWeakPointer<T> operator=(const QWeakPointer<T> &other);
-    QWeakPointer<T> operator=(const QSharedPointer<T> &other);
+    QWeakPointer<T> &operator=(const QWeakPointer<T> &other);
+    QWeakPointer<T> &operator=(const QSharedPointer<T> &other);
 
     QWeakPointer(const QObject *other);
-    QWeakPointer<T> operator=(const QObject *other);
+    QWeakPointer<T> &operator=(const QObject *other);
 
     void swap(QWeakPointer<T> &other);
 
diff --git a/src/corelib/tools/qsimd.cpp b/src/corelib/tools/qsimd.cpp
index c8e2ab4c0c19c7ea2a0eea7b61751c0299fa257b..06d7c54550deca46613c235063dc0e1e41b71209 100644
--- a/src/corelib/tools/qsimd.cpp
+++ b/src/corelib/tools/qsimd.cpp
@@ -636,7 +636,7 @@ int ffsll(quint64 i)
 #endif
 }
 #endif
-#elif defined(Q_OS_ANDROID) || defined(Q_OS_QNX) || defined(Q_OS_OSX)
+#elif defined(Q_OS_ANDROID) || defined(Q_OS_QNX) || defined(Q_OS_OSX) || defined(Q_OS_HAIKU)
 # define ffsll __builtin_ffsll
 #endif
 
diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp
index 89d9889b2f0a482bcff462d6985a741d8acbb0c9..39ec66c7f13bdb26b3b00148b484d6f177766ea1 100644
--- a/src/corelib/tools/qstring.cpp
+++ b/src/corelib/tools/qstring.cpp
@@ -5709,37 +5709,42 @@ static QString detachAndConvertCase(T &str, QStringIterator it)
     Q_ASSERT(!str.isEmpty());
     QString s = qMove(str);             // will copy if T is const QString
     QChar *pp = s.begin() + it.index(); // will detach if necessary
-    uint uc = it.nextUnchecked();
-    forever {
+
+    do {
+        uint uc = it.nextUnchecked();
+
         const QUnicodeTables::Properties *prop = qGetProp(uc);
         signed short caseDiff = Traits::caseDiff(prop);
 
         if (Q_UNLIKELY(Traits::caseSpecial(prop))) {
-            // slow path: the string is growing
             const ushort *specialCase = specialCaseMap + caseDiff;
             ushort length = *specialCase++;
-            int inpos = it.index() - 1;
-            int outpos = pp - s.constBegin();
-
-            s.replace(outpos, 1, reinterpret_cast<const QChar *>(specialCase), length);
-            pp = const_cast<QChar *>(s.constBegin()) + outpos + length;
-
-            // do we need to adjust the input iterator too?
-            // if it is pointing to s's data, str is empty
-            if (str.isEmpty())
-                it = QStringIterator(s.constBegin(), inpos + length, s.constEnd());
-        } else if (QChar::requiresSurrogates(uc)) {
-            *pp++ = QChar::highSurrogate(uc + caseDiff);
+
+            if (Q_LIKELY(length == 1)) {
+                *pp++ = QChar(*specialCase);
+            } else {
+                // slow path: the string is growing
+                int inpos = it.index() - 1;
+                int outpos = pp - s.constBegin();
+
+                s.replace(outpos, 1, reinterpret_cast<const QChar *>(specialCase), length);
+                pp = const_cast<QChar *>(s.constBegin()) + outpos + length;
+
+                // do we need to adjust the input iterator too?
+                // if it is pointing to s's data, str is empty
+                if (str.isEmpty())
+                    it = QStringIterator(s.constBegin(), inpos + length, s.constEnd());
+            }
+        } else if (Q_UNLIKELY(QChar::requiresSurrogates(uc))) {
+            // so far, case convertion never changes planes (guaranteed by the qunicodetables generator)
+            pp++;
             *pp++ = QChar::lowSurrogate(uc + caseDiff);
         } else {
             *pp++ = QChar(uc + caseDiff);
         }
+    } while (it.hasNext());
 
-        if (!it.hasNext())
-            return s;
-
-        uc = it.nextUnchecked();
-    }
+    return s;
 }
 
 template <typename Traits, typename T>
@@ -5752,12 +5757,13 @@ static QString convertCase(T &str)
     while (e != p && e[-1].isHighSurrogate())
         --e;
 
-    const QUnicodeTables::Properties *prop;
     QStringIterator it(p, e);
-    for ( ; it.hasNext(); it.advanceUnchecked()) {
-        prop = qGetProp(it.peekNextUnchecked());
-        if (Traits::caseDiff(prop))
+    while (it.hasNext()) {
+        uint uc = it.nextUnchecked();
+        if (Traits::caseDiff(qGetProp(uc))) {
+            it.recedeUnchecked();
             return detachAndConvertCase<Traits>(str, it);
+        }
     }
     return qMove(str);
 }
diff --git a/src/corelib/tools/qstringbuilder.h b/src/corelib/tools/qstringbuilder.h
index 3d41aeee18e4718c125ac2e963a75717355c3d29..69bd344f478d5d49d9ea083a669b7f2dc49c02f3 100644
--- a/src/corelib/tools/qstringbuilder.h
+++ b/src/corelib/tools/qstringbuilder.h
@@ -236,9 +236,9 @@ template <> struct QConcatenable<QLatin1String> : private QAbstractConcatenable
     }
     static inline void appendTo(const QLatin1String a, char *&out)
     {
-        if (a.data()) {
-            for (const char *s = a.data(); *s; )
-                *out++ = *s++;
+        if (const char *data = a.data()) {
+            memcpy(out, data, a.size());
+            out += a.size();
         }
     }
 };
diff --git a/src/dbus/qdbusconnection_p.h b/src/dbus/qdbusconnection_p.h
index f030a3ff8c007f3a8d65928d54551967103b92a9..c77daf7ee1be98b1bab9161c4c5e00c13953feda 100644
--- a/src/dbus/qdbusconnection_p.h
+++ b/src/dbus/qdbusconnection_p.h
@@ -1,7 +1,7 @@
 /****************************************************************************
 **
 ** Copyright (C) 2015 The Qt Company Ltd.
-** Copyright (C) 2015 Intel Corporation.
+** Copyright (C) 2016 Intel Corporation.
 ** Contact: http://www.qt.io/licensing/
 **
 ** This file is part of the QtDBus module of the Qt Toolkit.
@@ -281,6 +281,7 @@ private slots:
 
 signals:
     void dispatchStatusChanged();
+    void spyHooksFinished(const QDBusMessage &msg);
     void messageNeedsSending(QDBusPendingCallPrivate *pcall, void *msg, int timeout = -1);
     void signalNeedsConnecting(const QString &key, const QDBusConnectionPrivate::SignalHook &hook);
     bool signalNeedsDisconnecting(const QString &key, const QDBusConnectionPrivate::SignalHook &hook);
diff --git a/src/dbus/qdbusintegrator.cpp b/src/dbus/qdbusintegrator.cpp
index f6221d51b6f91c413379cd72de70991c454eefb4..f0b8f1b44151cadcc6d54a3efafd04afd98443ff 100644
--- a/src/dbus/qdbusintegrator.cpp
+++ b/src/dbus/qdbusintegrator.cpp
@@ -1,7 +1,7 @@
 /****************************************************************************
 **
 ** Copyright (C) 2015 The Qt Company Ltd.
-** Copyright (C) 2015 Intel Corporation.
+** Copyright (C) 2016 Intel Corporation.
 ** Contact: http://www.qt.io/licensing/
 **
 ** This file is part of the QtDBus module of the Qt Toolkit.
@@ -120,8 +120,7 @@ void qdbusDefaultThreadDebug(int action, int condition, QDBusConnectionPrivate *
 qdbusThreadDebugFunc qdbusThreadDebug = 0;
 #endif
 
-typedef void (*QDBusSpyHook)(const QDBusMessage&);
-typedef QVarLengthArray<QDBusSpyHook, 4> QDBusSpyHookList;
+typedef QVarLengthArray<QDBusSpyCallEvent::Hook, 4> QDBusSpyHookList;
 Q_GLOBAL_STATIC(QDBusSpyHookList, qDBusSpyHookList)
 
 extern "C" {
@@ -461,12 +460,29 @@ static QStringList matchArgsForService(const QString &service, QDBusServiceWatch
 }
 
 
-extern Q_DBUS_EXPORT void qDBusAddSpyHook(QDBusSpyHook);
-void qDBusAddSpyHook(QDBusSpyHook hook)
+extern Q_DBUS_EXPORT void qDBusAddSpyHook(QDBusSpyCallEvent::Hook);
+void qDBusAddSpyHook(QDBusSpyCallEvent::Hook hook)
 {
     qDBusSpyHookList()->append(hook);
 }
 
+QDBusSpyCallEvent::~QDBusSpyCallEvent()
+{
+    // Reinsert the message into the processing queue for the connection.
+    // This is done in the destructor so the message is reinserted even if
+    // QCoreApplication is destroyed.
+    QDBusConnectionPrivate *d = static_cast<QDBusConnectionPrivate *>(const_cast<QObject *>(sender()));
+    qDBusDebug() << d << "message spies done for" << msg;
+    emit d->spyHooksFinished(msg);
+}
+
+void QDBusSpyCallEvent::placeMetaCall(QObject *)
+{
+    // call the spy hook list
+    for (int i = 0; i < hookCount; ++i)
+        hooks[i](msg);
+}
+
 extern "C" {
 static DBusHandlerResult
 qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
@@ -488,16 +504,11 @@ qDBusSignalFilter(DBusConnection *connection, DBusMessage *message, void *data)
 
 bool QDBusConnectionPrivate::handleMessage(const QDBusMessage &amsg)
 {
-    const QDBusSpyHookList *list = qDBusSpyHookList();
-    for (int i = 0; list && i < list->size(); ++i) {
-        qDBusDebug() << "calling the message spy hook";
-        (*(*list)[i])(amsg);
-    }
-
     if (!ref.load())
         return false;
     if (!dispatchEnabled && !QDBusMessagePrivate::isLocal(amsg)) {
         // queue messages only, we'll handle them later
+        qDBusDebug() << this << "delivery is suspended";
         pendingMessages << amsg;
         return amsg.type() == QDBusMessage::MethodCallMessage;
     }
@@ -509,6 +520,15 @@ bool QDBusConnectionPrivate::handleMessage(const QDBusMessage &amsg)
         // let them see the signal too
         return false;
     case QDBusMessage::MethodCallMessage:
+        // run it through the spy filters (if any) before the regular processing
+        if (Q_UNLIKELY(qDBusSpyHookList.exists()) && qApp) {
+            const QDBusSpyHookList &list = *qDBusSpyHookList;
+            qDBusDebug() << this << "invoking message spies";
+            QCoreApplication::postEvent(qApp, new QDBusSpyCallEvent(this, QDBusConnection(this),
+                                                                    amsg, list.constData(), list.size()));
+            return true;
+        }
+
         handleObjectCall(amsg);
         return true;
     case QDBusMessage::ReplyMessage:
@@ -981,6 +1001,8 @@ QDBusConnectionPrivate::QDBusConnectionPrivate(QObject *p)
     QDBusMetaTypeId::init();
     connect(this, &QDBusConnectionPrivate::dispatchStatusChanged,
             this, &QDBusConnectionPrivate::doDispatch, Qt::QueuedConnection);
+    connect(this, &QDBusConnectionPrivate::spyHooksFinished,
+            this, &QDBusConnectionPrivate::handleObjectCall, Qt::QueuedConnection);
     connect(this, &QDBusConnectionPrivate::messageNeedsSending,
             this, &QDBusConnectionPrivate::sendInternal);
     connect(this, &QDBusConnectionPrivate::signalNeedsConnecting,
@@ -1092,8 +1114,10 @@ void QDBusConnectionPrivate::doDispatch()
             // dispatch previously queued messages
             PendingMessageList::Iterator it = pendingMessages.begin();
             PendingMessageList::Iterator end = pendingMessages.end();
-            for ( ; it != end; ++it)
+            for ( ; it != end; ++it) {
+                qDBusDebug() << this << "dequeueing message" << *it;
                 handleMessage(qMove(*it));
+            }
             pendingMessages.clear();
         }
     }
diff --git a/src/dbus/qdbusintegrator_p.h b/src/dbus/qdbusintegrator_p.h
index 62106e4c0bf4cdba32e958fadb7287cf20aa64a8..2bbebdf7083db191d2fa6a2823da1d55efb42517 100644
--- a/src/dbus/qdbusintegrator_p.h
+++ b/src/dbus/qdbusintegrator_p.h
@@ -1,6 +1,7 @@
 /****************************************************************************
 **
 ** Copyright (C) 2015 The Qt Company Ltd.
+** Copyright (C) 2016 Intel Corporation.
 ** Contact: http://www.qt.io/licensing/
 **
 ** This file is part of the QtDBus module of the Qt Toolkit.
@@ -65,6 +66,7 @@
 QT_BEGIN_NAMESPACE
 
 class QDBusConnectionPrivate;
+class QDBusMessage;
 
 // Really private structs used by qdbusintegrator.cpp
 // Things that aren't used by any other file
@@ -133,6 +135,23 @@ private:
     bool handled;
 };
 
+class QDBusSpyCallEvent : public QMetaCallEvent
+{
+public:
+    typedef void (*Hook)(const QDBusMessage&);
+    QDBusSpyCallEvent(QDBusConnectionPrivate *cp, const QDBusConnection &c, const QDBusMessage &msg,
+                      const Hook *hooks, int count)
+        : QMetaCallEvent(0, 0, Q_NULLPTR, cp, 0), conn(c), msg(msg), hooks(hooks), hookCount(count)
+    {}
+    ~QDBusSpyCallEvent();
+    void placeMetaCall(QObject *) Q_DECL_OVERRIDE;
+
+    QDBusConnection conn;   // keeps the refcount in QDBusConnectionPrivate up
+    QDBusMessage msg;
+    const Hook *hooks;
+    int hookCount;
+};
+
 QT_END_NAMESPACE
 
 Q_DECLARE_METATYPE(QDBusSlotCache)
diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp
index 6ec1eecfb1457e02da39213c4e5b6d369bbce975..667b65431e652201bbe6e9a8d4b347e91fa72eb1 100644
--- a/src/gui/image/qimage.cpp
+++ b/src/gui/image/qimage.cpp
@@ -192,7 +192,9 @@ bool QImageData::checkForAlphaPixels() const
     case QImage::Format_Indexed8:
         has_alpha_pixels = has_alpha_clut;
         break;
-
+    case QImage::Format_Alpha8:
+        has_alpha_pixels = true;
+        break;
     case QImage::Format_ARGB32:
     case QImage::Format_ARGB32_Premultiplied: {
         uchar *bits = data;
@@ -266,7 +268,20 @@ bool QImageData::checkForAlphaPixels() const
         }
     } break;
 
-    default:
+    case QImage::Format_RGB32:
+    case QImage::Format_RGB16:
+    case QImage::Format_RGB444:
+    case QImage::Format_RGB555:
+    case QImage::Format_RGB666:
+    case QImage::Format_RGB888:
+    case QImage::Format_RGBX8888:
+    case QImage::Format_BGR30:
+    case QImage::Format_RGB30:
+    case QImage::Format_Grayscale8:
+        break;
+    case QImage::Format_Invalid:
+    case QImage::NImageFormats:
+        Q_UNREACHABLE();
         break;
     }
 
diff --git a/src/gui/kernel/qguiapplication.cpp b/src/gui/kernel/qguiapplication.cpp
index a387b3ac7672c8d5a2bc3c9e2d726ac7ba261c7c..0414d40f7b74a5dbfbe03193ece7b0883ce64cf3 100644
--- a/src/gui/kernel/qguiapplication.cpp
+++ b/src/gui/kernel/qguiapplication.cpp
@@ -607,6 +607,8 @@ QGuiApplication::~QGuiApplication()
     QGuiApplicationPrivate::platform_name = 0;
     delete QGuiApplicationPrivate::displayName;
     QGuiApplicationPrivate::displayName = 0;
+    delete QGuiApplicationPrivate::m_inputDeviceManager;
+    QGuiApplicationPrivate::m_inputDeviceManager = 0;
 }
 
 QGuiApplicationPrivate::QGuiApplicationPrivate(int &argc, char **argv, int flags)
@@ -1063,7 +1065,7 @@ static void init_platform(const QString &pluginArgument, const QString &platform
         QStringList keys = QPlatformIntegrationFactory::keys(platformPluginPath);
 
         QString fatalMessage
-                = QStringLiteral("This application failed to start because it could not find or load the Qt platform plugin \"%1\".\n\n").arg(name);
+                = QStringLiteral("This application failed to start because it could not find or load the Qt platform plugin \"%1\"\nin \"%2\".\n\n").arg(name, QDir::toNativeSeparators(platformPluginPath));
         if (!keys.isEmpty()) {
             fatalMessage += QStringLiteral("Available platform plugins are: %1.\n\n").arg(
                         keys.join(QStringLiteral(", ")));
@@ -1186,30 +1188,32 @@ void QGuiApplicationPrivate::createPlatformIntegration()
 
     int j = argc ? 1 : 0;
     for (int i=1; i<argc; i++) {
-        if (argv[i] && *argv[i] != '-') {
+        if (!argv[i])
+            continue;
+        if (*argv[i] != '-') {
             argv[j++] = argv[i];
             continue;
         }
         const bool isXcb = platformName == "xcb";
-        QByteArray arg = argv[i];
-        if (arg.startsWith("--"))
-            arg.remove(0, 1);
-        if (arg == "-platformpluginpath") {
+        const char *arg = argv[i];
+        if (arg[1] == '-') // startsWith("--")
+            ++arg;
+        if (strcmp(arg, "-platformpluginpath") == 0) {
             if (++i < argc)
                 platformPluginPath = QString::fromLocal8Bit(argv[i]);
-        } else if (arg == "-platform") {
+        } else if (strcmp(arg, "-platform") == 0) {
             if (++i < argc)
                 platformName = argv[i];
-        } else if (arg == "-platformtheme") {
+        } else if (strcmp(arg, "-platformtheme") == 0) {
             if (++i < argc)
                 platformThemeName = QString::fromLocal8Bit(argv[i]);
-        } else if (arg == "-qwindowgeometry" || (isXcb && arg == "-geometry")) {
+        } else if (strcmp(arg, "-qwindowgeometry") == 0 || (isXcb && strcmp(arg, "-geometry") == 0)) {
             if (++i < argc)
                 windowGeometrySpecification = QWindowGeometrySpecification::fromArgument(argv[i]);
-        } else if (arg == "-qwindowtitle" || (isXcb && arg == "-title")) {
+        } else if (strcmp(arg, "-qwindowtitle") == 0 || (isXcb && strcmp(arg, "-title") == 0)) {
             if (++i < argc)
                 firstWindowTitle = QString::fromLocal8Bit(argv[i]);
-        } else if (arg == "-qwindowicon" || (isXcb && arg == "-icon")) {
+        } else if (strcmp(arg, "-qwindowicon") == 0 || (isXcb && strcmp(arg, "-icon") == 0)) {
             if (++i < argc) {
                 icon = QString::fromLocal8Bit(argv[i]);
             }
@@ -1285,20 +1289,22 @@ void QGuiApplicationPrivate::init()
     QString s;
     int j = argc ? 1 : 0;
     for (int i=1; i<argc; i++) {
-        if (argv[i] && *argv[i] != '-') {
+        if (!argv[i])
+            continue;
+        if (*argv[i] != '-') {
             argv[j++] = argv[i];
             continue;
         }
-        QByteArray arg = argv[i];
-        if (arg.startsWith("--"))
-            arg.remove(0, 1);
-        if (arg == "-plugin") {
+        const char *arg = argv[i];
+        if (arg[1] == '-') // startsWith("--")
+            ++arg;
+        if (strcmp(arg, "-plugin") == 0) {
             if (++i < argc)
                 pluginList << argv[i];
-        } else if (arg == "-reverse") {
+        } else if (strcmp(arg, "-reverse") == 0) {
             force_reverse = true;
 #ifdef Q_OS_MAC
-        } else if (arg.startsWith("-psn_")) {
+        } else if (strncmp(arg, "-psn_", 5) == 0) {
             // eat "-psn_xxxx" on Mac, which is passed when starting an app from Finder.
             // special hack to change working directory (for an app bundle) when running from finder
             if (QDir::currentPath() == QLatin1String("/")) {
@@ -1310,7 +1316,7 @@ void QGuiApplicationPrivate::init()
             }
 #endif
 #ifndef QT_NO_SESSIONMANAGER
-        } else if (arg == "-session" && i < argc-1) {
+        } else if (strcmp(arg, "-session") == 0 && i < argc - 1) {
             ++i;
             if (argv[i] && *argv[i]) {
                 session_id = QString::fromLatin1(argv[i]);
@@ -1322,11 +1328,11 @@ void QGuiApplicationPrivate::init()
                 is_session_restored = true;
             }
 #endif
-        } else if (arg == "-testability") {
+        } else if (strcmp(arg, "-testability") == 0) {
             loadTestability = true;
-        } else if (arg.indexOf("-style=", 0) != -1) {
-            s = QString::fromLocal8Bit(arg.right(arg.length() - 7).toLower());
-        } else if (arg == "-style" && i < argc-1) {
+        } else if (strncmp(arg, "-style=", 7) == 0) {
+            s = QString::fromLocal8Bit(arg + 7).toLower();
+        } else if (strcmp(arg, "-style") == 0 && i < argc - 1) {
             s = QString::fromLocal8Bit(argv[++i]).toLower();
         } else {
             argv[j++] = argv[i];
diff --git a/src/gui/kernel/qplatformgraphicsbufferhelper.cpp b/src/gui/kernel/qplatformgraphicsbufferhelper.cpp
index 1d59c385980aafaf9887965c8224a77db3ee8b1c..52457ed606ec5e856aa4d4eaaa5948bc9b1f7466 100644
--- a/src/gui/kernel/qplatformgraphicsbufferhelper.cpp
+++ b/src/gui/kernel/qplatformgraphicsbufferhelper.cpp
@@ -40,6 +40,14 @@
 #include <QtGui/QOpenGLContext>
 #include <QtGui/QOpenGLFunctions>
 
+#ifndef GL_RGB10_A2
+#define GL_RGB10_A2                       0x8059
+#endif
+
+#ifndef GL_UNSIGNED_INT_2_10_10_10_REV
+#define GL_UNSIGNED_INT_2_10_10_10_REV    0x8368
+#endif
+
 QT_BEGIN_NAMESPACE
 
 /*!
@@ -64,7 +72,7 @@ QT_BEGIN_NAMESPACE
     bound texture, otherwise returns false.
 */
 bool QPlatformGraphicsBufferHelper::lockAndBindToTexture(QPlatformGraphicsBuffer *graphicsBuffer,
-                                                         bool *swizzle,
+                                                         bool *swizzle, bool *premultiplied,
                                                          const QRect &rect)
 {
     if (graphicsBuffer->lock(QPlatformGraphicsBuffer::TextureAccess)) {
@@ -74,8 +82,10 @@ bool QPlatformGraphicsBufferHelper::lockAndBindToTexture(QPlatformGraphicsBuffer
         }
         if (swizzle)
             *swizzle = false;
+        if (premultiplied)
+            *premultiplied = false;
     } else if (graphicsBuffer->lock(QPlatformGraphicsBuffer::SWReadAccess)) {
-        if (!bindSWToTexture(graphicsBuffer, swizzle, rect)) {
+        if (!bindSWToTexture(graphicsBuffer, swizzle, premultiplied, rect)) {
             qWarning("Failed to bind %sgraphicsbuffer to texture", "SW ");
             return false;
         }
@@ -109,11 +119,12 @@ bool QPlatformGraphicsBufferHelper::lockAndBindToTexture(QPlatformGraphicsBuffer
     Returns true on success, otherwise false.
 */
 bool QPlatformGraphicsBufferHelper::bindSWToTexture(const QPlatformGraphicsBuffer *graphicsBuffer,
-                                                    bool *swizzleRandB,
+                                                    bool *swizzleRandB, bool *premultipliedB,
                                                     const QRect &subRect)
 {
 #ifndef QT_NO_OPENGL
-    if (!QOpenGLContext::currentContext())
+    QOpenGLContext *ctx = QOpenGLContext::currentContext();
+    if (!ctx)
         return false;
 
     if (!(graphicsBuffer->isLocked() & QPlatformGraphicsBuffer::SWReadAccess))
@@ -123,27 +134,70 @@ bool QPlatformGraphicsBufferHelper::bindSWToTexture(const QPlatformGraphicsBuffe
 
     Q_ASSERT(subRect.isEmpty() || QRect(QPoint(0,0), size).contains(subRect));
 
+    GLenum internalFormat = GL_RGBA;
+    GLuint pixelType = GL_UNSIGNED_BYTE;
+
+    bool needsConversion = false;
     bool swizzle = false;
+    bool premultiplied = false;
     QImage::Format imageformat = QImage::toImageFormat(graphicsBuffer->format());
     QImage image(graphicsBuffer->data(), size.width(), size.height(), graphicsBuffer->bytesPerLine(), imageformat);
     if (graphicsBuffer->bytesPerLine() != (size.width() * 4)) {
-        image = image.convertToFormat(QImage::Format_RGBA8888);
-    } else if (imageformat == QImage::Format_RGB32) {
-        swizzle = true;
-    } else if (imageformat != QImage::Format_RGBA8888) {
-        image = image.convertToFormat(QImage::Format_RGBA8888);
+        needsConversion = true;
+    } else {
+        switch (imageformat) {
+        case QImage::Format_ARGB32_Premultiplied:
+            premultiplied = true;
+            // no break
+        case QImage::Format_RGB32:
+        case QImage::Format_ARGB32:
+            swizzle = true;
+            break;
+        case QImage::Format_RGBA8888_Premultiplied:
+            premultiplied = true;
+            // no break
+        case QImage::Format_RGBX8888:
+        case QImage::Format_RGBA8888:
+            break;
+        case QImage::Format_BGR30:
+        case QImage::Format_A2BGR30_Premultiplied:
+            if (!ctx->isOpenGLES() || ctx->format().majorVersion() >= 3) {
+                pixelType = GL_UNSIGNED_INT_2_10_10_10_REV;
+                internalFormat = GL_RGB10_A2;
+                premultiplied = true;
+            } else {
+                needsConversion = true;
+            }
+            break;
+        case QImage::Format_RGB30:
+        case QImage::Format_A2RGB30_Premultiplied:
+            if (!ctx->isOpenGLES() || ctx->format().majorVersion() >= 3) {
+                pixelType = GL_UNSIGNED_INT_2_10_10_10_REV;
+                internalFormat = GL_RGB10_A2;
+                premultiplied = true;
+                swizzle = true;
+            } else {
+                needsConversion = true;
+            }
+            break;
+        default:
+            needsConversion = true;
+            break;
+        }
     }
+    if (needsConversion)
+        image = image.convertToFormat(QImage::Format_RGBA8888);
 
-    QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
+    QOpenGLFunctions *funcs = ctx->functions();
 
     QRect rect = subRect;
     if (rect.isNull() || rect == QRect(QPoint(0,0),size)) {
-        funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size.width(), size.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image.constBits());
+        funcs->glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, size.width(), size.height(), 0, GL_RGBA, pixelType, image.constBits());
     } else {
 #ifndef QT_OPENGL_ES_2
-        if (!QOpenGLContext::currentContext()->isOpenGLES()) {
+        if (!ctx->isOpenGLES()) {
             funcs->glPixelStorei(GL_UNPACK_ROW_LENGTH, image.width());
-            funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
+            funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, pixelType,
                                    image.constScanLine(rect.y()) + rect.x() * 4);
             funcs->glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
         } else
@@ -160,22 +214,25 @@ bool QPlatformGraphicsBufferHelper::bindSWToTexture(const QPlatformGraphicsBuffe
             // OpenGL instead of copying, since there's no gap between scanlines
 
             if (rect.width() == size.width()) {
-                funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
+                funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(), rect.width(), rect.height(), GL_RGBA, pixelType,
                                        image.constScanLine(rect.y()));
             } else {
-                funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
+                funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, pixelType,
                                        image.copy(rect).constBits());
             }
         }
     }
     if (swizzleRandB)
         *swizzleRandB = swizzle;
+    if (premultipliedB)
+        *premultipliedB = premultiplied;
 
     return true;
 
 #else
     Q_UNUSED(graphicsBuffer)
     Q_UNUSED(swizzleRandB)
+    Q_UNUSED(premultipliedB)
     Q_UNUSED(subRect)
     return false;
 #endif // QT_NO_OPENGL
diff --git a/src/gui/kernel/qplatformgraphicsbufferhelper.h b/src/gui/kernel/qplatformgraphicsbufferhelper.h
index ded7810608f9ee4fac8e2f2d5d36d4becf358fd9..cc1a4918cdecc753cc646c330f5306d411016647 100644
--- a/src/gui/kernel/qplatformgraphicsbufferhelper.h
+++ b/src/gui/kernel/qplatformgraphicsbufferhelper.h
@@ -39,8 +39,8 @@
 QT_BEGIN_NAMESPACE
 
 namespace QPlatformGraphicsBufferHelper {
-    bool lockAndBindToTexture(QPlatformGraphicsBuffer *graphicsBuffer, bool *swizzleRandB, const QRect &rect = QRect());
-    bool bindSWToTexture(const QPlatformGraphicsBuffer *graphicsBuffer, bool *swizzleRandB = Q_NULLPTR, const QRect &rect = QRect());
+    bool lockAndBindToTexture(QPlatformGraphicsBuffer *graphicsBuffer, bool *swizzleRandB, bool *premultipliedB, const QRect &rect = QRect());
+    bool bindSWToTexture(const QPlatformGraphicsBuffer *graphicsBuffer, bool *swizzleRandB = Q_NULLPTR, bool *premultipliedB = Q_NULLPTR, const QRect &rect = QRect());
 }
 
 QT_END_NAMESPACE
diff --git a/src/gui/opengl/qopenglframebufferobject.cpp b/src/gui/opengl/qopenglframebufferobject.cpp
index e0ef7c52a5eb3b36a732b1b42ac488de5f496e04..5184283a317502806c9f439d04b2fd2c75e53794 100644
--- a/src/gui/opengl/qopenglframebufferobject.cpp
+++ b/src/gui/opengl/qopenglframebufferobject.cpp
@@ -1077,8 +1077,6 @@ bool QOpenGLFramebufferObject::bind()
         }
     }
 
-    d->valid = d->checkFramebufferStatus(current);
-
     return d->valid;
 }
 
diff --git a/src/gui/opengl/qopenglfunctions.cpp b/src/gui/opengl/qopenglfunctions.cpp
index d614ad8401b3da08dafeb99b51798f32a8561144..be1a979c37765cc209852af3d38ae9ea0d574770 100644
--- a/src/gui/opengl/qopenglfunctions.cpp
+++ b/src/gui/opengl/qopenglfunctions.cpp
@@ -96,7 +96,7 @@ Q_LOGGING_CATEGORY(lcGLES3, "qt.opengl.es3")
 
         // Setup scene and render it
         initializeGL();
-        paintGL()
+        paintGL();
     }
 
     void MyGLWindow::initializeGL()
diff --git a/src/gui/opengl/qopenglpaintengine.cpp b/src/gui/opengl/qopenglpaintengine.cpp
index 4836dde3439eee6e2536670ca5f497d639b98289..0b92bf4b1da2f2087354353783b77ea1656e7f86 100644
--- a/src/gui/opengl/qopenglpaintengine.cpp
+++ b/src/gui/opengl/qopenglpaintengine.cpp
@@ -93,13 +93,6 @@ QOpenGL2PaintEngineExPrivate::~QOpenGL2PaintEngineExPrivate()
 {
     delete shaderManager;
 
-    while (pathCaches.size()) {
-        QVectorPath::CacheEntry *e = *(pathCaches.constBegin());
-        e->cleanup(e->engine, e->data);
-        e->data = 0;
-        e->engine = 0;
-    }
-
     if (elementIndicesVBOId != 0) {
         funcs.glDeleteBuffers(1, &elementIndicesVBOId);
         elementIndicesVBOId = 0;
@@ -292,8 +285,6 @@ void QOpenGL2PaintEngineExPrivate::updateBrushTexture()
         }
 
         updateTexture(QT_BRUSH_TEXTURE_UNIT, currentBrushImage, wrapMode, filterMode, ForceUpdate);
-
-        textureInvertedY = false;
     }
     brushTextureDirty = false;
 }
@@ -409,11 +400,7 @@ void QOpenGL2PaintEngineExPrivate::updateBrushUniforms()
             dy = 0;
         }
         QTransform gl_to_qt(1, 0, 0, m22, 0, dy);
-        QTransform inv_matrix;
-        if (style == Qt::TexturePattern && textureInvertedY == -1)
-            inv_matrix = gl_to_qt * (QTransform(1, 0, 0, -1, 0, currentBrush.texture().height()) * brushQTransform * matrix).inverted() * translate;
-        else
-            inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
+        QTransform inv_matrix = gl_to_qt * (brushQTransform * matrix).inverted() * translate;
 
         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTransform), inv_matrix);
         shaderManager->currentProgram()->setUniformValue(location(QOpenGLEngineShaderManager::BrushTexture), QT_BRUSH_TEXTURE_UNIT);
diff --git a/src/gui/opengl/qopenglpaintengine_p.h b/src/gui/opengl/qopenglpaintengine_p.h
index 17be72b1e9db9baa54ea3fd717c94c65b4d7828e..f1ec669ca0aab9b05c85c10a905a3b684817d2d0 100644
--- a/src/gui/opengl/qopenglpaintengine_p.h
+++ b/src/gui/opengl/qopenglpaintengine_p.h
@@ -309,14 +309,9 @@ public:
     bool needsSync;
     bool multisamplingAlwaysEnabled;
 
-    GLfloat depthRange[2];
-
-    float textureInvertedY;
-
     QTriangulatingStroker stroker;
     QDashedStrokeProcessor dasher;
 
-    QSet<QVectorPath::CacheEntry *> pathCaches;
     QVector<GLuint> unusedVBOSToClean;
     QVector<GLuint> unusedIBOSToClean;
 
diff --git a/src/gui/opengl/qopengltexture.cpp b/src/gui/opengl/qopengltexture.cpp
index 02dee5a90a98318b466ed252bda33aa520a21368..6b83c17fd4704d4349becc76c8d9cb32526b6530 100644
--- a/src/gui/opengl/qopengltexture.cpp
+++ b/src/gui/opengl/qopengltexture.cpp
@@ -3222,6 +3222,12 @@ void QOpenGLTexture::setData(const QImage& image, MipMapGeneration genMipMaps)
         qWarning("QOpenGLTexture::setData() requires a valid current context");
         return;
     }
+
+    if (image.isNull()) {
+        qWarning("QOpenGLTexture::setData() tried to set a null image");
+        return;
+    }
+
     if (context->isOpenGLES() && context->format().majorVersion() < 3)
         setFormat(QOpenGLTexture::RGBAFormat);
     else
diff --git a/src/gui/painting/qplatformbackingstore.cpp b/src/gui/painting/qplatformbackingstore.cpp
index 4b725fc79fac9a444ed3c02b4e64cef30fb9dd7f..8e40eb6dff5736245ac4899d0c69e98755c8fbf1 100644
--- a/src/gui/painting/qplatformbackingstore.cpp
+++ b/src/gui/painting/qplatformbackingstore.cpp
@@ -57,6 +57,12 @@
 #ifndef GL_UNPACK_ROW_LENGTH
 #define GL_UNPACK_ROW_LENGTH              0x0CF2
 #endif
+#ifndef GL_RGB10_A2
+#define GL_RGB10_A2                       0x8059
+#endif
+#ifndef GL_UNSIGNED_INT_2_10_10_10_REV
+#define GL_UNSIGNED_INT_2_10_10_10_REV    0x8368
+#endif
 
 QT_BEGIN_NAMESPACE
 
@@ -92,6 +98,7 @@ public:
     mutable GLuint textureId;
     mutable QSize textureSize;
     mutable bool needsSwizzle;
+    mutable bool premultiplied;
     QOpenGLTextureBlitter *blitter;
 #endif
 };
@@ -323,9 +330,6 @@ void QPlatformBackingStore::composeAndFlush(QWindow *window, const QRegion &regi
             blitTextureForWidget(textures, i, window, deviceWindowRect, d_ptr->blitter, offset);
     }
 
-    funcs->glEnable(GL_BLEND);
-    funcs->glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
-
     // Backingstore texture with the normal widgets.
     GLuint textureId = 0;
     QOpenGLTextureBlitter::Origin origin = QOpenGLTextureBlitter::OriginTopLeft;
@@ -345,7 +349,7 @@ void QPlatformBackingStore::composeAndFlush(QWindow *window, const QRegion &regi
             funcs->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
             funcs->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 
-            if (QPlatformGraphicsBufferHelper::lockAndBindToTexture(graphicsBuffer, &d_ptr->needsSwizzle)) {
+            if (QPlatformGraphicsBufferHelper::lockAndBindToTexture(graphicsBuffer, &d_ptr->needsSwizzle, &d_ptr->premultiplied)) {
                 d_ptr->textureSize = graphicsBuffer->size();
             } else {
                 d_ptr->textureSize = QSize(0,0);
@@ -354,7 +358,7 @@ void QPlatformBackingStore::composeAndFlush(QWindow *window, const QRegion &regi
             graphicsBuffer->unlock();
         } else if (!region.isEmpty()){
             funcs->glBindTexture(GL_TEXTURE_2D, d_ptr->textureId);
-            QPlatformGraphicsBufferHelper::lockAndBindToTexture(graphicsBuffer, &d_ptr->needsSwizzle);
+            QPlatformGraphicsBufferHelper::lockAndBindToTexture(graphicsBuffer, &d_ptr->needsSwizzle, &d_ptr->premultiplied);
         }
 
         if (graphicsBuffer->origin() == QPlatformGraphicsBuffer::OriginBottomLeft)
@@ -364,17 +368,24 @@ void QPlatformBackingStore::composeAndFlush(QWindow *window, const QRegion &regi
         TextureFlags flags = 0;
         textureId = toTexture(deviceRegion(region, window, offset), &d_ptr->textureSize, &flags);
         d_ptr->needsSwizzle = (flags & TextureSwizzle) != 0;
+        d_ptr->premultiplied = (flags & TexturePremultiplied) != 0;
         if (flags & TextureFlip)
             origin = QOpenGLTextureBlitter::OriginBottomLeft;
     }
 
+    funcs->glEnable(GL_BLEND);
+    if (d_ptr->premultiplied)
+        funcs->glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
+    else
+        funcs->glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
+
     if (textureId) {
         if (d_ptr->needsSwizzle)
             d_ptr->blitter->setSwizzleRB(true);
         // The backingstore is for the entire tlw.
         // In case of native children offset tells the position relative to the tlw.
         const QRect srcRect = toBottomLeftRect(deviceWindowRect.translated(offset), d_ptr->textureSize.height());
-        const QMatrix3x3 source = QOpenGLTextureBlitter::sourceTransform(deviceRect(srcRect, window),
+        const QMatrix3x3 source = QOpenGLTextureBlitter::sourceTransform(srcRect,
                                                                          d_ptr->textureSize,
                                                                          origin);
         d_ptr->blitter->blit(textureId, QMatrix4x4(), source);
@@ -443,10 +454,50 @@ GLuint QPlatformBackingStore::toTexture(const QRegion &dirtyRegion, QSize *textu
     QImage image = toImage();
     QSize imageSize = image.size();
 
+    QOpenGLContext *ctx = QOpenGLContext::currentContext();
+    GLenum internalFormat = GL_RGBA;
+    GLuint pixelType = GL_UNSIGNED_BYTE;
+
+    bool needsConversion = false;
     *flags = 0;
-    if (image.format() == QImage::Format_RGB32)
+    switch (image.format()) {
+    case QImage::Format_ARGB32_Premultiplied:
+        *flags |= TexturePremultiplied;
+        // no break
+    case QImage::Format_RGB32:
+    case QImage::Format_ARGB32:
         *flags |= TextureSwizzle;
-
+        break;
+    case QImage::Format_RGBA8888_Premultiplied:
+        *flags |= TexturePremultiplied;
+        // no break
+    case QImage::Format_RGBX8888:
+    case QImage::Format_RGBA8888:
+        break;
+    case QImage::Format_BGR30:
+    case QImage::Format_A2BGR30_Premultiplied:
+        if (!ctx->isOpenGLES() || ctx->format().majorVersion() >= 3) {
+            pixelType = GL_UNSIGNED_INT_2_10_10_10_REV;
+            internalFormat = GL_RGB10_A2;
+            *flags |= TexturePremultiplied;
+        } else {
+            needsConversion = true;
+        }
+        break;
+    case QImage::Format_RGB30:
+    case QImage::Format_A2RGB30_Premultiplied:
+        if (!ctx->isOpenGLES() || ctx->format().majorVersion() >= 3) {
+            pixelType = GL_UNSIGNED_INT_2_10_10_10_REV;
+            internalFormat = GL_RGB10_A2;
+            *flags |= TextureSwizzle | TexturePremultiplied;
+        } else {
+            needsConversion = true;
+        }
+        break;
+    default:
+        needsConversion = true;
+        break;
+    }
     if (imageSize.isEmpty()) {
         *textureSize = imageSize;
         return 0;
@@ -460,17 +511,15 @@ GLuint QPlatformBackingStore::toTexture(const QRegion &dirtyRegion, QSize *textu
 
     *textureSize = imageSize;
 
-    // Fast path for RGB32 and RGBA8888, convert everything else to RGBA8888.
-    if (image.format() != QImage::Format_RGB32 && image.format() != QImage::Format_RGBA8888)
+    if (needsConversion)
         image = image.convertToFormat(QImage::Format_RGBA8888);
 
-    QOpenGLFunctions *funcs = QOpenGLContext::currentContext()->functions();
+    QOpenGLFunctions *funcs = ctx->functions();
     if (resized) {
         if (d_ptr->textureId)
             funcs->glDeleteTextures(1, &d_ptr->textureId);
         funcs->glGenTextures(1, &d_ptr->textureId);
         funcs->glBindTexture(GL_TEXTURE_2D, d_ptr->textureId);
-        QOpenGLContext *ctx = QOpenGLContext::currentContext();
         if (!ctx->isOpenGLES() || ctx->format().majorVersion() >= 3) {
             funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
             funcs->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
@@ -480,17 +529,16 @@ GLuint QPlatformBackingStore::toTexture(const QRegion &dirtyRegion, QSize *textu
         funcs->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
         funcs->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 
-        funcs->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageSize.width(), imageSize.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE,
+        funcs->glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, imageSize.width(), imageSize.height(), 0, GL_RGBA, pixelType,
                             const_cast<uchar*>(image.constBits()));
     } else {
         funcs->glBindTexture(GL_TEXTURE_2D, d_ptr->textureId);
         QRect imageRect = image.rect();
         QRect rect = dirtyRegion.boundingRect() & imageRect;
 
-        QOpenGLContext *ctx = QOpenGLContext::currentContext();
         if (!ctx->isOpenGLES() || ctx->format().majorVersion() >= 3) {
             funcs->glPixelStorei(GL_UNPACK_ROW_LENGTH, image.width());
-            funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
+            funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, pixelType,
                                    image.constScanLine(rect.y()) + rect.x() * 4);
             funcs->glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
         } else {
@@ -505,10 +553,10 @@ GLuint QPlatformBackingStore::toTexture(const QRegion &dirtyRegion, QSize *textu
             // OpenGL instead of copying, since there's no gap between scanlines
 
             if (rect.width() == imageRect.width()) {
-                funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
+                funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, 0, rect.y(), rect.width(), rect.height(), GL_RGBA, pixelType,
                                        image.constScanLine(rect.y()));
             } else {
-                funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, GL_UNSIGNED_BYTE,
+                funcs->glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x(), rect.y(), rect.width(), rect.height(), GL_RGBA, pixelType,
                                        image.copy(rect).constBits());
             }
         }
diff --git a/src/gui/painting/qplatformbackingstore.h b/src/gui/painting/qplatformbackingstore.h
index eac97e9cf69c03538836699e43ed1b4be1a82ce2..9c8da0d1db5b5e6f03e3af155185a945165ebff0 100644
--- a/src/gui/painting/qplatformbackingstore.h
+++ b/src/gui/painting/qplatformbackingstore.h
@@ -118,7 +118,8 @@ public:
     virtual QImage toImage() const;
     enum TextureFlag {
         TextureSwizzle = 0x01,
-        TextureFlip = 0x02
+        TextureFlip = 0x02,
+        TexturePremultiplied = 0x04,
     };
     Q_DECLARE_FLAGS(TextureFlags, TextureFlag)
     virtual GLuint toTexture(const QRegion &dirtyRegion, QSize *textureSize, TextureFlags *flags) const;
diff --git a/src/gui/text/qfont.cpp b/src/gui/text/qfont.cpp
index 947c538234be644c50af5507d3a98faebfb3dfee..bc9da5b564eafae3ad9239a46ec66ea54c1cfc2f 100644
--- a/src/gui/text/qfont.cpp
+++ b/src/gui/text/qfont.cpp
@@ -2796,6 +2796,10 @@ void QFontCache::insertEngineData(const QFontDef &def, QFontEngineData *engineDa
     Q_ASSERT(!engineDataCache.contains(def));
 
     engineData->ref.ref();
+    // Decrease now rather than waiting
+    if (total_cost > min_cost * 2)
+        decreaseCache();
+
     engineDataCache.insert(def, engineData);
     increaseCost(sizeof(QFontEngineData));
 }
@@ -2833,8 +2837,10 @@ void QFontCache::insertEngine(const Key &key, QFontEngine *engine, bool insertMu
                  key.def.pixelSize, key.def.weight, key.def.style, key.def.fixedPitch);
     }
 #endif
-
     engine->ref.ref();
+    // Decrease now rather than waiting
+    if (total_cost > min_cost * 2)
+        decreaseCache();
 
     Engine data(engine);
     data.timestamp = ++current_timestamp;
@@ -2895,7 +2901,11 @@ void QFontCache::timerEvent(QTimerEvent *)
 
         return;
     }
+    decreaseCache();
+}
 
+void QFontCache::decreaseCache()
+{
     // go through the cache and count up everything in use
     uint in_use_cost = 0;
 
diff --git a/src/gui/text/qfont_p.h b/src/gui/text/qfont_p.h
index 25b5ef0b0e21f10de23c21199d82593ed20414c7..ff9265ca19d224ba744cd3f89d9267a4d445fc4a 100644
--- a/src/gui/text/qfont_p.h
+++ b/src/gui/text/qfont_p.h
@@ -276,6 +276,7 @@ private:
     void increaseCost(uint cost);
     void decreaseCost(uint cost);
     void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE;
+    void decreaseCache();
 
     static const uint min_cost;
     uint total_cost, max_cost;
diff --git a/src/gui/text/qfontdatabase.cpp b/src/gui/text/qfontdatabase.cpp
index 1b9852c20c22bd8468f1d91a69773daccc5a9539..c41b3d2c186f63ff887a10242c89696084688e0a 100644
--- a/src/gui/text/qfontdatabase.cpp
+++ b/src/gui/text/qfontdatabase.cpp
@@ -838,7 +838,7 @@ QStringList QPlatformFontDatabase::fallbacksForFamily(const QString &family, QFo
     return retList;
 }
 
-QStringList qt_fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script)
+static QStringList fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script)
 {
     QFontDatabasePrivate *db = privateDb();
 
@@ -870,6 +870,12 @@ QStringList qt_fallbacksForFamily(const QString &family, QFont::Style style, QFo
     return retList;
 }
 
+QStringList qt_fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script)
+{
+    QMutexLocker locker(fontDatabaseMutex());
+    return fallbacksForFamily(family, style, styleHint, script);
+}
+
 static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt);
 
 static void initializeDb()
@@ -915,13 +921,18 @@ QFontEngine *loadSingleEngine(int script,
     QFontDef def = request;
     def.pixelSize = pixelSize;
 
+    QFontCache *fontCache = QFontCache::instance();
+
     QFontCache::Key key(def,script);
-    QFontEngine *engine = QFontCache::instance()->findEngine(key);
+    QFontEngine *engine = fontCache->findEngine(key);
     if (!engine) {
-        if (script != QChar::Script_Common) {
+        const bool cacheForCommonScript = script != QChar::Script_Common
+                && (family->writingSystems[QFontDatabase::Latin] & QtFontFamily::Supported) != 0;
+
+        if (Q_LIKELY(cacheForCommonScript)) {
             // fast path: check if engine was loaded for another script
             key.script = QChar::Script_Common;
-            engine = QFontCache::instance()->findEngine(key);
+            engine = fontCache->findEngine(key);
             key.script = script;
             if (engine) {
                 Q_ASSERT(engine->type() != QFontEngine::Multi);
@@ -931,7 +942,8 @@ QFontEngine *loadSingleEngine(int script,
                     return 0;
                 }
 
-                QFontCache::instance()->insertEngine(key, engine);
+                fontCache->insertEngine(key, engine);
+
                 return engine;
             }
         }
@@ -939,9 +951,10 @@ QFontEngine *loadSingleEngine(int script,
         // If the font data's native stretch matches the requested stretch we need to set stretch to 100
         // to avoid the fontengine synthesizing stretch. If they didn't match exactly we need to calculate
         // the new stretch factor. This only done if not matched by styleName.
-        bool styleNameMatch = !request.styleName.isEmpty() && request.styleName == style->styleName;
-        if (!styleNameMatch && style->key.stretch != 0 && request.stretch != 0)
+        if (style->key.stretch != 0 && request.stretch != 0
+            && (request.styleName.isEmpty() || request.styleName != style->styleName)) {
             def.stretch = (request.stretch * 100 + 50) / style->key.stretch;
+        }
 
         engine = pfdb->fontEngine(def, size->handle);
         if (engine) {
@@ -954,13 +967,13 @@ QFontEngine *loadSingleEngine(int script,
                 return 0;
             }
 
-            QFontCache::instance()->insertEngine(key, engine);
+            fontCache->insertEngine(key, engine);
 
-            if (!engine->symbol && script != QChar::Script_Common && (family->writingSystems[QFontDatabase::Latin] & QtFontFamily::Supported) != 0) {
+            if (Q_LIKELY(cacheForCommonScript && !engine->symbol)) {
                 // cache engine for Common script as well
                 key.script = QChar::Script_Common;
-                if (!QFontCache::instance()->findEngine(key))
-                    QFontCache::instance()->insertEngine(key, engine);
+                if (!fontCache->findEngine(key))
+                    fontCache->insertEngine(key, engine);
             }
         }
     }
@@ -984,7 +997,7 @@ QFontEngine *loadEngine(int script, const QFontDef &request,
             if (styleHint == QFont::AnyStyle && request.fixedPitch)
                 styleHint = QFont::TypeWriter;
 
-            fallbacks += qt_fallbacksForFamily(family->name, QFont::Style(style->key.style), styleHint, QChar::Script(script));
+            fallbacks += fallbacksForFamily(family->name, QFont::Style(style->key.style), styleHint, QChar::Script(script));
 
             pfMultiEngine->setFallbackFamiliesList(fallbacks);
         }
@@ -2629,12 +2642,14 @@ QFontEngine *QFontDatabase::findFont(const QFontDef &request, int script)
     }
 #endif
 
+    QFontCache *fontCache = QFontCache::instance();
+
     // Until we specifically asked not to, try looking for Multi font engine
     // first, the last '1' indicates that we want Multi font engine instead
     // of single ones
     bool multi = !(request.styleStrategy & QFont::NoFontMerging);
     QFontCache::Key key(request, script, multi ? 1 : 0);
-    engine = QFontCache::instance()->findEngine(key);
+    engine = fontCache->findEngine(key);
     if (engine) {
         FM_DEBUG("Cache hit level 1");
         return engine;
@@ -2664,10 +2679,10 @@ QFontEngine *QFontDatabase::findFont(const QFontDef &request, int script)
                 styleHint = QFont::TypeWriter;
 
             QStringList fallbacks = request.fallBackFamilies
-                                  + qt_fallbacksForFamily(request.family,
-                                                          QFont::Style(request.style),
-                                                          styleHint,
-                                                          QChar::Script(script));
+                                  + fallbacksForFamily(request.family,
+                                                       QFont::Style(request.style),
+                                                       styleHint,
+                                                       QChar::Script(script));
             if (script > QChar::Script_Common)
                 fallbacks += QString(); // Find the first font matching the specified script.
 
@@ -2675,7 +2690,7 @@ QFontEngine *QFontDatabase::findFont(const QFontDef &request, int script)
                 QFontDef def = request;
                 def.family = fallbacks.at(i);
                 QFontCache::Key key(def, script, multi ? 1 : 0);
-                engine = QFontCache::instance()->findEngine(key);
+                engine = fontCache->findEngine(key);
                 if (!engine) {
                     QtFontDesc desc;
                     do {
@@ -2720,12 +2735,13 @@ void QFontDatabase::load(const QFontPrivate *d, int script)
         req.stretch = 100;
 
     if (!d->engineData) {
+        QFontCache *fontCache = QFontCache::instance();
         // look for the requested font in the engine data cache
-        d->engineData = QFontCache::instance()->findEngineData(req);
+        d->engineData = fontCache->findEngineData(req);
         if (!d->engineData) {
             // create a new one
             d->engineData = new QFontEngineData;
-            QFontCache::instance()->insertEngineData(req, d->engineData);
+            fontCache->insertEngineData(req, d->engineData);
         }
         d->engineData->ref.ref();
     }
diff --git a/src/gui/text/qfontengine.cpp b/src/gui/text/qfontengine.cpp
index f267b2d147d9ee0c8a674738a38e57d9d28bab13..fc66c4ec4cbc053faaf1b52e749a3ce07402cdc5 100644
--- a/src/gui/text/qfontengine.cpp
+++ b/src/gui/text/qfontengine.cpp
@@ -2290,7 +2290,7 @@ QFontEngine *QFontEngineMulti::createMultiFontEngine(QFontEngine *fe, int script
     }
     if (!engine) {
         engine = QGuiApplicationPrivate::instance()->platformIntegration()->fontDatabase()->fontEngineMulti(fe, QChar::Script(script));
-        QFontCache::instance()->insertEngine(key, engine, /* insertMulti */ !faceIsLocal);
+        fc->insertEngine(key, engine, /* insertMulti */ !faceIsLocal);
     }
     Q_ASSERT(engine);
     return engine;
diff --git a/src/gui/text/qfontengine_ft.cpp b/src/gui/text/qfontengine_ft.cpp
index 89bc72ae4f58c953ba3ce9f17f42d67ad862c327..4dd2ee35b13cd7a685bad38f7391105cd5601ba6 100644
--- a/src/gui/text/qfontengine_ft.cpp
+++ b/src/gui/text/qfontengine_ft.cpp
@@ -646,7 +646,7 @@ QFontEngineFT::QFontEngineFT(const QFontDef &fd)
     matrix.yy = 0x10000;
     matrix.xy = 0;
     matrix.yx = 0;
-    cache_cost = 100;
+    cache_cost = 100 * 1024;
     kerning_pairs_loaded = false;
     transform = false;
     embolden = false;
diff --git a/src/gui/text/qfontengine_ft_p.h b/src/gui/text/qfontengine_ft_p.h
index 83f9a4ef3dfff4e1446c1cac5bf119dd73186d0c..6f05645a3fa7666d45f8a5599c2b8e1eae7e8495 100644
--- a/src/gui/text/qfontengine_ft_p.h
+++ b/src/gui/text/qfontengine_ft_p.h
@@ -189,65 +189,65 @@ private:
         mutable int fast_glyph_count;
     };
 
-    virtual QFontEngine::FaceId faceId() const Q_DECL_OVERRIDE;
-    virtual QFontEngine::Properties properties() const Q_DECL_OVERRIDE;
-    virtual QFixed emSquareSize() const Q_DECL_OVERRIDE;
-    virtual bool supportsSubPixelPositions() const Q_DECL_OVERRIDE
+    QFontEngine::FaceId faceId() const Q_DECL_OVERRIDE;
+    QFontEngine::Properties properties() const Q_DECL_OVERRIDE;
+    QFixed emSquareSize() const Q_DECL_OVERRIDE;
+    bool supportsSubPixelPositions() const Q_DECL_OVERRIDE
     {
         return default_hint_style == HintLight ||
                default_hint_style == HintNone;
     }
 
-    virtual bool getSfntTableData(uint tag, uchar *buffer, uint *length) const Q_DECL_OVERRIDE;
-    virtual int synthesized() const Q_DECL_OVERRIDE;
+    bool getSfntTableData(uint tag, uchar *buffer, uint *length) const Q_DECL_OVERRIDE;
+    int synthesized() const Q_DECL_OVERRIDE;
 
-    virtual QFixed ascent() const Q_DECL_OVERRIDE;
-    virtual QFixed descent() const Q_DECL_OVERRIDE;
-    virtual QFixed leading() const Q_DECL_OVERRIDE;
-    virtual QFixed xHeight() const Q_DECL_OVERRIDE;
-    virtual QFixed averageCharWidth() const Q_DECL_OVERRIDE;
+    QFixed ascent() const Q_DECL_OVERRIDE;
+    QFixed descent() const Q_DECL_OVERRIDE;
+    QFixed leading() const Q_DECL_OVERRIDE;
+    QFixed xHeight() const Q_DECL_OVERRIDE;
+    QFixed averageCharWidth() const Q_DECL_OVERRIDE;
 
-    virtual qreal maxCharWidth() const Q_DECL_OVERRIDE;
-    virtual QFixed lineThickness() const Q_DECL_OVERRIDE;
-    virtual QFixed underlinePosition() const Q_DECL_OVERRIDE;
+    qreal maxCharWidth() const Q_DECL_OVERRIDE;
+    QFixed lineThickness() const Q_DECL_OVERRIDE;
+    QFixed underlinePosition() const Q_DECL_OVERRIDE;
 
-    virtual glyph_t glyphIndex(uint ucs4) const Q_DECL_OVERRIDE;
+    glyph_t glyphIndex(uint ucs4) const Q_DECL_OVERRIDE;
     void doKerning(QGlyphLayout *, ShaperFlags) const Q_DECL_OVERRIDE;
 
-    virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics) Q_DECL_OVERRIDE;
+    void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics) Q_DECL_OVERRIDE;
 
-    virtual bool supportsTransformation(const QTransform &transform) const Q_DECL_OVERRIDE;
+    bool supportsTransformation(const QTransform &transform) const Q_DECL_OVERRIDE;
 
-    virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
-                         QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
-    virtual void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
-                          QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
+    void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
+                 QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
+    void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs,
+                  QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
 
-    virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, ShaperFlags flags) const Q_DECL_OVERRIDE;
+    bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, ShaperFlags flags) const Q_DECL_OVERRIDE;
 
-    virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) Q_DECL_OVERRIDE;
-    virtual glyph_metrics_t boundingBox(glyph_t glyph) Q_DECL_OVERRIDE;
-    virtual glyph_metrics_t boundingBox(glyph_t glyph, const QTransform &matrix) Q_DECL_OVERRIDE;
+    glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) Q_DECL_OVERRIDE;
+    glyph_metrics_t boundingBox(glyph_t glyph) Q_DECL_OVERRIDE;
+    glyph_metrics_t boundingBox(glyph_t glyph, const QTransform &matrix) Q_DECL_OVERRIDE;
 
-    virtual void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags flags) const Q_DECL_OVERRIDE;
-    virtual QImage alphaMapForGlyph(glyph_t g) Q_DECL_OVERRIDE { return alphaMapForGlyph(g, 0); }
-    virtual QImage alphaMapForGlyph(glyph_t, QFixed) Q_DECL_OVERRIDE;
+    void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags flags) const Q_DECL_OVERRIDE;
+    QImage alphaMapForGlyph(glyph_t g) Q_DECL_OVERRIDE { return alphaMapForGlyph(g, 0); }
+    QImage alphaMapForGlyph(glyph_t, QFixed) Q_DECL_OVERRIDE;
     QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t) Q_DECL_OVERRIDE;
-    virtual QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t) Q_DECL_OVERRIDE;
-    virtual glyph_metrics_t alphaMapBoundingBox(glyph_t glyph,
-                                                QFixed subPixelPosition,
-                                                const QTransform &matrix,
-                                                QFontEngine::GlyphFormat format) Q_DECL_OVERRIDE;
-    virtual QImage *lockedAlphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition,
-                                           GlyphFormat neededFormat, const QTransform &t,
-                                           QPoint *offset) Q_DECL_OVERRIDE;
-    virtual bool hasInternalCaching() const Q_DECL_OVERRIDE { return cacheEnabled; }
-    virtual void unlockAlphaMapForGlyph() Q_DECL_OVERRIDE;
-
-    virtual void removeGlyphFromCache(glyph_t glyph) Q_DECL_OVERRIDE;
-    virtual int glyphMargin(QFontEngine::GlyphFormat /* format */) Q_DECL_OVERRIDE { return 0; }
-
-    virtual int glyphCount() const Q_DECL_OVERRIDE;
+    QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t) Q_DECL_OVERRIDE;
+    glyph_metrics_t alphaMapBoundingBox(glyph_t glyph,
+                                        QFixed subPixelPosition,
+                                        const QTransform &matrix,
+                                        QFontEngine::GlyphFormat format) Q_DECL_OVERRIDE;
+    QImage *lockedAlphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition,
+                                   GlyphFormat neededFormat, const QTransform &t,
+                                   QPoint *offset) Q_DECL_OVERRIDE;
+    bool hasInternalCaching() const Q_DECL_OVERRIDE { return cacheEnabled; }
+    void unlockAlphaMapForGlyph() Q_DECL_OVERRIDE;
+
+    void removeGlyphFromCache(glyph_t glyph) Q_DECL_OVERRIDE;
+    int glyphMargin(QFontEngine::GlyphFormat /* format */) Q_DECL_OVERRIDE { return 0; }
+
+    int glyphCount() const Q_DECL_OVERRIDE;
 
     enum Scaling {
         Scaled,
@@ -277,12 +277,12 @@ private:
     bool init(FaceId faceId, bool antialias, GlyphFormat format,
               QFreetypeFace *freetypeFace);
 
-    virtual int getPointInOutline(glyph_t glyph, int flags, quint32 point, QFixed *xpos, QFixed *ypos, quint32 *nPoints) Q_DECL_OVERRIDE;
+    int getPointInOutline(glyph_t glyph, int flags, quint32 point, QFixed *xpos, QFixed *ypos, quint32 *nPoints) Q_DECL_OVERRIDE;
 
     void setQtDefaultHintStyle(QFont::HintingPreference hintingPreference);
-    virtual void setDefaultHintStyle(HintStyle style) Q_DECL_OVERRIDE;
+    void setDefaultHintStyle(HintStyle style) Q_DECL_OVERRIDE;
 
-    virtual QFontEngine *cloneWithSize(qreal pixelSize) const Q_DECL_OVERRIDE;
+    QFontEngine *cloneWithSize(qreal pixelSize) const Q_DECL_OVERRIDE;
     bool initFromFontEngine(const QFontEngineFT *fontEngine);
 
     HintStyle defaultHintStyle() const { return default_hint_style; }
diff --git a/src/gui/text/qfontengine_p.h b/src/gui/text/qfontengine_p.h
index 5282a4033e60fe4f46943efe41851c94d023171e..be9eaa50206e9cff50ce76049425c50f2cf6386c 100644
--- a/src/gui/text/qfontengine_p.h
+++ b/src/gui/text/qfontengine_p.h
@@ -278,7 +278,7 @@ public:
         qt_get_font_table_func_t get_font_table;
     } faceData;
 
-    uint cache_cost; // amount of mem used in kb by the font
+    uint cache_cost; // amount of mem used in bytes by the font
     uint fsType : 16;
     bool symbol;
     struct KernPair {
diff --git a/src/gui/text/qtextcursor.cpp b/src/gui/text/qtextcursor.cpp
index eb51447105c767453985b39ca75f4e0121162366..dfb6c9c471d5a8e22dd5cac64958bf1926b4f3e2 100644
--- a/src/gui/text/qtextcursor.cpp
+++ b/src/gui/text/qtextcursor.cpp
@@ -1072,8 +1072,8 @@ QTextCursor::QTextCursor(const QTextBlock &block)
 /*!
   \internal
  */
-QTextCursor::QTextCursor(QTextDocumentPrivate *p, int pos)
-    : d(new QTextCursorPrivate(p))
+QTextCursor::QTextCursor(QTextDocumentPrivate &p, int pos)
+    : d(new QTextCursorPrivate(&p))
 {
     d->adjusted_anchor = d->anchor = d->position = pos;
 
diff --git a/src/gui/text/qtextcursor.h b/src/gui/text/qtextcursor.h
index 350f38cd0201ccd99857439a4167cd3f1520e57c..c5462b293631d331342e8014a4b4a4942b2d210c 100644
--- a/src/gui/text/qtextcursor.h
+++ b/src/gui/text/qtextcursor.h
@@ -61,10 +61,8 @@ class Q_GUI_EXPORT QTextCursor
 public:
     QTextCursor();
     explicit QTextCursor(QTextDocument *document);
-    QTextCursor(QTextDocumentPrivate *p, int pos);
     explicit QTextCursor(QTextFrame *frame);
     explicit QTextCursor(const QTextBlock &block);
-    explicit QTextCursor(QTextCursorPrivate *d);
     QTextCursor(const QTextCursor &cursor);
 #ifdef Q_COMPILER_RVALUE_REFS
     QTextCursor &operator=(QTextCursor &&other) Q_DECL_NOTHROW { swap(other); return *this; }
@@ -221,8 +219,12 @@ public:
     QTextDocument *document() const;
 
 private:
+    QTextCursor(QTextDocumentPrivate &p, int pos);
+    explicit QTextCursor(QTextCursorPrivate *d);
+
     QSharedDataPointer<QTextCursorPrivate> d;
     friend class QTextCursorPrivate;
+    friend class QTextDocumentPrivate;
     friend class QTextDocumentFragmentPrivate;
     friend class QTextCopyHelper;
     friend class QWidgetTextControlPrivate;
diff --git a/src/gui/text/qtextcursor_p.h b/src/gui/text/qtextcursor_p.h
index 51fb92d37cfe22b3bc03c77acbf8074df34deda9..983ff13742a593efbe037ac9dbbcc147be2502a8 100644
--- a/src/gui/text/qtextcursor_p.h
+++ b/src/gui/text/qtextcursor_p.h
@@ -100,6 +100,9 @@ public:
 
     void aboutToRemoveCell(int from, int to);
 
+    static QTextCursor fromPosition(QTextDocumentPrivate *d, int pos)
+    { return QTextCursor(*d, pos); }
+
     QTextDocumentPrivate *priv;
     qreal x;
     int position;
diff --git a/src/gui/text/qtextdocument.cpp b/src/gui/text/qtextdocument.cpp
index 0affd3239d15598370be46d1b4a5abc449107997..3edf652f35b88da168db466b89f787a03ea7fd30 100644
--- a/src/gui/text/qtextdocument.cpp
+++ b/src/gui/text/qtextdocument.cpp
@@ -33,6 +33,7 @@
 
 #include "qtextdocument.h"
 #include <qtextformat.h>
+#include "qtextcursor_p.h"
 #include "qtextdocumentlayout_p.h"
 #include "qtextdocumentfragment.h"
 #include "qtextdocumentfragment_p.h"
@@ -1273,7 +1274,7 @@ static bool findInBlock(const QTextBlock &block, const QString &expression, int
             }
         }
         //we have a hit, return the cursor for that.
-        *cursor = QTextCursor(block.docHandle(), block.position() + idx);
+        *cursor = QTextCursorPrivate::fromPosition(block.docHandle(), block.position() + idx);
         cursor->setPosition(cursor->position() + expression.length(), QTextCursor::KeepAnchor);
         return true;
     }
@@ -1391,7 +1392,7 @@ static bool findInBlock(const QTextBlock &block, const QRegExp &expression, int
             }
         }
         //we have a hit, return the cursor for that.
-        *cursor = QTextCursor(block.docHandle(), block.position() + idx);
+        *cursor = QTextCursorPrivate::fromPosition(block.docHandle(), block.position() + idx);
         cursor->setPosition(cursor->position() + expr.matchedLength(), QTextCursor::KeepAnchor);
         return true;
     }
@@ -1519,7 +1520,7 @@ static bool findInBlock(const QTextBlock &block, const QRegularExpression &expre
             }
         }
         //we have a hit, return the cursor for that.
-        *cursor = QTextCursor(block.docHandle(), block.position() + idx);
+        *cursor = QTextCursorPrivate::fromPosition(block.docHandle(), block.position() + idx);
         cursor->setPosition(cursor->position() + match.capturedLength(), QTextCursor::KeepAnchor);
         return true;
     }
diff --git a/src/gui/text/qtextdocument_p.cpp b/src/gui/text/qtextdocument_p.cpp
index 587844c1dd2ae7e11f96b6cbbabc2e47e61a5cee..e5dcfb2e55c721b119808075af519a342359bacb 100644
--- a/src/gui/text/qtextdocument_p.cpp
+++ b/src/gui/text/qtextdocument_p.cpp
@@ -1704,7 +1704,7 @@ bool QTextDocumentPrivate::ensureMaximumBlockCount()
     beginEditBlock();
 
     const int blocksToRemove = blocks.numNodes() - maximumBlockCount;
-    QTextCursor cursor(this, 0);
+    QTextCursor cursor(*this, 0);
     cursor.movePosition(QTextCursor::NextBlock, QTextCursor::KeepAnchor, blocksToRemove);
 
     unreachableCharacterCount += cursor.selectionEnd() - cursor.selectionStart();
diff --git a/src/gui/text/qtextobject.cpp b/src/gui/text/qtextobject.cpp
index df7c8b9c71f1f83975c3ff6cb124556518e2fef9..e70b8ed300731b1d8e26c42cd058f3f5968b82dd 100644
--- a/src/gui/text/qtextobject.cpp
+++ b/src/gui/text/qtextobject.cpp
@@ -33,6 +33,7 @@
 
 #include "qtextobject.h"
 #include "qtextobject_p.h"
+#include "qtextcursor_p.h"
 #include "qtextdocument.h"
 #include "qtextformat_p.h"
 #include "qtextdocument_p.h"
@@ -461,7 +462,7 @@ QTextFrame *QTextFrame::parentFrame() const
 QTextCursor QTextFrame::firstCursorPosition() const
 {
     Q_D(const QTextFrame);
-    return QTextCursor(d->pieceTable, firstPosition());
+    return QTextCursorPrivate::fromPosition(d->pieceTable, firstPosition());
 }
 
 /*!
@@ -472,7 +473,7 @@ QTextCursor QTextFrame::firstCursorPosition() const
 QTextCursor QTextFrame::lastCursorPosition() const
 {
     Q_D(const QTextFrame);
-    return QTextCursor(d->pieceTable, lastPosition());
+    return QTextCursorPrivate::fromPosition(d->pieceTable, lastPosition());
 }
 
 /*!
diff --git a/src/gui/text/qtexttable.cpp b/src/gui/text/qtexttable.cpp
index 454d3440d69069e0e4d32f192a13ed415b4b3c83..553dc3c772ea9604566700abd15e8e534a01382e 100644
--- a/src/gui/text/qtexttable.cpp
+++ b/src/gui/text/qtexttable.cpp
@@ -35,6 +35,7 @@
 #include "qtextcursor.h"
 #include "qtextformat.h"
 #include <qdebug.h>
+#include "qtextcursor_p.h"
 #include "qtexttable_p.h"
 #include "qvarlengtharray.h"
 
@@ -220,7 +221,7 @@ int QTextTableCell::columnSpan() const
 */
 QTextCursor QTextTableCell::firstCursorPosition() const
 {
-    return QTextCursor(table->d_func()->pieceTable, firstPosition());
+    return QTextCursorPrivate::fromPosition(table->d_func()->pieceTable, firstPosition());
 }
 
 /*!
@@ -230,7 +231,7 @@ QTextCursor QTextTableCell::firstCursorPosition() const
 */
 QTextCursor QTextTableCell::lastCursorPosition() const
 {
-    return QTextCursor(table->d_func()->pieceTable, lastPosition());
+    return QTextCursorPrivate::fromPosition(table->d_func()->pieceTable, lastPosition());
 }
 
 
@@ -1103,10 +1104,10 @@ void QTextTable::mergeCells(int row, int column, int numRows, int numCols)
             if (nextPos > pos) {
                 if (needsParagraph) {
                     needsParagraph = false;
-                    QTextCursor(p, insertPos++).insertBlock();
+                    QTextCursorPrivate::fromPosition(p, insertPos++).insertBlock();
                     p->move(pos + 1, insertPos, nextPos - pos);
                 } else if (rowHasText) {
-                    QTextCursor(p, insertPos++).insertText(QLatin1String(" "));
+                    QTextCursorPrivate::fromPosition(p, insertPos++).insertText(QLatin1String(" "));
                     p->move(pos + 1, insertPos, nextPos - pos);
                 } else {
                     p->move(pos, insertPos, nextPos - pos);
@@ -1282,7 +1283,7 @@ QTextCursor QTextTable::rowStart(const QTextCursor &c) const
     int row = cell.row();
     QTextDocumentPrivate *p = d->pieceTable;
     QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), d->grid[row*d->nCols]);
-    return QTextCursor(p, it.position());
+    return QTextCursorPrivate::fromPosition(p, it.position());
 }
 
 /*!
@@ -1304,7 +1305,7 @@ QTextCursor QTextTable::rowEnd(const QTextCursor &c) const
     int fragment = row < d->nRows ? d->grid[row*d->nCols] : d->fragment_end;
     QTextDocumentPrivate *p = d->pieceTable;
     QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), fragment);
-    return QTextCursor(p, it.position() - 1);
+    return QTextCursorPrivate::fromPosition(p, it.position() - 1);
 }
 
 /*!
diff --git a/src/network/access/qnetworkdiskcache.cpp b/src/network/access/qnetworkdiskcache.cpp
index 3f705450ddfba695b8dfe71f4004c8066fdf1f01..1d87d63f5da7c9875962d1c0b7f2056470eae787 100644
--- a/src/network/access/qnetworkdiskcache.cpp
+++ b/src/network/access/qnetworkdiskcache.cpp
@@ -67,8 +67,7 @@ QT_BEGIN_NAMESPACE
 
     QNetworkDiskCache stores each url in its own file inside of the
     cacheDirectory using QDataStream.  Files with a text MimeType
-    are compressed using qCompress.  Each cache file starts with "cache_"
-    and ends in ".cache".  Data is written to disk only in insert()
+    are compressed using qCompress.  Data is written to disk only in insert()
     and updateMetaData().
 
     Currently you cannot share the same cache files with more than
diff --git a/src/network/kernel/qnetworkinterface_unix.cpp b/src/network/kernel/qnetworkinterface_unix.cpp
index 5e6d24dd447ff2aa181b212d5b651f385c53bf76..eb73a2fb180a7b41fcda53bb287a0c926a501341 100644
--- a/src/network/kernel/qnetworkinterface_unix.cpp
+++ b/src/network/kernel/qnetworkinterface_unix.cpp
@@ -268,29 +268,29 @@ static QList<QNetworkInterfacePrivate *> interfaceListing()
         }
 #endif
 
-        // Get the interface broadcast address
-        QNetworkAddressEntry entry;
-        if (iface->flags & QNetworkInterface::CanBroadcast) {
-            if (qt_safe_ioctl(socket, SIOCGIFBRDADDR, &req) >= 0) {
-                sockaddr *sa = &req.ifr_addr;
-                if (sa->sa_family == AF_INET)
-                    entry.setBroadcast(addressFromSockaddr(sa));
-            }
-        }
-
         // Get the address of the interface
+        QNetworkAddressEntry entry;
         if (qt_safe_ioctl(socket, SIOCGIFADDR, &req) >= 0) {
             sockaddr *sa = &req.ifr_addr;
             entry.setIp(addressFromSockaddr(sa));
-        }
 
-        // Get the interface netmask
-        if (qt_safe_ioctl(socket, SIOCGIFNETMASK, &req) >= 0) {
-            sockaddr *sa = &req.ifr_addr;
-            entry.setNetmask(addressFromSockaddr(sa));
-        }
+            // Get the interface broadcast address
+            if (iface->flags & QNetworkInterface::CanBroadcast) {
+                if (qt_safe_ioctl(socket, SIOCGIFBRDADDR, &req) >= 0) {
+                    sockaddr *sa = &req.ifr_addr;
+                    if (sa->sa_family == AF_INET)
+                        entry.setBroadcast(addressFromSockaddr(sa));
+                }
+            }
 
-        iface->addressEntries << entry;
+            // Get the interface netmask
+            if (qt_safe_ioctl(socket, SIOCGIFNETMASK, &req) >= 0) {
+                sockaddr *sa = &req.ifr_addr;
+                entry.setNetmask(addressFromSockaddr(sa));
+            }
+
+            iface->addressEntries << entry;
+        }
     }
 
     ::close(socket);
@@ -343,7 +343,7 @@ static QList<QNetworkInterfacePrivate *> createInterfaces(ifaddrs *rawList)
     // - virtual interfaces with no HW address have no AF_PACKET
     // - interface labels have no AF_PACKET, but shouldn't be shown as a new interface
     for (ifaddrs *ptr = rawList; ptr; ptr = ptr->ifa_next) {
-        if (ptr->ifa_addr && ptr->ifa_addr->sa_family != AF_PACKET) {
+        if (!ptr->ifa_addr || ptr->ifa_addr->sa_family != AF_PACKET) {
             QString name = QString::fromLatin1(ptr->ifa_name);
             if (seenInterfaces.contains(name))
                 continue;
diff --git a/src/network/socket/qabstractsocket.cpp b/src/network/socket/qabstractsocket.cpp
index 1c77d14b29d5b2c042054e7e00d01277a6692b6e..385146bb95b8e3d58d6f7542f377846c4c8308da 100644
--- a/src/network/socket/qabstractsocket.cpp
+++ b/src/network/socket/qabstractsocket.cpp
@@ -1555,7 +1555,8 @@ bool QAbstractSocketPrivate::bind(const QHostAddress &address, quint16 port, QAb
     localPort = socketEngine->localPort();
 
     emit q->stateChanged(state);
-    socketEngine->setReadNotificationEnabled(true);
+    if (socketType == QAbstractSocket::UdpSocket)
+        socketEngine->setReadNotificationEnabled(true);
     return true;
 }
 
diff --git a/src/network/socket/qhttpsocketengine.cpp b/src/network/socket/qhttpsocketengine.cpp
index 92ca76b560b25b9d645a09a947f1e345caabe37a..a744688f29c23531d7944b653251e0c4ebc31318 100644
--- a/src/network/socket/qhttpsocketengine.cpp
+++ b/src/network/socket/qhttpsocketengine.cpp
@@ -439,8 +439,11 @@ void QHttpSocketEngine::setReadNotificationEnabled(bool enable)
     d->readNotificationEnabled = enable;
     if (enable) {
         // Enabling read notification can trigger a notification.
-        if (bytesAvailable())
+        if (bytesAvailable()) {
             slotSocketReadNotification();
+        } else if (d->socket && d->socket->state() == QAbstractSocket::UnconnectedState) {
+            emitReadNotification();
+        }
     }
 }
 
diff --git a/src/network/socket/qnativesocketengine.cpp b/src/network/socket/qnativesocketengine.cpp
index e86d3ad76ef652733a2f554b1acc2eac0f4d0f02..805acde860269f501ae446445f7cf3ab33404864 100644
--- a/src/network/socket/qnativesocketengine.cpp
+++ b/src/network/socket/qnativesocketengine.cpp
@@ -293,6 +293,12 @@ void QNativeSocketEnginePrivate::setError(QAbstractSocket::SocketError error, Er
     case TemporaryErrorString:
         socketErrorString = QNativeSocketEngine::tr("Temporary error");
         break;
+    case NetworkDroppedConnectionErrorString:
+        socketErrorString = QNativeSocketEngine::tr("Network dropped connection on reset");
+        break;
+    case ConnectionResetErrorString:
+        socketErrorString = QNativeSocketEngine::tr("Connection reset by peer");
+        break;
     case UnknownSocketErrorString:
         socketErrorString = QNativeSocketEngine::tr("Unknown error");
         break;
diff --git a/src/network/socket/qnativesocketengine_p.h b/src/network/socket/qnativesocketengine_p.h
index 9a76e23013f29f1f2107326f836b572151f7d336..10e34c485a5a9f48bfb9bb0d33e8d61a1b3ee754 100644
--- a/src/network/socket/qnativesocketengine_p.h
+++ b/src/network/socket/qnativesocketengine_p.h
@@ -223,6 +223,8 @@ public:
         NotSocketErrorString,
         InvalidProxyTypeString,
         TemporaryErrorString,
+        NetworkDroppedConnectionErrorString,
+        ConnectionResetErrorString,
 
         UnknownSocketErrorString = -1
     };
diff --git a/src/network/socket/qnativesocketengine_win.cpp b/src/network/socket/qnativesocketengine_win.cpp
index 9aed0caa25fa41e811bdc19cb5893e983b5d0c41..ca0a8b95d597ccb1233f2f067508fe072077308c 100644
--- a/src/network/socket/qnativesocketengine_win.cpp
+++ b/src/network/socket/qnativesocketengine_win.cpp
@@ -1244,7 +1244,17 @@ qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxL
             ret = qint64(bytesRead) > maxLength ? maxLength : qint64(bytesRead);
         } else {
             WS_ERROR_DEBUG(err);
-            setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString);
+            switch (err) {
+            case WSAENETRESET:
+                setError(QAbstractSocket::NetworkError, NetworkDroppedConnectionErrorString);
+                break;
+            case WSAECONNRESET:
+                setError(QAbstractSocket::ConnectionRefusedError, ConnectionResetErrorString);
+                break;
+            default:
+                setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString);
+                break;
+            }
             ret = -1;
             if (header)
                 header->clear();
diff --git a/src/network/socket/qnativesocketengine_winrt.cpp b/src/network/socket/qnativesocketengine_winrt.cpp
index 1c68b28784819ee60fc5adf6362504ce684bfaa1..35b7d5474b2f3f4d4ed6e6639924ccfe22cea284 100644
--- a/src/network/socket/qnativesocketengine_winrt.cpp
+++ b/src/network/socket/qnativesocketengine_winrt.cpp
@@ -578,7 +578,7 @@ qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QIpPacketHea
     } else {
         readOrigin = datagram.data;
     }
-    strcpy(data, readOrigin);
+    memcpy(data, readOrigin, qMin(maxlen, qint64(datagram.data.length())));
     return readOrigin.length();
 }
 
diff --git a/src/network/ssl/qsslcipher.cpp b/src/network/ssl/qsslcipher.cpp
index c480b79371aad934b07b1f2474e49b51ecb8c145..302ba530d44a284c79cf0e5b522cb57bd9372f9c 100644
--- a/src/network/ssl/qsslcipher.cpp
+++ b/src/network/ssl/qsslcipher.cpp
@@ -71,6 +71,8 @@ QSslCipher::QSslCipher()
 }
 
 /*!
+    \since 5.3
+
     Constructs a QSslCipher object for the cipher determined by \a
     name. The constructor accepts only supported ciphers (i.e., the
     \a name must identify a cipher in the list of ciphers returned by
diff --git a/src/platformsupport/dbustray/qstatusnotifieritemadaptor_p.h b/src/platformsupport/dbustray/qstatusnotifieritemadaptor_p.h
index c3849f0e037266568584750501941c2842348f57..46f605a480456803923344c42ae13521396ff336 100644
--- a/src/platformsupport/dbustray/qstatusnotifieritemadaptor_p.h
+++ b/src/platformsupport/dbustray/qstatusnotifieritemadaptor_p.h
@@ -86,19 +86,19 @@ class QStatusNotifierItemAdaptor: public QDBusAbstractAdaptor
 "    <property access=\"read\" type=\"o\" name=\"Menu\"/>\n"
 "    <property access=\"read\" type=\"b\" name=\"ItemIsMenu\"/>\n"
 "    <property access=\"read\" type=\"s\" name=\"IconName\"/>\n"
-"    <property access=\"read\" type=\"(iiay)\" name=\"IconPixmap\">\n"
+"    <property access=\"read\" type=\"a(iiay)\" name=\"IconPixmap\">\n"
 "      <annotation value=\"QXdgDBusImageVector\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n"
 "    </property>\n"
 "    <property access=\"read\" type=\"s\" name=\"OverlayIconName\"/>\n"
-"    <property access=\"read\" type=\"(iiay)\" name=\"OverlayIconPixmap\">\n"
+"    <property access=\"read\" type=\"a(iiay)\" name=\"OverlayIconPixmap\">\n"
 "      <annotation value=\"QXdgDBusImageVector\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n"
 "    </property>\n"
 "    <property access=\"read\" type=\"s\" name=\"AttentionIconName\"/>\n"
-"    <property access=\"read\" type=\"(iiay)\" name=\"AttentionIconPixmap\">\n"
+"    <property access=\"read\" type=\"a(iiay)\" name=\"AttentionIconPixmap\">\n"
 "      <annotation value=\"QXdgDBusImageVector\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n"
 "    </property>\n"
 "    <property access=\"read\" type=\"s\" name=\"AttentionMovieName\"/>\n"
-"    <property access=\"read\" type=\"(s(iiay)ss)\" name=\"ToolTip\">\n"
+"    <property access=\"read\" type=\"(sa(iiay)ss)\" name=\"ToolTip\">\n"
 "      <annotation value=\"QXdgDBusToolTipStruct\" name=\"org.qtproject.QtDBus.QtTypeName\"/>\n"
 "    </property>\n"
 "    <method name=\"ContextMenu\">\n"
diff --git a/src/platformsupport/eglconvenience/qeglplatformcontext.cpp b/src/platformsupport/eglconvenience/qeglplatformcontext.cpp
index acd6197ed5a8fe7838a7258d4b39d41e4d36343b..f5ba5872937ccba6165c71d72b09bee860f4d7cb 100644
--- a/src/platformsupport/eglconvenience/qeglplatformcontext.cpp
+++ b/src/platformsupport/eglconvenience/qeglplatformcontext.cpp
@@ -275,6 +275,12 @@ void QEGLPlatformContext::destroyTemporaryOffscreenSurface(EGLSurface surface)
     eglDestroySurface(m_eglDisplay, surface);
 }
 
+void QEGLPlatformContext::runGLChecks()
+{
+    // Nothing to do here, subclasses may override in order to perform OpenGL
+    // queries needing a context.
+}
+
 void QEGLPlatformContext::updateFormatFromGL()
 {
 #ifndef QT_NO_OPENGL
@@ -346,6 +352,7 @@ void QEGLPlatformContext::updateFormatFromGL()
                 }
             }
         }
+        runGLChecks();
         eglMakeCurrent(prevDisplay, prevSurfaceDraw, prevSurfaceRead, prevContext);
     } else {
         qWarning("QEGLPlatformContext: Failed to make temporary surface current, format not updated (%x)", eglGetError());
diff --git a/src/platformsupport/eglconvenience/qeglplatformcontext_p.h b/src/platformsupport/eglconvenience/qeglplatformcontext_p.h
index 2fa465556b75d5f05b4d25b4431f2ecbb19f731b..41601272a38dfffb4ba5b12107a3c34f40e95c6f 100644
--- a/src/platformsupport/eglconvenience/qeglplatformcontext_p.h
+++ b/src/platformsupport/eglconvenience/qeglplatformcontext_p.h
@@ -84,6 +84,7 @@ protected:
     virtual EGLSurface eglSurfaceForPlatformSurface(QPlatformSurface *surface) = 0;
     virtual EGLSurface createTemporaryOffscreenSurface();
     virtual void destroyTemporaryOffscreenSurface(EGLSurface surface);
+    virtual void runGLChecks();
 
 private:
     void init(const QSurfaceFormat &format, QPlatformOpenGLContext *share);
diff --git a/src/platformsupport/fbconvenience/qfbbackingstore_p.h b/src/platformsupport/fbconvenience/qfbbackingstore_p.h
index 1dc8127fed477011ce6f421690fd03a2fe3e6e85..3a441284494c19702836be0f56dd357ab6bcf420 100644
--- a/src/platformsupport/fbconvenience/qfbbackingstore_p.h
+++ b/src/platformsupport/fbconvenience/qfbbackingstore_p.h
@@ -60,10 +60,10 @@ public:
     QFbBackingStore(QWindow *window);
     ~QFbBackingStore();
 
-    virtual QPaintDevice *paintDevice() Q_DECL_OVERRIDE { return &mImage; }
-    virtual void flush(QWindow *window, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
+    QPaintDevice *paintDevice() Q_DECL_OVERRIDE { return &mImage; }
+    void flush(QWindow *window, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
 
-    virtual void resize(const QSize &size, const QRegion &region) Q_DECL_OVERRIDE;
+    void resize(const QSize &size, const QRegion &region) Q_DECL_OVERRIDE;
 
     const QImage image();
 
diff --git a/src/platformsupport/linuxaccessibility/bridge_p.h b/src/platformsupport/linuxaccessibility/bridge_p.h
index 802b1e4725c83c1631dcb8a7cdd7d4aef3dd737c..69ab618e17858a7c664e5e8fb83780f60e8ae94d 100644
--- a/src/platformsupport/linuxaccessibility/bridge_p.h
+++ b/src/platformsupport/linuxaccessibility/bridge_p.h
@@ -66,7 +66,7 @@ public:
 
     virtual ~QSpiAccessibleBridge();
 
-    virtual void notifyAccessibilityUpdate(QAccessibleEvent *event) Q_DECL_OVERRIDE;
+    void notifyAccessibilityUpdate(QAccessibleEvent *event) Q_DECL_OVERRIDE;
     QDBusConnection dBusConnection() const;
 
 public Q_SLOTS:
diff --git a/src/platformsupport/services/genericunix/qgenericunixservices_p.h b/src/platformsupport/services/genericunix/qgenericunixservices_p.h
index 0c15d6216542572d14927a73351ff5ccd5fdba95..89d5a4dab4db9b03b21596cb9d52d97ade27f4b5 100644
--- a/src/platformsupport/services/genericunix/qgenericunixservices_p.h
+++ b/src/platformsupport/services/genericunix/qgenericunixservices_p.h
@@ -57,8 +57,8 @@ public:
 
     QByteArray desktopEnvironment() const Q_DECL_OVERRIDE;
 
-    virtual bool openUrl(const QUrl &url) Q_DECL_OVERRIDE;
-    virtual bool openDocument(const QUrl &url) Q_DECL_OVERRIDE;
+    bool openUrl(const QUrl &url) Q_DECL_OVERRIDE;
+    bool openDocument(const QUrl &url) Q_DECL_OVERRIDE;
 
 private:
     QString m_webBrowser;
diff --git a/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp b/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
index 8f6171f2179a555f71e15349a38fea0013243ff7..0bcd3464b74eae327b257d19af65f29c68fdfafe 100644
--- a/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
+++ b/src/platformsupport/themes/genericunix/qgenericunixthemes.cpp
@@ -577,23 +577,23 @@ const char *QGnomeTheme::name = "gnome";
 class QGnomeThemePrivate : public QPlatformThemePrivate
 {
 public:
-    QGnomeThemePrivate() : fontsConfigured(false) { }
+    QGnomeThemePrivate() : systemFont(Q_NULLPTR), fixedFont(Q_NULLPTR) {}
+    ~QGnomeThemePrivate() { delete systemFont; delete fixedFont; }
+
     void configureFonts(const QString &gtkFontName) const
     {
-        Q_ASSERT(!fontsConfigured);
+        Q_ASSERT(!systemFont);
         const int split = gtkFontName.lastIndexOf(QChar::Space);
         float size = gtkFontName.mid(split+1).toFloat();
         QString fontName = gtkFontName.left(split);
 
-        systemFont = QFont(fontName, size);
-        fixedFont = QFont(QLatin1String("monospace"), systemFont.pointSize());
-        fixedFont.setStyleHint(QFont::TypeWriter);
-        fontsConfigured = true;
+        systemFont = new QFont(fontName, size);
+        fixedFont = new QFont(QLatin1String("monospace"), systemFont->pointSize());
+        fixedFont->setStyleHint(QFont::TypeWriter);
     }
 
-    mutable QFont systemFont;
-    mutable QFont fixedFont;
-    mutable bool fontsConfigured;
+    mutable QFont *systemFont;
+    mutable QFont *fixedFont;
 };
 
 QGnomeTheme::QGnomeTheme()
@@ -632,13 +632,13 @@ QVariant QGnomeTheme::themeHint(QPlatformTheme::ThemeHint hint) const
 const QFont *QGnomeTheme::font(Font type) const
 {
     Q_D(const QGnomeTheme);
-    if (!d->fontsConfigured)
+    if (!d->systemFont)
         d->configureFonts(gtkFontName());
     switch (type) {
     case QPlatformTheme::SystemFont:
-        return &d->systemFont;
+        return d->systemFont;
     case QPlatformTheme::FixedFont:
-        return &d->fixedFont;
+        return d->fixedFont;
     default:
         return 0;
     }
diff --git a/src/platformsupport/themes/genericunix/qgenericunixthemes_p.h b/src/platformsupport/themes/genericunix/qgenericunixthemes_p.h
index 115b9d9f917795e903f6f2496551c403474ef6e4..77aa04fe950265b6b5098e2620e104099e52bb17 100644
--- a/src/platformsupport/themes/genericunix/qgenericunixthemes_p.h
+++ b/src/platformsupport/themes/genericunix/qgenericunixthemes_p.h
@@ -75,8 +75,8 @@ public:
     static QPlatformTheme *createUnixTheme(const QString &name);
     static QStringList themeNames();
 
-    virtual const QFont *font(Font type) const Q_DECL_OVERRIDE;
-    virtual QVariant themeHint(ThemeHint hint) const Q_DECL_OVERRIDE;
+    const QFont *font(Font type) const Q_DECL_OVERRIDE;
+    QVariant themeHint(ThemeHint hint) const Q_DECL_OVERRIDE;
 
     static QStringList xdgIconThemePaths();
 #if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON)
@@ -96,11 +96,11 @@ public:
     QKdeTheme(const QStringList& kdeDirs, int kdeVersion);
 
     static QPlatformTheme *createKdeTheme();
-    virtual QVariant themeHint(ThemeHint hint) const Q_DECL_OVERRIDE;
+    QVariant themeHint(ThemeHint hint) const Q_DECL_OVERRIDE;
 
-    virtual const QPalette *palette(Palette type = SystemPalette) const Q_DECL_OVERRIDE;
+    const QPalette *palette(Palette type = SystemPalette) const Q_DECL_OVERRIDE;
 
-    virtual const QFont *font(Font type) const Q_DECL_OVERRIDE;
+    const QFont *font(Font type) const Q_DECL_OVERRIDE;
 #if !defined(QT_NO_DBUS) && !defined(QT_NO_SYSTEMTRAYICON)
     QPlatformSystemTrayIcon *createPlatformSystemTrayIcon() const Q_DECL_OVERRIDE;
 #endif
@@ -116,8 +116,8 @@ class QGnomeTheme : public QPlatformTheme
     Q_DECLARE_PRIVATE(QGnomeTheme)
 public:
     QGnomeTheme();
-    virtual QVariant themeHint(ThemeHint hint) const Q_DECL_OVERRIDE;
-    virtual const QFont *font(Font type) const Q_DECL_OVERRIDE;
+    QVariant themeHint(ThemeHint hint) const Q_DECL_OVERRIDE;
+    const QFont *font(Font type) const Q_DECL_OVERRIDE;
     QString standardButtonText(int button) const Q_DECL_OVERRIDE;
 
     virtual QString gtkFontName() const;
diff --git a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
index 4126456f90296d32bf682a9a49246666c661a8a2..44f1d7e6bab2d0407e71bcd2b0958d6ba5a1b67a 100644
--- a/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
+++ b/src/plugins/platforminputcontexts/compose/generator/qtablegenerator.cpp
@@ -273,7 +273,7 @@ QString TableGenerator::findComposeFile()
     // check if user’s home directory has a file named .XCompose
     if (cleanState()) {
         QString path = qgetenv("HOME") + QStringLiteral("/.XCompose");
-        if (QFile(path).exists())
+        if (QFile::exists(path))
             return path;
     }
 
@@ -286,7 +286,7 @@ QString TableGenerator::findComposeFile()
                 m_state = UnsupportedLocale;
             else {
                 QString path = QDir(systemComposeDir()).filePath(table);
-                if (QFile(path).exists())
+                if (QFile::exists(path))
                     return path;
             }
         }
@@ -308,7 +308,7 @@ bool TableGenerator::findSystemComposeDir()
     bool found = false;
     for (int i = 0; i < m_possibleLocations.size(); ++i) {
         QString path = m_possibleLocations.at(i);
-        if (QFile(path + QLatin1String("/compose.dir")).exists()) {
+        if (QFile::exists(path + QLatin1String("/compose.dir"))) {
             m_systemComposeDir = path;
             found = true;
             break;
diff --git a/src/plugins/platforms/android/androidjnimain.cpp b/src/plugins/platforms/android/androidjnimain.cpp
index dd9154f8d2fc57e879fe0062fdb55e07b6e8d25a..ac37e7bd92ac09029e587a56c065f9200c88277a 100644
--- a/src/plugins/platforms/android/androidjnimain.cpp
+++ b/src/plugins/platforms/android/androidjnimain.cpp
@@ -356,6 +356,15 @@ namespace QtAndroid
         return surfaceId;
     }
 
+    void setViewVisibility(jobject view, bool visible)
+    {
+        QJNIObjectPrivate::callStaticMethod<void>(m_applicationClass,
+                                                  "setViewVisibility",
+                                                  "(Landroid/view/View;Z)V",
+                                                  view,
+                                                  visible);
+    }
+
     void setSurfaceGeometry(int surfaceId, const QRect &geometry)
     {
         if (surfaceId == -1)
diff --git a/src/plugins/platforms/android/androidjnimain.h b/src/plugins/platforms/android/androidjnimain.h
index cdedeb38f8e415114f0308aa2f99ecc00fd64e6e..037a070516478ebf106fdd16c86d40a2ba4d4b34 100644
--- a/src/plugins/platforms/android/androidjnimain.h
+++ b/src/plugins/platforms/android/androidjnimain.h
@@ -62,6 +62,7 @@ namespace QtAndroid
 
     int createSurface(AndroidSurfaceClient * client, const QRect &geometry, bool onTop, int imageDepth);
     int insertNativeView(jobject view, const QRect &geometry);
+    void setViewVisibility(jobject view, bool visible);
     void setSurfaceGeometry(int surfaceId, const QRect &geometry);
     void destroySurface(int surfaceId);
     void bringChildToFront(int surfaceId);
diff --git a/src/plugins/platforms/android/qandroidplatformforeignwindow.cpp b/src/plugins/platforms/android/qandroidplatformforeignwindow.cpp
index 315a0faac0f0aa29ce17dc24aec0b16749024c1d..03927dbe5ae02c5af46a885f8f78ecc46cf4366d 100644
--- a/src/plugins/platforms/android/qandroidplatformforeignwindow.cpp
+++ b/src/plugins/platforms/android/qandroidplatformforeignwindow.cpp
@@ -45,10 +45,14 @@ QAndroidPlatformForeignWindow::QAndroidPlatformForeignWindow(QWindow *window)
 {
     const WId wId = window->property("_q_foreignWinId").value<WId>();
     m_view = reinterpret_cast<jobject>(wId);
+    if (m_view.isValid())
+        QtAndroid::setViewVisibility(m_view.object(), false);
 }
 
 QAndroidPlatformForeignWindow::~QAndroidPlatformForeignWindow()
 {
+    if (m_view.isValid())
+        QtAndroid::setViewVisibility(m_view.object(), false);
     if (m_surfaceId != -1)
         QtAndroid::destroySurface(m_surfaceId);
 }
@@ -84,8 +88,9 @@ void QAndroidPlatformForeignWindow::setVisible(bool visible)
     if (!m_view.isValid())
         return;
 
-    QAndroidPlatformWindow::setVisible(visible);
+    QtAndroid::setViewVisibility(m_view.object(), visible);
 
+    QAndroidPlatformWindow::setVisible(visible);
     if (!visible && m_surfaceId != -1) {
         QtAndroid::destroySurface(m_surfaceId);
         m_surfaceId = -1;
diff --git a/src/plugins/platforms/android/qandroidplatformtheme.cpp b/src/plugins/platforms/android/qandroidplatformtheme.cpp
index 5531910555c33f6b0f17b991bec2ea7261f34a0f..d53d678bcf850b6f996e935d4f99124f59129d89 100644
--- a/src/plugins/platforms/android/qandroidplatformtheme.cpp
+++ b/src/plugins/platforms/android/qandroidplatformtheme.cpp
@@ -195,7 +195,7 @@ QJsonObject AndroidStyle::loadStyleData()
     }
     Q_ASSERT(!stylePath.isEmpty());
 
-    if (!androidTheme.isEmpty() && QFileInfo(stylePath + androidTheme + QLatin1String("style.json")).exists())
+    if (!androidTheme.isEmpty() && QFileInfo::exists(stylePath + androidTheme + QLatin1String("style.json")))
         stylePath += androidTheme;
 
     QFile f(stylePath + QLatin1String("style.json"));
diff --git a/src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm b/src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm
index b55393c7dc493362ac01a09b0e67f24fc5a3d358..608a7583c020c66480ac000ac4b591616e7df795 100644
--- a/src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm
+++ b/src/plugins/platforms/cocoa/qcocoaaccessibilityelement.mm
@@ -44,11 +44,11 @@ QT_USE_NAMESPACE
 
 #ifndef QT_NO_ACCESSIBILITY
 
-static void convertLineOffset(QAccessibleTextInterface *text, int &line, int &offset, NSUInteger *start = 0, NSUInteger *end = 0)
+static void convertLineOffset(QAccessibleTextInterface *text, int *line, int *offset, NSUInteger *start = 0, NSUInteger *end = 0)
 {
-    Q_ASSERT(line == -1 || offset == -1);
-    Q_ASSERT(line != -1 || offset != -1);
-    Q_ASSERT(offset <= text->characterCount());
+    Q_ASSERT(*line == -1 || *offset == -1);
+    Q_ASSERT(*line != -1 || *offset != -1);
+    Q_ASSERT(*offset <= text->characterCount());
 
     int curLine = -1;
     int curStart = 0, curEnd = 0;
@@ -75,14 +75,14 @@ static void convertLineOffset(QAccessibleTextInterface *text, int &line, int &of
             if (nextEnd == curEnd)
                 ++curEnd;
         }
-    } while ((line == -1 || curLine < line) && (offset == -1 || (curEnd <= offset)) && curEnd <= text->characterCount());
+    } while ((*line == -1 || curLine < *line) && (*offset == -1 || (curEnd <= *offset)) && curEnd <= text->characterCount());
 
     curEnd = qMin(curEnd, text->characterCount());
 
-    if (line == -1)
-        line = curLine;
-    if (offset == -1)
-        offset = curStart;
+    if (*line == -1)
+        *line = curLine;
+    if (*offset == -1)
+        *offset = curStart;
 
     Q_ASSERT(curStart >= 0);
     Q_ASSERT(curEnd >= 0);
@@ -338,7 +338,7 @@ static void convertLineOffset(QAccessibleTextInterface *text, int &line, int &of
         if (QAccessibleTextInterface *text = iface->textInterface()) {
             int line = -1;
             int position = text->cursorPosition();
-            convertLineOffset(text, line, position);
+            convertLineOffset(text, &line, &position);
             return [NSNumber numberWithInt: line];
         }
         return nil;
@@ -397,7 +397,7 @@ static void convertLineOffset(QAccessibleTextInterface *text, int &line, int &of
         if (index < 0 || index > iface->textInterface()->characterCount())
             return nil;
         int line = -1;
-        convertLineOffset(iface->textInterface(), line, index);
+        convertLineOffset(iface->textInterface(), &line, &index);
         return [NSNumber numberWithInt:line];
     }
     if ([attribute isEqualToString: NSAccessibilityRangeForLineParameterizedAttribute]) {
@@ -407,7 +407,7 @@ static void convertLineOffset(QAccessibleTextInterface *text, int &line, int &of
         int lineOffset = -1;
         NSUInteger startOffset = 0;
         NSUInteger endOffset = 0;
-        convertLineOffset(iface->textInterface(), line, lineOffset, &startOffset, &endOffset);
+        convertLineOffset(iface->textInterface(), &line, &lineOffset, &startOffset, &endOffset);
         return [NSValue valueWithRange:NSMakeRange(startOffset, endOffset - startOffset)];
     }
     if ([attribute isEqualToString: NSAccessibilityBoundsForRangeParameterizedAttribute]) {
diff --git a/src/plugins/platforms/cocoa/qcocoadrag.mm b/src/plugins/platforms/cocoa/qcocoadrag.mm
index 8aa7a6b583d1bdc943bcae9cf692459416e5120e..80006ae9b850840adcbcfe66c63a0d417af1ced0 100644
--- a/src/plugins/platforms/cocoa/qcocoadrag.mm
+++ b/src/plugins/platforms/cocoa/qcocoadrag.mm
@@ -120,7 +120,9 @@ Qt::DropAction QCocoaDrag::drag(QDrag *o)
 
     QPoint hotSpot = m_drag->hotSpot();
     QPixmap pm = dragPixmap(m_drag, hotSpot);
+    QSize pmDeviceIndependentSize = pm.size() / pm.devicePixelRatio();
     NSImage *nsimage = qt_mac_create_nsimage(pm);
+    [nsimage setSize : qt_mac_toNSSize(pmDeviceIndependentSize)];
 
     QMacPasteboard dragBoard((CFStringRef) NSDragPboard, QMacInternalPasteboardMime::MIME_DND);
     m_drag->mimeData()->setData(QLatin1String("application/x-qt-mime-type-name"), QByteArray("dummy"));
@@ -130,7 +132,7 @@ Qt::DropAction QCocoaDrag::drag(QDrag *o)
     NSWindow *theWindow = [m_lastEvent window];
     Q_ASSERT(theWindow != nil);
     event_location.x -= hotSpot.x();
-    CGFloat flippedY = pm.height() - hotSpot.y();
+    CGFloat flippedY = pmDeviceIndependentSize.height() - hotSpot.y();
     event_location.y -= flippedY;
     NSSize mouseOffset_unused = NSMakeSize(0.0, 0.0);
     NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
diff --git a/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm b/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
index a3ffb5be66d69709b855b00e45e51a0e62289452..8152c57ffd80f09a5c6c5fdcd01f5cfd2c2233fa 100644
--- a/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
+++ b/src/plugins/platforms/cocoa/qcocoasystemtrayicon.mm
@@ -198,7 +198,7 @@ void QCocoaSystemTrayIcon::updateIcon(const QIcon &icon)
     // current OS X versions is 22 points. Provide some future-proofing
     // by deriving the icon height from the menu height.
     const int padding = 4;
-    const int menuHeight = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
+    const int menuHeight = [[NSStatusBar systemStatusBar] thickness];
     const int maxImageHeight = menuHeight - padding;
 
     // Select pixmap based on the device pixel height. Ideally we would use
diff --git a/src/plugins/platforms/cocoa/qcocoawindow.mm b/src/plugins/platforms/cocoa/qcocoawindow.mm
index 3b5909a37e2dcba426e30078a0c8f7d28b3e9586..00cb43c9405ab47753bd831b9598ad5a88bdb153 100644
--- a/src/plugins/platforms/cocoa/qcocoawindow.mm
+++ b/src/plugins/platforms/cocoa/qcocoawindow.mm
@@ -1775,6 +1775,18 @@ void QCocoaWindow::exposeWindow()
     if (!isWindowExposable())
         return;
 
+    // Update the QWindow's screen property. This property is set
+    // to QGuiApplication::primaryScreen() at QWindow construciton
+    // time, and we won't get a NSWindowDidChangeScreenNotification
+    // on show. The case where the window is initially displayed
+    // on a non-primary screen needs special handling here.
+    NSUInteger screenIndex = [[NSScreen screens] indexOfObject:m_nsWindow.screen];
+    if (screenIndex != NSNotFound) {
+        QCocoaScreen *cocoaScreen = QCocoaIntegration::instance()->screenAtIndex(screenIndex);
+        if (cocoaScreen)
+            window()->setScreen(cocoaScreen->screen());
+    }
+
     if (!m_isExposed) {
         m_isExposed = true;
         m_exposedGeometry = geometry();
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h b/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h
index 1c7f65a12da112ee465517d09926f4fb4321c3ab..08bfaa1240c3915b000960d7b7f12a4f2588551d 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dbackingstore.h
@@ -48,8 +48,8 @@ public:
     QWindowsDirect2DBackingStore(QWindow *window);
     ~QWindowsDirect2DBackingStore();
 
-    void beginPaint(const QRegion &);
-    void endPaint();
+    void beginPaint(const QRegion &) Q_DECL_OVERRIDE;
+    void endPaint() Q_DECL_OVERRIDE;
 
     QPaintDevice *paintDevice() Q_DECL_OVERRIDE;
     void flush(QWindow *targetWindow, const QRegion &region, const QPoint &offset) Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/direct2d/qwindowsdirect2dplatformpixmap.h b/src/plugins/platforms/direct2d/qwindowsdirect2dplatformpixmap.h
index 5720f84853c8a8e5cf4d656e23de35271193232c..a9591a493aa988931dfec2066c685cfd887b011b 100644
--- a/src/plugins/platforms/direct2d/qwindowsdirect2dplatformpixmap.h
+++ b/src/plugins/platforms/direct2d/qwindowsdirect2dplatformpixmap.h
@@ -54,8 +54,7 @@ public:
     ~QWindowsDirect2DPlatformPixmap();
 
     void resize(int width, int height) Q_DECL_OVERRIDE;
-    virtual void fromImage(const QImage &image,
-                           Qt::ImageConversionFlags flags);
+    void fromImage(const QImage &image, Qt::ImageConversionFlags flags) Q_DECL_OVERRIDE;
 
     int metric(QPaintDevice::PaintDeviceMetric metric) const Q_DECL_OVERRIDE;
     void fill(const QColor &color) Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/eglfs/qeglfscontext.cpp b/src/plugins/platforms/eglfs/qeglfscontext.cpp
index 6fcdae7ad21c14100993623be2dd1fa220f265c3..db35338423e8e3496190bb2bad7b4e467fef381a 100644
--- a/src/plugins/platforms/eglfs/qeglfscontext.cpp
+++ b/src/plugins/platforms/eglfs/qeglfscontext.cpp
@@ -85,6 +85,16 @@ void QEglFSContext::destroyTemporaryOffscreenSurface(EGLSurface surface)
     }
 }
 
+void QEglFSContext::runGLChecks()
+{
+    // Note that even though there is an EGL context current here,
+    // QOpenGLContext and QOpenGLFunctions are not yet usable at this stage.
+    const char *renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
+    // Be nice and warn about a common source of confusion.
+    if (renderer && strstr(renderer, "llvmpipe"))
+        qWarning("Running on a software rasterizer (LLVMpipe), expect limited performance.");
+}
+
 void QEglFSContext::swapBuffers(QPlatformSurface *surface)
 {
     // draw the cursor
diff --git a/src/plugins/platforms/eglfs/qeglfscontext.h b/src/plugins/platforms/eglfs/qeglfscontext.h
index 612960dc242b4ad973f0a946276834271e1d5bcb..906d11b3d1b08f24c4059b95a8d14e909c0cc459 100644
--- a/src/plugins/platforms/eglfs/qeglfscontext.h
+++ b/src/plugins/platforms/eglfs/qeglfscontext.h
@@ -48,6 +48,7 @@ public:
     EGLSurface eglSurfaceForPlatformSurface(QPlatformSurface *surface) Q_DECL_OVERRIDE;
     EGLSurface createTemporaryOffscreenSurface() Q_DECL_OVERRIDE;
     void destroyTemporaryOffscreenSurface(EGLSurface surface) Q_DECL_OVERRIDE;
+    void runGLChecks() Q_DECL_OVERRIDE;
     void swapBuffers(QPlatformSurface *surface) Q_DECL_OVERRIDE;
 
 private:
diff --git a/src/plugins/platforms/mirclient/mirclient.pro b/src/plugins/platforms/mirclient/mirclient.pro
index 033ce579b92c24c498cf5b688e5c5394de5cc476..0851e8d71926fcb4628983391313d2d49376896d 100644
--- a/src/plugins/platforms/mirclient/mirclient.pro
+++ b/src/plugins/platforms/mirclient/mirclient.pro
@@ -21,6 +21,7 @@ PKGCONFIG += egl mirclient ubuntu-platform-api
 SOURCES = \
     qmirclientbackingstore.cpp \
     qmirclientclipboard.cpp \
+    qmirclientcursor.cpp \
     qmirclientglcontext.cpp \
     qmirclientinput.cpp \
     qmirclientintegration.cpp \
@@ -34,6 +35,7 @@ SOURCES = \
 HEADERS = \
     qmirclientbackingstore.h \
     qmirclientclipboard.h \
+    qmirclientcursor.h \
     qmirclientglcontext.h \
     qmirclientinput.h \
     qmirclientintegration.h \
diff --git a/src/plugins/platforms/mirclient/qmirclientclipboard.cpp b/src/plugins/platforms/mirclient/qmirclientclipboard.cpp
index aa2ddf2103791a3e1c1e557dd2f249ee77082391..53246f66c0c4bec93bf2c515b2ab31f82a09ee28 100644
--- a/src/plugins/platforms/mirclient/qmirclientclipboard.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientclipboard.cpp
@@ -87,12 +87,12 @@ void QMirClientClipboard::requestDBusClipboardContents()
     if (!mPendingGetContentsCall.isNull())
         return;
 
-    QDBusPendingCall pendingCall = mDBusClipboard->asyncCall("GetContents");
+    QDBusPendingCall pendingCall = mDBusClipboard->asyncCall(QStringLiteral("GetContents"));
 
     mPendingGetContentsCall = new QDBusPendingCallWatcher(pendingCall, this);
 
-    QObject::connect(mPendingGetContentsCall.data(), SIGNAL(finished(QDBusPendingCallWatcher*)),
-                     this, SLOT(onDBusClipboardGetContentsFinished(QDBusPendingCallWatcher*)));
+    QObject::connect(mPendingGetContentsCall.data(), &QDBusPendingCallWatcher::finished,
+                     this, &QMirClientClipboard::onDBusClipboardGetContentsFinished);
 }
 
 void QMirClientClipboard::onDBusClipboardGetContentsFinished(QDBusPendingCallWatcher* call)
@@ -143,18 +143,18 @@ void QMirClientClipboard::setupDBus()
     QDBusConnection dbusConnection = QDBusConnection::sessionBus();
 
     bool ok = dbusConnection.connect(
-            "com.canonical.QtMir",
-            "/com/canonical/QtMir/Clipboard",
-            "com.canonical.QtMir.Clipboard",
-            "ContentsChanged",
+            QStringLiteral("com.canonical.QtMir"),
+            QStringLiteral("/com/canonical/QtMir/Clipboard"),
+            QStringLiteral("com.canonical.QtMir.Clipboard"),
+            QStringLiteral("ContentsChanged"),
             this, SLOT(updateMimeData(QByteArray)));
     if (!ok) {
         qCritical("QMirClientClipboard - Failed to connect to ContentsChanged signal form the D-Bus system clipboard.");
     }
 
-    mDBusClipboard = new QDBusInterface("com.canonical.QtMir",
-            "/com/canonical/QtMir/Clipboard",
-            "com.canonical.QtMir.Clipboard",
+    mDBusClipboard = new QDBusInterface(QStringLiteral("com.canonical.QtMir"),
+            QStringLiteral("/com/canonical/QtMir/Clipboard"),
+            QStringLiteral("com.canonical.QtMir.Clipboard"),
             dbusConnection);
 
     mDBusSetupDone = true;
@@ -162,6 +162,8 @@ void QMirClientClipboard::setupDBus()
 
 QByteArray QMirClientClipboard::serializeMimeData(QMimeData *mimeData) const
 {
+    Q_ASSERT(mimeData != nullptr);
+
     const QStringList formats = mimeData->formats();
     const int formatCount = qMin(formats.size(), maxFormatsCount);
     const int headerSize = sizeof(int) + (formatCount * 4 * sizeof(int));
@@ -180,12 +182,13 @@ QByteArray QMirClientClipboard::serializeMimeData(QMimeData *mimeData) const
             int offset = headerSize;
             header[0] = formatCount;
             for (int i = 0; i < formatCount; i++) {
+                const QByteArray data = mimeData->data(formats[i]);
                 const int formatOffset = offset;
                 const int formatSize = formats[i].size();
                 const int dataOffset = offset + formatSize;
-                const int dataSize = mimeData->data(formats[i]).size();
+                const int dataSize = data.size();
                 memcpy(&buffer[formatOffset], formats[i].toLatin1().data(), formatSize);
-                memcpy(&buffer[dataOffset], mimeData->data(formats[i]).data(), dataSize);
+                memcpy(&buffer[dataOffset], data.data(), dataSize);
                 header[i*4+1] = formatOffset;
                 header[i*4+2] = formatSize;
                 header[i*4+3] = dataOffset;
@@ -265,13 +268,15 @@ void QMirClientClipboard::setMimeData(QMimeData* mimeData, QClipboard::Mode mode
         delete mPendingGetContentsCall.data();
     }
 
-    QByteArray serializedMimeData = serializeMimeData(mimeData);
-    if (!serializedMimeData.isEmpty()) {
-        setDBusClipboardContents(serializedMimeData);
-    }
+    if (mimeData != nullptr) {
+        QByteArray serializedMimeData = serializeMimeData(mimeData);
+        if (!serializedMimeData.isEmpty()) {
+            setDBusClipboardContents(serializedMimeData);
+        }
 
-    mMimeData = mimeData;
-    emitChanged(QClipboard::Clipboard);
+        mMimeData = mimeData;
+        emitChanged(QClipboard::Clipboard);
+    }
 }
 
 bool QMirClientClipboard::supportsMode(QClipboard::Mode mode) const
@@ -287,6 +292,10 @@ bool QMirClientClipboard::ownsMode(QClipboard::Mode mode) const
 
 void QMirClientClipboard::setDBusClipboardContents(const QByteArray &clipboardContents)
 {
+    if (!mDBusSetupDone) {
+        setupDBus();
+    }
+
     if (!mPendingSetContentsCall.isNull()) {
         // Ignore any previous set call as we are going to overwrite it anyway
         QObject::disconnect(mPendingSetContentsCall.data(), 0, this, 0);
@@ -296,10 +305,10 @@ void QMirClientClipboard::setDBusClipboardContents(const QByteArray &clipboardCo
         delete mPendingSetContentsCall.data();
     }
 
-    QDBusPendingCall pendingCall = mDBusClipboard->asyncCall("SetContents", clipboardContents);
+    QDBusPendingCall pendingCall = mDBusClipboard->asyncCall(QStringLiteral("SetContents"), clipboardContents);
 
     mPendingSetContentsCall = new QDBusPendingCallWatcher(pendingCall, this);
 
-    QObject::connect(mPendingSetContentsCall.data(), SIGNAL(finished(QDBusPendingCallWatcher*)),
-                     this, SLOT(onDBusClipboardSetContentsFinished(QDBusPendingCallWatcher*)));
+    QObject::connect(mPendingSetContentsCall.data(), &QDBusPendingCallWatcher::finished,
+                     this, &QMirClientClipboard::onDBusClipboardSetContentsFinished);
 }
diff --git a/src/plugins/platforms/mirclient/qmirclientcursor.cpp b/src/plugins/platforms/mirclient/qmirclientcursor.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1d6ec8391e72203999ac228ee0fe7b61e51355fd
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientcursor.cpp
@@ -0,0 +1,201 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software 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 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later 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 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#include "qmirclientcursor.h"
+
+#include "qmirclientlogging.h"
+#include "qmirclientwindow.h"
+
+#include <mir_toolkit/mir_client_library.h>
+
+QMirClientCursor::QMirClientCursor(MirConnection *connection)
+    : mConnection(connection)
+{
+    mShapeToCursorName[Qt::ArrowCursor] = "left_ptr";
+    mShapeToCursorName[Qt::UpArrowCursor] = "up_arrow";
+    mShapeToCursorName[Qt::CrossCursor] = "cross";
+    mShapeToCursorName[Qt::WaitCursor] = "watch";
+    mShapeToCursorName[Qt::IBeamCursor] = "xterm";
+    mShapeToCursorName[Qt::SizeVerCursor] = "size_ver";
+    mShapeToCursorName[Qt::SizeHorCursor] = "size_hor";
+    mShapeToCursorName[Qt::SizeBDiagCursor] = "size_bdiag";
+    mShapeToCursorName[Qt::SizeFDiagCursor] = "size_fdiag";
+    mShapeToCursorName[Qt::SizeAllCursor] = "size_all";
+    mShapeToCursorName[Qt::BlankCursor] = "blank";
+    mShapeToCursorName[Qt::SplitVCursor] = "split_v";
+    mShapeToCursorName[Qt::SplitHCursor] = "split_h";
+    mShapeToCursorName[Qt::PointingHandCursor] = "hand";
+    mShapeToCursorName[Qt::ForbiddenCursor] = "forbidden";
+    mShapeToCursorName[Qt::WhatsThisCursor] = "whats_this";
+    mShapeToCursorName[Qt::BusyCursor] = "left_ptr_watch";
+    mShapeToCursorName[Qt::OpenHandCursor] = "openhand";
+    mShapeToCursorName[Qt::ClosedHandCursor] = "closedhand";
+    mShapeToCursorName[Qt::DragCopyCursor] = "dnd-copy";
+    mShapeToCursorName[Qt::DragMoveCursor] = "dnd-move";
+    mShapeToCursorName[Qt::DragLinkCursor] = "dnd-link";
+}
+
+namespace {
+#if !defined(QT_NO_DEBUG)
+const char *qtCursorShapeToStr(Qt::CursorShape shape)
+{
+    switch (shape) {
+    case Qt::ArrowCursor:
+        return "Arrow";
+    case Qt::UpArrowCursor:
+        return "UpArrow";
+    case Qt::CrossCursor:
+        return "Cross";
+    case Qt::WaitCursor:
+        return "Wait";
+    case Qt::IBeamCursor:
+        return "IBeam";
+    case Qt::SizeVerCursor:
+        return "SizeVer";
+    case Qt::SizeHorCursor:
+        return "SizeHor";
+    case Qt::SizeBDiagCursor:
+        return "SizeBDiag";
+    case Qt::SizeFDiagCursor:
+        return "SizeFDiag";
+    case Qt::SizeAllCursor:
+        return "SizeAll";
+    case Qt::BlankCursor:
+        return "Blank";
+    case Qt::SplitVCursor:
+        return "SplitV";
+    case Qt::SplitHCursor:
+        return "SplitH";
+    case Qt::PointingHandCursor:
+        return "PointingHand";
+    case Qt::ForbiddenCursor:
+        return "Forbidden";
+    case Qt::WhatsThisCursor:
+        return "WhatsThis";
+    case Qt::BusyCursor:
+        return "Busy";
+    case Qt::OpenHandCursor:
+        return "OpenHand";
+    case Qt::ClosedHandCursor:
+        return "ClosedHand";
+    case Qt::DragCopyCursor:
+        return "DragCopy";
+    case Qt::DragMoveCursor:
+        return "DragMove";
+    case Qt::DragLinkCursor:
+        return "DragLink";
+    case Qt::BitmapCursor:
+        return "Bitmap";
+    default:
+        return "???";
+    }
+}
+#endif // !defined(QT_NO_DEBUG)
+} // anonymous namespace
+
+void QMirClientCursor::changeCursor(QCursor *windowCursor, QWindow *window)
+{
+    if (!window) {
+        return;
+    }
+
+    MirSurface *surface = static_cast<QMirClientWindow*>(window->handle())->mirSurface();
+
+    if (!surface) {
+        return;
+    }
+
+
+    if (windowCursor) {
+        DLOG("[ubuntumirclient QPA] changeCursor shape=%s, window=%p\n", qtCursorShapeToStr(windowCursor->shape()), window);
+        if (!windowCursor->pixmap().isNull()) {
+            configureMirCursorWithPixmapQCursor(surface, *windowCursor);
+        } else if (windowCursor->shape() == Qt::BitmapCursor) {
+            // TODO: Implement bitmap cursor support
+            applyDefaultCursorConfiguration(surface);
+        } else {
+            const auto &cursorName = mShapeToCursorName.value(windowCursor->shape(), QByteArray("left_ptr"));
+            auto cursorConfiguration = mir_cursor_configuration_from_name(cursorName.data());
+            mir_surface_configure_cursor(surface, cursorConfiguration);
+            mir_cursor_configuration_destroy(cursorConfiguration);
+        }
+    } else {
+        applyDefaultCursorConfiguration(surface);
+    }
+
+}
+
+void QMirClientCursor::configureMirCursorWithPixmapQCursor(MirSurface *surface, QCursor &cursor)
+{
+    QImage image = cursor.pixmap().toImage();
+
+    if (image.format() != QImage::Format_ARGB32) {
+        image.convertToFormat(QImage::Format_ARGB32);
+    }
+
+    MirBufferStream *bufferStream = mir_connection_create_buffer_stream_sync(mConnection,
+            image.width(), image.height(), mir_pixel_format_argb_8888, mir_buffer_usage_software);
+
+    {
+        MirGraphicsRegion region;
+        mir_buffer_stream_get_graphics_region(bufferStream, &region);
+
+        char *regionLine = region.vaddr;
+        Q_ASSERT(image.bytesPerLine() <= region.stride);
+        for (int i = 0; i < image.height(); ++i) {
+            memcpy(regionLine, image.scanLine(i), image.bytesPerLine());
+            regionLine += region.stride;
+        }
+    }
+
+    mir_buffer_stream_swap_buffers_sync(bufferStream);
+
+    {
+        auto configuration = mir_cursor_configuration_from_buffer_stream(bufferStream, cursor.hotSpot().x(), cursor.hotSpot().y());
+        mir_surface_configure_cursor(surface, configuration);
+        mir_cursor_configuration_destroy(configuration);
+    }
+
+    mir_buffer_stream_release_sync(bufferStream);
+}
+
+void QMirClientCursor::applyDefaultCursorConfiguration(MirSurface *surface)
+{
+    auto cursorConfiguration = mir_cursor_configuration_from_name("left_ptr");
+    mir_surface_configure_cursor(surface, cursorConfiguration);
+    mir_cursor_configuration_destroy(cursorConfiguration);
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientcursor.h b/src/plugins/platforms/mirclient/qmirclientcursor.h
new file mode 100644
index 0000000000000000000000000000000000000000..8bb151ddda3d053986542a37fb29bc191c5f6707
--- /dev/null
+++ b/src/plugins/platforms/mirclient/qmirclientcursor.h
@@ -0,0 +1,61 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Canonical, Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL3$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software 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 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPLv3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or later 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 2.0 requirements will be
+** met: http://www.gnu.org/licenses/gpl-2.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+
+#ifndef QMIRCLIENTCURSOR_H
+#define QMIRCLIENTCURSOR_H
+
+#include <qpa/qplatformcursor.h>
+
+#include <QMap>
+#include <QByteArray>
+
+struct MirConnection;
+struct MirSurface;
+
+class QMirClientCursor : public QPlatformCursor
+{
+public:
+    QMirClientCursor(MirConnection *connection);
+    void changeCursor(QCursor *windowCursor, QWindow *window) override;
+private:
+    void configureMirCursorWithPixmapQCursor(MirSurface *surface, QCursor &cursor);
+    void applyDefaultCursorConfiguration(MirSurface *surface);
+    QMap<int, QByteArray> mShapeToCursorName;
+    MirConnection *mConnection;
+};
+
+#endif // QMIRCLIENTCURSOR_H
diff --git a/src/plugins/platforms/mirclient/qmirclientglcontext.cpp b/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
index bfba5051e55f4b13e608dfaa52d951bfe70fac0e..01db3b8d61c26f8bc76d360c8a5eed17b5f4e4ed 100644
--- a/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientglcontext.cpp
@@ -130,19 +130,7 @@ void QMirClientOpenGLContext::swapBuffers(QPlatformSurface* surface)
     ASSERT(eglSwapBuffers(mEglDisplay, eglSurface) == EGL_TRUE);
 #endif
 
-    // "Technique" copied from mir, in examples/eglapp.c around line 96
-    EGLint newBufferWidth = -1;
-    EGLint newBufferHeight = -1;
-    /*
-     * Querying the surface (actually the current buffer) dimensions here is
-     * the only truly safe way to be sure that the dimensions we think we
-     * have are those of the buffer being rendered to. But this should be
-     * improved in future; https://bugs.launchpad.net/mir/+bug/1194384
-     */
-    eglQuerySurface(mEglDisplay, eglSurface, EGL_WIDTH, &newBufferWidth);
-    eglQuerySurface(mEglDisplay, eglSurface, EGL_HEIGHT, &newBufferHeight);
-
-    ubuntuWindow->onBuffersSwapped_threadSafe(newBufferWidth, newBufferHeight);
+    ubuntuWindow->onSwapBuffersDone();
 }
 
 void (*QMirClientOpenGLContext::getProcAddress(const QByteArray& procName)) ()
diff --git a/src/plugins/platforms/mirclient/qmirclientglcontext.h b/src/plugins/platforms/mirclient/qmirclientglcontext.h
index cc402982597a3989ef00ba23ad3743b5d2067f7e..29c196ce5cc7fb910946d6f0b0583d5b275a57e2 100644
--- a/src/plugins/platforms/mirclient/qmirclientglcontext.h
+++ b/src/plugins/platforms/mirclient/qmirclientglcontext.h
@@ -53,7 +53,7 @@ public:
     bool makeCurrent(QPlatformSurface* surface) override;
     void doneCurrent() override;
     bool isValid() const override { return mEglContext != EGL_NO_CONTEXT; }
-    void (*getProcAddress(const QByteArray& procName)) ();
+    void (*getProcAddress(const QByteArray& procName)) () override;
 
     EGLContext eglContext() const { return mEglContext; }
 
diff --git a/src/plugins/platforms/mirclient/qmirclientinput.cpp b/src/plugins/platforms/mirclient/qmirclientinput.cpp
index 56bc21f420d2d4a157e80ecfad38b19bdc91ec8b..addeda634cac9ac0482948c3cf8a791516bab8a1 100644
--- a/src/plugins/platforms/mirclient/qmirclientinput.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientinput.cpp
@@ -163,6 +163,7 @@ QMirClientInput::QMirClientInput(QMirClientClientIntegration* integration)
     , mEventFilterType(static_cast<QMirClientNativeInterface*>(
         integration->nativeInterface())->genericEventFilterType())
     , mEventType(static_cast<QEvent::Type>(QEvent::registerEventType()))
+    , mLastFocusedWindow(nullptr)
 {
     // Initialize touch device.
     mTouchDevice = new QTouchDevice;
@@ -234,7 +235,7 @@ void QMirClientInput::customEvent(QEvent* event)
     switch (mir_event_get_type(nativeEvent))
     {
     case mir_event_type_input:
-        dispatchInputEvent(ubuntuEvent->window->window(), mir_event_get_input_event(nativeEvent));
+        dispatchInputEvent(ubuntuEvent->window, mir_event_get_input_event(nativeEvent));
         break;
     case mir_event_type_resize:
     {
@@ -246,7 +247,7 @@ void QMirClientInput::customEvent(QEvent* event)
                 mir_resize_event_get_width(resizeEvent),
                 mir_resize_event_get_height(resizeEvent));
 
-        ubuntuEvent->window->handleSurfaceResize(mir_resize_event_get_width(resizeEvent),
+        ubuntuEvent->window->handleSurfaceResized(mir_resize_event_get_width(resizeEvent),
             mir_resize_event_get_height(resizeEvent));
         break;
     }
@@ -254,8 +255,24 @@ void QMirClientInput::customEvent(QEvent* event)
     {
         auto surfaceEvent = mir_event_get_surface_event(nativeEvent);
         if (mir_surface_event_get_attribute(surfaceEvent) == mir_surface_attrib_focus) {
-            ubuntuEvent->window->handleSurfaceFocusChange(mir_surface_event_get_attribute_value(surfaceEvent) ==
-                mir_surface_focused);
+            const bool focused = mir_surface_event_get_attribute_value(surfaceEvent) == mir_surface_focused;
+            // Mir may have sent a pair of focus lost/gained events, so we need to "peek" into the queue
+            // so that we don't deactivate windows prematurely.
+            if (focused) {
+                mPendingFocusGainedEvents--;
+                ubuntuEvent->window->handleSurfaceFocused();
+                QWindowSystemInterface::handleWindowActivated(ubuntuEvent->window->window(), Qt::ActiveWindowFocusReason);
+
+                // NB: Since processing of system events is queued, never check qGuiApp->applicationState()
+                //     as it might be outdated. Always call handleApplicationStateChanged() with the latest
+                //     state regardless.
+                QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationActive);
+
+            } else if (!mPendingFocusGainedEvents) {
+                DLOG("[ubuntumirclient QPA] No windows have focus");
+                QWindowSystemInterface::handleWindowActivated(nullptr, Qt::ActiveWindowFocusReason);
+                QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationInactive);
+            }
         }
         break;
     }
@@ -274,6 +291,17 @@ void QMirClientInput::postEvent(QMirClientWindow *platformWindow, const MirEvent
 {
     QWindow *window = platformWindow->window();
 
+    const auto eventType = mir_event_get_type(event);
+    if (mir_event_type_surface == eventType) {
+        auto surfaceEvent = mir_event_get_surface_event(event);
+        if (mir_surface_attrib_focus == mir_surface_event_get_attribute(surfaceEvent)) {
+            const bool focused = mir_surface_event_get_attribute_value(surfaceEvent) == mir_surface_focused;
+            if (focused) {
+                mPendingFocusGainedEvents++;
+            }
+        }
+    }
+
     QCoreApplication::postEvent(this, new QMirClientEvent(
             platformWindow, event, mEventType));
 
@@ -284,7 +312,7 @@ void QMirClientInput::postEvent(QMirClientWindow *platformWindow, const MirEvent
     }
 }
 
-void QMirClientInput::dispatchInputEvent(QWindow *window, const MirInputEvent *ev)
+void QMirClientInput::dispatchInputEvent(QMirClientWindow *window, const MirInputEvent *ev)
 {
     switch (mir_input_event_get_type(ev))
     {
@@ -302,7 +330,7 @@ void QMirClientInput::dispatchInputEvent(QWindow *window, const MirInputEvent *e
     }
 }
 
-void QMirClientInput::dispatchTouchEvent(QWindow *window, const MirInputEvent *ev)
+void QMirClientInput::dispatchTouchEvent(QMirClientWindow *window, const MirInputEvent *ev)
 {
     const MirTouchEvent *tev = mir_input_event_get_touch_event(ev);
 
@@ -333,6 +361,7 @@ void QMirClientInput::dispatchTouchEvent(QWindow *window, const MirInputEvent *e
         switch (touch_action)
         {
         case mir_touch_action_down:
+            mLastFocusedWindow = window;
             touchPoint.state = Qt::TouchPointPressed;
             break;
         case mir_touch_action_up:
@@ -347,7 +376,7 @@ void QMirClientInput::dispatchTouchEvent(QWindow *window, const MirInputEvent *e
     }
 
     ulong timestamp = mir_input_event_get_event_time(ev) / 1000000;
-    QWindowSystemInterface::handleTouchEvent(window, timestamp,
+    QWindowSystemInterface::handleTouchEvent(window->window(), timestamp,
             mTouchDevice, touchPoints);
 }
 
@@ -390,7 +419,7 @@ Qt::KeyboardModifiers qt_modifiers_from_mir(MirInputEventModifiers modifiers)
 }
 }
 
-void QMirClientInput::dispatchKeyEvent(QWindow *window, const MirInputEvent *event)
+void QMirClientInput::dispatchKeyEvent(QMirClientWindow *window, const MirInputEvent *event)
 {
     const MirKeyboardEvent *key_event = mir_input_event_get_keyboard_event(event);
 
@@ -404,6 +433,9 @@ void QMirClientInput::dispatchKeyEvent(QWindow *window, const MirInputEvent *eve
     QEvent::Type keyType = action == mir_keyboard_action_up
         ? QEvent::KeyRelease : QEvent::KeyPress;
 
+    if (action == mir_keyboard_action_down)
+        mLastFocusedWindow = window;
+
     char s[2];
     int sym = translateKeysym(xk_sym, s, sizeof(s));
     QString text = QString::fromLatin1(s);
@@ -420,7 +452,7 @@ void QMirClientInput::dispatchKeyEvent(QWindow *window, const MirInputEvent *eve
         }
     }
 
-    QWindowSystemInterface::handleKeyEvent(window, timestamp, keyType, sym, modifiers, text, is_auto_rep);
+    QWindowSystemInterface::handleKeyEvent(window->window(), timestamp, keyType, sym, modifiers, text, is_auto_rep);
 }
 
 namespace
@@ -433,27 +465,54 @@ Qt::MouseButtons extract_buttons(const MirPointerEvent *pev)
     if (mir_pointer_event_button_state(pev, mir_pointer_button_secondary))
         buttons |= Qt::RightButton;
     if (mir_pointer_event_button_state(pev, mir_pointer_button_tertiary))
-        buttons |= Qt::MidButton;
+        buttons |= Qt::MiddleButton;
+    if (mir_pointer_event_button_state(pev, mir_pointer_button_back))
+        buttons |= Qt::BackButton;
+    if (mir_pointer_event_button_state(pev, mir_pointer_button_forward))
+        buttons |= Qt::ForwardButton;
 
-    // TODO: Should mir back and forward buttons exist?
-    // should they be Qt::X button 1 and 2?
     return buttons;
 }
 }
 
-void QMirClientInput::dispatchPointerEvent(QWindow *window, const MirInputEvent *ev)
+void QMirClientInput::dispatchPointerEvent(QMirClientWindow *platformWindow, const MirInputEvent *ev)
 {
+    auto window = platformWindow->window();
     auto timestamp = mir_input_event_get_event_time(ev) / 1000000;
 
     auto pev = mir_input_event_get_pointer_event(ev);
+    auto action = mir_pointer_event_action(pev);
+    auto localPoint = QPointF(mir_pointer_event_axis_value(pev, mir_pointer_axis_x),
+                              mir_pointer_event_axis_value(pev, mir_pointer_axis_y));
     auto modifiers = qt_modifiers_from_mir(mir_pointer_event_modifiers(pev));
-    auto buttons = extract_buttons(pev);
 
-    auto local_point = QPointF(mir_pointer_event_axis_value(pev, mir_pointer_axis_x),
-                               mir_pointer_event_axis_value(pev, mir_pointer_axis_y));
+    switch (action) {
+    case mir_pointer_action_button_up:
+    case mir_pointer_action_button_down:
+    case mir_pointer_action_motion:
+    {
+        const float hDelta = mir_pointer_event_axis_value(pev, mir_pointer_axis_hscroll);
+        const float vDelta = mir_pointer_event_axis_value(pev, mir_pointer_axis_vscroll);
 
-    QWindowSystemInterface::handleMouseEvent(window, timestamp, local_point, local_point /* Should we omit global point instead? */,
-                                             buttons, modifiers);
+        if (hDelta != 0 || vDelta != 0) {
+            const QPoint angleDelta = QPoint(hDelta * 15, vDelta * 15);
+            QWindowSystemInterface::handleWheelEvent(window, timestamp, localPoint, window->position() + localPoint,
+                                                     QPoint(), angleDelta, modifiers, Qt::ScrollUpdate);
+        }
+        auto buttons = extract_buttons(pev);
+        QWindowSystemInterface::handleMouseEvent(window, timestamp, localPoint, window->position() + localPoint /* Should we omit global point instead? */,
+                                                 buttons, modifiers);
+        break;
+    }
+    case mir_pointer_action_enter:
+        QWindowSystemInterface::handleEnterEvent(window, localPoint, window->position() + localPoint);
+        break;
+    case mir_pointer_action_leave:
+        QWindowSystemInterface::handleLeaveEvent(window);
+        break;
+    default:
+        DLOG("Unrecognized pointer event");
+    }
 }
 
 #if (LOG_EVENTS != 0)
diff --git a/src/plugins/platforms/mirclient/qmirclientinput.h b/src/plugins/platforms/mirclient/qmirclientinput.h
index c987d18c1296cce01b56a709ed35fc559ea1e122..3ed887419edc257e81a06e71e445227c172e64b2 100644
--- a/src/plugins/platforms/mirclient/qmirclientinput.h
+++ b/src/plugins/platforms/mirclient/qmirclientinput.h
@@ -40,6 +40,7 @@
 
 // Qt
 #include <qpa/qwindowsysteminterface.h>
+#include <QAtomicInt>
 
 #include <mir_toolkit/mir_client_library.h>
 
@@ -59,12 +60,13 @@ public:
 
     void postEvent(QMirClientWindow* window, const MirEvent *event);
     QMirClientClientIntegration* integration() const { return mIntegration; }
+    QMirClientWindow *lastFocusedWindow() const {return mLastFocusedWindow; }
 
 protected:
-    void dispatchKeyEvent(QWindow *window, const MirInputEvent *event);
-    void dispatchPointerEvent(QWindow *window, const MirInputEvent *event);
-    void dispatchTouchEvent(QWindow *window, const MirInputEvent *event);
-    void dispatchInputEvent(QWindow *window, const MirInputEvent *event);
+    void dispatchKeyEvent(QMirClientWindow *window, const MirInputEvent *event);
+    void dispatchPointerEvent(QMirClientWindow *window, const MirInputEvent *event);
+    void dispatchTouchEvent(QMirClientWindow *window, const MirInputEvent *event);
+    void dispatchInputEvent(QMirClientWindow *window, const MirInputEvent *event);
 
     void dispatchOrientationEvent(QWindow* window, const MirOrientationEvent *event);
 
@@ -73,6 +75,9 @@ private:
     QTouchDevice* mTouchDevice;
     const QByteArray mEventFilterType;
     const QEvent::Type mEventType;
+
+    QMirClientWindow *mLastFocusedWindow;
+    QAtomicInt mPendingFocusGainedEvents;
 };
 
 #endif // QMIRCLIENTINPUT_H
diff --git a/src/plugins/platforms/mirclient/qmirclientintegration.cpp b/src/plugins/platforms/mirclient/qmirclientintegration.cpp
index a234f4eac6ba79fd54b7c22c8104dba07fd721a3..4b2572ce0d8e2598c087ec5fdf382ef0984394e8 100644
--- a/src/plugins/platforms/mirclient/qmirclientintegration.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientintegration.cpp
@@ -35,28 +35,28 @@
 ****************************************************************************/
 
 
-// Qt
-#include <QGuiApplication>
-#include <private/qguiapplication_p.h>
-#include <qpa/qplatformnativeinterface.h>
-#include <qpa/qplatforminputcontextfactory_p.h>
-#include <qpa/qplatforminputcontext.h>
-#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
-#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
-#include <QOpenGLContext>
-
 // Local
+#include "qmirclientintegration.h"
 #include "qmirclientbackingstore.h"
 #include "qmirclientclipboard.h"
 #include "qmirclientglcontext.h"
 #include "qmirclientinput.h"
-#include "qmirclientintegration.h"
 #include "qmirclientlogging.h"
 #include "qmirclientnativeinterface.h"
 #include "qmirclientscreen.h"
 #include "qmirclienttheme.h"
 #include "qmirclientwindow.h"
 
+// Qt
+#include <QGuiApplication>
+#include <private/qguiapplication_p.h>
+#include <qpa/qplatformnativeinterface.h>
+#include <qpa/qplatforminputcontextfactory_p.h>
+#include <qpa/qplatforminputcontext.h>
+#include <QtPlatformSupport/private/qgenericunixfontdatabase_p.h>
+#include <QtPlatformSupport/private/qgenericunixeventdispatcher_p.h>
+#include <QOpenGLContext>
+
 // platform-api
 #include <ubuntu/application/lifecycle_delegate.h>
 #include <ubuntu/application/id.h>
@@ -67,8 +67,11 @@ static void resumedCallback(const UApplicationOptions *options, void* context)
     Q_UNUSED(options)
     Q_UNUSED(context)
     DASSERT(context != NULL);
-    QCoreApplication::postEvent(QCoreApplication::instance(),
-                                new QEvent(QEvent::ApplicationActivate));
+    if (qGuiApp->focusWindow()) {
+        QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationActive);
+    } else {
+        QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationInactive);
+    }
 }
 
 static void aboutToStopCallback(UApplicationArchive *archive, void* context)
@@ -76,9 +79,13 @@ static void aboutToStopCallback(UApplicationArchive *archive, void* context)
     Q_UNUSED(archive)
     DASSERT(context != NULL);
     QMirClientClientIntegration* integration = static_cast<QMirClientClientIntegration*>(context);
-    integration->inputContext()->hideInputPanel();
-    QCoreApplication::postEvent(QCoreApplication::instance(),
-                                new QEvent(QEvent::ApplicationDeactivate));
+    QPlatformInputContext *inputContext = integration->inputContext();
+    if (inputContext) {
+        inputContext->hideInputPanel();
+    } else {
+        qWarning("QMirClientClientIntegration aboutToStopCallback(): no input context");
+    }
+    QWindowSystemInterface::handleApplicationStateChanged(Qt::ApplicationSuspended);
 }
 
 QMirClientClientIntegration::QMirClientClientIntegration()
@@ -100,6 +107,8 @@ QMirClientClientIntegration::QMirClientClientIntegration()
                "running, and the correct socket is being used and is accessible. The shell may have\n"
                "rejected the incoming connection, so check its log file");
 
+    mNativeInterface->setMirConnection(u_application_instance_get_mir_connection(mInstance));
+
     // Create default screen.
     mScreen = new QMirClientScreen(u_application_instance_get_mir_connection(mInstance));
     screenAdded(mScreen);
@@ -176,10 +185,8 @@ QPlatformWindow* QMirClientClientIntegration::createPlatformWindow(QWindow* wind
 
 QPlatformWindow* QMirClientClientIntegration::createPlatformWindow(QWindow* window)
 {
-    QPlatformWindow* platformWindow = new QMirClientWindow(
-            window, mClipboard, static_cast<QMirClientScreen*>(mScreen), mInput, u_application_instance_get_mir_connection(mInstance));
-    platformWindow->requestActivateWindow();
-    return platformWindow;
+    return new QMirClientWindow(window, mClipboard, static_cast<QMirClientScreen*>(mScreen),
+                            mInput, u_application_instance_get_mir_connection(mInstance));
 }
 
 bool QMirClientClientIntegration::hasCapability(QPlatformIntegration::Capability cap) const
@@ -187,11 +194,12 @@ bool QMirClientClientIntegration::hasCapability(QPlatformIntegration::Capability
     switch (cap) {
     case ThreadedPixmaps:
         return true;
-        break;
 
     case OpenGL:
         return true;
-        break;
+
+    case ApplicationState:
+        return true;
 
     case ThreadedOpenGL:
         if (qEnvironmentVariableIsEmpty("QTUBUNTU_NO_THREADED_OPENGL")) {
@@ -200,8 +208,9 @@ bool QMirClientClientIntegration::hasCapability(QPlatformIntegration::Capability
             DLOG("ubuntumirclient: disabled threaded OpenGL");
             return false;
         }
-        break;
-
+    case MultipleWindows:
+    case NonFullScreenWindows:
+        return true;
     default:
         return QPlatformIntegration::hasCapability(cap);
     }
@@ -262,3 +271,8 @@ QPlatformClipboard* QMirClientClientIntegration::clipboard() const
 {
     return mClipboard.data();
 }
+
+QPlatformNativeInterface* QMirClientClientIntegration::nativeInterface() const
+{
+    return mNativeInterface;
+}
diff --git a/src/plugins/platforms/mirclient/qmirclientintegration.h b/src/plugins/platforms/mirclient/qmirclientintegration.h
index 2960209691443212bcc23cb6a1f2a6094e4ea968..e41cbe2cee95ff2cd5318b7dc463a098b92f0c11 100644
--- a/src/plugins/platforms/mirclient/qmirclientintegration.h
+++ b/src/plugins/platforms/mirclient/qmirclientintegration.h
@@ -49,6 +49,7 @@
 
 class QMirClientClipboard;
 class QMirClientInput;
+class QMirClientNativeInterface;
 class QMirClientScreen;
 
 class QMirClientClientIntegration : public QPlatformIntegration {
@@ -59,7 +60,7 @@ public:
     // QPlatformIntegration methods.
     bool hasCapability(QPlatformIntegration::Capability cap) const override;
     QAbstractEventDispatcher *createEventDispatcher() const override;
-    QPlatformNativeInterface* nativeInterface() const override { return mNativeInterface; }
+    QPlatformNativeInterface* nativeInterface() const override;
     QPlatformBackingStore* createPlatformBackingStore(QWindow* window) const override;
     QPlatformOpenGLContext* createPlatformOpenGLContext(QOpenGLContext* context) const override;
     QPlatformFontDatabase* fontDatabase() const override { return mFontDb; }
@@ -79,7 +80,7 @@ private:
     void setupOptions();
     void setupDescription();
 
-    QPlatformNativeInterface* mNativeInterface;
+    QMirClientNativeInterface* mNativeInterface;
     QPlatformFontDatabase* mFontDb;
 
     QMirClientPlatformServices* mServices;
diff --git a/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp b/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp
index a0bb932df3c0c3925c2ab8b1245ae0f2b983e3f8..1b4c20153bc60f33ede772281fb111da0983492e 100644
--- a/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientnativeinterface.cpp
@@ -35,17 +35,17 @@
 ****************************************************************************/
 
 
+// Local
+#include "qmirclientnativeinterface.h"
+#include "qmirclientscreen.h"
+#include "qmirclientglcontext.h"
+
 // Qt
 #include <private/qguiapplication_p.h>
 #include <QtGui/qopenglcontext.h>
 #include <QtGui/qscreen.h>
 #include <QtCore/QMap>
 
-// Local
-#include "qmirclientnativeinterface.h"
-#include "qmirclientscreen.h"
-#include "qmirclientglcontext.h"
-
 class QMirClientResourceMap : public QMap<QByteArray, QMirClientNativeInterface::ResourceType>
 {
 public:
@@ -55,6 +55,7 @@ public:
         insert("eglcontext", QMirClientNativeInterface::EglContext);
         insert("nativeorientation", QMirClientNativeInterface::NativeOrientation);
         insert("display", QMirClientNativeInterface::Display);
+        insert("mirconnection", QMirClientNativeInterface::MirConnection);
     }
 };
 
@@ -63,6 +64,7 @@ Q_GLOBAL_STATIC(QMirClientResourceMap, ubuntuResourceMap)
 QMirClientNativeInterface::QMirClientNativeInterface()
     : mGenericEventFilterType(QByteArrayLiteral("Event"))
     , mNativeOrientation(nullptr)
+    , mMirConnection(nullptr)
 {
 }
 
@@ -72,6 +74,23 @@ QMirClientNativeInterface::~QMirClientNativeInterface()
     mNativeOrientation = nullptr;
 }
 
+void* QMirClientNativeInterface::nativeResourceForIntegration(const QByteArray &resourceString)
+{
+    const QByteArray lowerCaseResource = resourceString.toLower();
+
+    if (!ubuntuResourceMap()->contains(lowerCaseResource)) {
+        return nullptr;
+    }
+
+    const ResourceType resourceType = ubuntuResourceMap()->value(lowerCaseResource);
+
+    if (resourceType == QMirClientNativeInterface::MirConnection) {
+        return mMirConnection;
+    } else {
+        return nullptr;
+    }
+}
+
 void* QMirClientNativeInterface::nativeResourceForContext(
     const QByteArray& resourceString, QOpenGLContext* context)
 {
diff --git a/src/plugins/platforms/mirclient/qmirclientnativeinterface.h b/src/plugins/platforms/mirclient/qmirclientnativeinterface.h
index 84f03bb915c555783f214e69f8c404d628c57279..7df646e73a34d571a7573f6a8277858e96213cfa 100644
--- a/src/plugins/platforms/mirclient/qmirclientnativeinterface.h
+++ b/src/plugins/platforms/mirclient/qmirclientnativeinterface.h
@@ -42,12 +42,13 @@
 
 class QMirClientNativeInterface : public QPlatformNativeInterface {
 public:
-    enum ResourceType { EglDisplay, EglContext, NativeOrientation, Display };
+    enum ResourceType { EglDisplay, EglContext, NativeOrientation, Display, MirConnection };
 
     QMirClientNativeInterface();
     ~QMirClientNativeInterface();
 
     // QPlatformNativeInterface methods.
+    void* nativeResourceForIntegration(const QByteArray &resource) override;
     void* nativeResourceForContext(const QByteArray& resourceString,
                                    QOpenGLContext* context) override;
     void* nativeResourceForWindow(const QByteArray& resourceString,
@@ -57,10 +58,12 @@ public:
 
     // New methods.
     const QByteArray& genericEventFilterType() const { return mGenericEventFilterType; }
+    void setMirConnection(void *mirConnection) { mMirConnection = mirConnection; }
 
 private:
     const QByteArray mGenericEventFilterType;
     Qt::ScreenOrientation* mNativeOrientation;
+    void *mMirConnection;
 };
 
 #endif // QMIRCLIENTNATIVEINTERFACE_H
diff --git a/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h b/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h
index 24d7307faaab4260a38e517261ece6bd2b88c35c..2a1ed9c09f73b58e99edd7a506ee72475f0347e2 100644
--- a/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h
+++ b/src/plugins/platforms/mirclient/qmirclientorientationchangeevent_p.h
@@ -43,15 +43,7 @@
 
 class OrientationChangeEvent : public QEvent {
 public:
-    enum Orientation {
-        Undefined = 0,
-        TopUp,
-        TopDown,
-        LeftUp,
-        RightUp,
-        FaceUp,
-        FaceDown
-    };
+    enum Orientation { TopUp, LeftUp, TopDown, RightUp };
 
     OrientationChangeEvent(QEvent::Type type, Orientation orientation)
         : QEvent(type)
diff --git a/src/plugins/platforms/mirclient/qmirclientplugin.cpp b/src/plugins/platforms/mirclient/qmirclientplugin.cpp
index 203a1cbfd826566a0aafe2a337c84d2840fcae6b..75561f7fd3997638de1a39754f8d7aa90a9cc7d2 100644
--- a/src/plugins/platforms/mirclient/qmirclientplugin.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientplugin.cpp
@@ -41,14 +41,14 @@
 QStringList QMirClientIntegrationPlugin::keys() const
 {
     QStringList list;
-    list << "mirclient";
+    list << QStringLiteral("mirclient");
     return list;
 }
 
 QPlatformIntegration* QMirClientIntegrationPlugin::create(const QString &system,
                                                                const QStringList &)
 {
-    if (system.toLower() == "mirclient") {
+    if (system.toLower() == QLatin1String("mirclient")) {
         return new QMirClientClientIntegration;
     } else {
         return 0;
diff --git a/src/plugins/platforms/mirclient/qmirclientscreen.cpp b/src/plugins/platforms/mirclient/qmirclientscreen.cpp
index 5c4b1cd0d624f47aa07501f86b7dbd17eef5e8d8..3eb01f816a1a62542004f2b012f4b78a4bc35eb8 100644
--- a/src/plugins/platforms/mirclient/qmirclientscreen.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientscreen.cpp
@@ -1,6 +1,6 @@
 /****************************************************************************
 **
-** Copyright (C) 2014 Canonical, Ltd.
+** Copyright (C) 2014-2015 Canonical, Ltd.
 ** Contact: http://www.qt.io/licensing/
 **
 ** This file is part of the plugins of the Qt Toolkit.
@@ -35,6 +35,11 @@
 ****************************************************************************/
 
 
+// local
+#include "qmirclientscreen.h"
+#include "qmirclientlogging.h"
+#include "qmirclientorientationchangeevent_p.h"
+
 #include <mir_toolkit/mir_client_library.h>
 
 // Qt
@@ -45,12 +50,7 @@
 #include <qpa/qwindowsysteminterface.h>
 #include <QtPlatformSupport/private/qeglconvenience_p.h>
 
-// local
-#include "qmirclientscreen.h"
-#include "qmirclientlogging.h"
-#include "qmirclientorientationchangeevent_p.h"
-
-#include "memory"
+#include <memory>
 
 static const int kSwapInterval = 1;
 
@@ -149,9 +149,11 @@ static const MirDisplayOutput *find_active_output(
 QMirClientScreen::QMirClientScreen(MirConnection *connection)
     : mFormat(QImage::Format_RGB32)
     , mDepth(32)
+    , mOutputId(0)
     , mSurfaceFormat()
     , mEglDisplay(EGL_NO_DISPLAY)
     , mEglConfig(nullptr)
+    , mCursor(connection)
 {
     // Initialize EGL.
     ASSERT(eglBindAPI(EGL_OPENGL_ES_API) == EGL_TRUE);
@@ -203,6 +205,11 @@ QMirClientScreen::QMirClientScreen(MirConnection *connection)
     auto const displayOutput = find_active_output(displayConfig.get());
     ASSERT(displayOutput != nullptr);
 
+    mOutputId = displayOutput->output_id;
+
+    mPhysicalSize = QSizeF(displayOutput->physical_width_mm, displayOutput->physical_height_mm);
+    DLOG("ubuntumirclient: screen physical size: %.2fx%.2f", mPhysicalSize.width(), mPhysicalSize.height());
+
     const MirDisplayMode *mode = &displayOutput->modes[displayOutput->current_mode];
     const int kScreenWidth = mode->horizontal_resolution;
     const int kScreenHeight = mode->vertical_resolution;
diff --git a/src/plugins/platforms/mirclient/qmirclientscreen.h b/src/plugins/platforms/mirclient/qmirclientscreen.h
index 5d9325354f753c9705cefe94eda1486ed416a1a0..a6b4f442da26cfded9e68e19fed05405dec9e0ce 100644
--- a/src/plugins/platforms/mirclient/qmirclientscreen.h
+++ b/src/plugins/platforms/mirclient/qmirclientscreen.h
@@ -1,6 +1,6 @@
 /****************************************************************************
 **
-** Copyright (C) 2014 Canonical, Ltd.
+** Copyright (C) 2014-2015 Canonical, Ltd.
 ** Contact: http://www.qt.io/licensing/
 **
 ** This file is part of the plugins of the Qt Toolkit.
@@ -42,6 +42,8 @@
 #include <QSurfaceFormat>
 #include <EGL/egl.h>
 
+#include "qmirclientcursor.h"
+
 struct MirConnection;
 
 class QMirClientScreen : public QObject, public QPlatformScreen
@@ -56,8 +58,10 @@ public:
     int depth() const override { return mDepth; }
     QRect geometry() const override { return mGeometry; }
     QRect availableGeometry() const override { return mGeometry; }
+    QSizeF physicalSize() const override { return mPhysicalSize; }
     Qt::ScreenOrientation nativeOrientation() const override { return mNativeOrientation; }
     Qt::ScreenOrientation orientation() const override { return mNativeOrientation; }
+    QPlatformCursor *cursor() const override { return const_cast<QMirClientCursor*>(&mCursor); }
 
     // New methods.
     QSurfaceFormat surfaceFormat() const { return mSurfaceFormat; }
@@ -65,20 +69,24 @@ public:
     EGLConfig eglConfig() const { return mEglConfig; }
     EGLNativeDisplayType eglNativeDisplay() const { return mEglNativeDisplay; }
     void handleWindowSurfaceResize(int width, int height);
+    uint32_t mirOutputId() const { return mOutputId; }
 
     // QObject methods.
-    void customEvent(QEvent* event);
+    void customEvent(QEvent* event) override;
 
 private:
     QRect mGeometry;
+    QSizeF mPhysicalSize;
     Qt::ScreenOrientation mNativeOrientation;
     Qt::ScreenOrientation mCurrentOrientation;
     QImage::Format mFormat;
     int mDepth;
+    uint32_t mOutputId;
     QSurfaceFormat mSurfaceFormat;
     EGLDisplay mEglDisplay;
     EGLConfig mEglConfig;
     EGLNativeDisplayType mEglNativeDisplay;
+    QMirClientCursor mCursor;
 };
 
 #endif // QMIRCLIENTSCREEN_H
diff --git a/src/plugins/platforms/mirclient/qmirclientwindow.cpp b/src/plugins/platforms/mirclient/qmirclientwindow.cpp
index 3d1e5377e5cd9e3f4a0a52107f5efca97c1b3e7c..9a72c2f9dcfa7c3db9b974f7fe8a00d238a96450 100644
--- a/src/plugins/platforms/mirclient/qmirclientwindow.cpp
+++ b/src/plugins/platforms/mirclient/qmirclientwindow.cpp
@@ -36,16 +36,16 @@
 
 
 // Local
+#include "qmirclientwindow.h"
 #include "qmirclientclipboard.h"
 #include "qmirclientinput.h"
-#include "qmirclientwindow.h"
 #include "qmirclientscreen.h"
 #include "qmirclientlogging.h"
 
+#include <mir_toolkit/mir_client_library.h>
+
 // Qt
 #include <qpa/qwindowsysteminterface.h>
-#include <qpa/qwindowsysteminterface.h>
-#include <QMutex>
 #include <QMutexLocker>
 #include <QSize>
 #include <QtMath>
@@ -55,25 +55,46 @@
 
 #include <EGL/egl.h>
 
-#define IS_OPAQUE_FLAG 1
-
 namespace
 {
+
+// FIXME: this used to be defined by platform-api, but it's been removed in v3. Change ubuntu-keyboard to use
+// a different enum for window roles.
+enum UAUiWindowRole {
+    U_MAIN_ROLE = 1,
+    U_DASH_ROLE,
+    U_INDICATOR_ROLE,
+    U_NOTIFICATIONS_ROLE,
+    U_GREETER_ROLE,
+    U_LAUNCHER_ROLE,
+    U_ON_SCREEN_KEYBOARD_ROLE,
+    U_SHUTDOWN_DIALOG_ROLE,
+};
+
+struct MirSpecDeleter
+{
+    void operator()(MirSurfaceSpec *spec) { mir_surface_spec_release(spec); }
+};
+
+using Spec = std::unique_ptr<MirSurfaceSpec, MirSpecDeleter>;
+
+EGLNativeWindowType nativeWindowFor(MirSurface *surf)
+{
+    auto stream = mir_surface_get_buffer_stream(surf);
+    return reinterpret_cast<EGLNativeWindowType>(mir_buffer_stream_get_egl_native_window(stream));
+}
+
 MirSurfaceState qtWindowStateToMirSurfaceState(Qt::WindowState state)
 {
     switch (state) {
     case Qt::WindowNoState:
         return mir_surface_state_restored;
-
     case Qt::WindowFullScreen:
         return mir_surface_state_fullscreen;
-
     case Qt::WindowMaximized:
         return mir_surface_state_maximized;
-
     case Qt::WindowMinimized:
         return mir_surface_state_minimized;
-
     default:
         LOG("Unexpected Qt::WindowState: %d", state);
         return mir_surface_state_restored;
@@ -86,117 +107,137 @@ const char *qtWindowStateToStr(Qt::WindowState state)
     switch (state) {
     case Qt::WindowNoState:
         return "NoState";
-
     case Qt::WindowFullScreen:
         return "FullScreen";
-
     case Qt::WindowMaximized:
         return "Maximized";
-
     case Qt::WindowMinimized:
         return "Minimized";
-
     default:
         return "!?";
     }
 }
 #endif
 
-} // anonymous namespace
-
-class QMirClientWindowPrivate
+WId makeId()
 {
-public:
-    void createEGLSurface(EGLNativeWindowType nativeWindow);
-    void destroyEGLSurface();
-    int panelHeight();
-
-    QMirClientScreen* screen;
-    EGLSurface eglSurface;
-    WId id;
-    QMirClientInput* input;
-    Qt::WindowState state;
-    MirConnection *connection;
-    MirSurface* surface;
-    QSize bufferSize;
-    QMutex mutex;
-    QSharedPointer<QMirClientClipboard> clipboard;
-};
-
-static void eventCallback(MirSurface* surface, const MirEvent *event, void* context)
-{
-    (void) surface;
-    DASSERT(context != NULL);
-    QMirClientWindow* platformWindow = static_cast<QMirClientWindow*>(context);
-    platformWindow->priv()->input->postEvent(platformWindow, event);
+    static int id = 1;
+    return id++;
 }
 
-static void surfaceCreateCallback(MirSurface* surface, void* context)
+MirPixelFormat defaultPixelFormatFor(MirConnection *connection)
 {
-    DASSERT(context != NULL);
-    QMirClientWindow* platformWindow = static_cast<QMirClientWindow*>(context);
-    platformWindow->priv()->surface = surface;
-
-    mir_surface_set_event_handler(surface, eventCallback, context);
+    MirPixelFormat format;
+    unsigned int nformats;
+    mir_connection_get_available_surface_formats(connection, &format, 1, &nformats);
+    return format;
 }
 
-QMirClientWindow::QMirClientWindow(QWindow* w, QSharedPointer<QMirClientClipboard> clipboard, QMirClientScreen* screen,
-                           QMirClientInput* input, MirConnection* connection)
-    : QObject(nullptr), QPlatformWindow(w)
+UAUiWindowRole roleFor(QWindow *window)
 {
-    DASSERT(screen != NULL);
+    QVariant roleVariant = window->property("role");
+    if (!roleVariant.isValid())
+        return U_MAIN_ROLE;
 
-    d = new QMirClientWindowPrivate;
-    d->screen = screen;
-    d->eglSurface = EGL_NO_SURFACE;
-    d->input = input;
-    d->state = window()->windowState();
-    d->connection = connection;
-    d->clipboard = clipboard;
+    uint role = roleVariant.toUInt();
+    if (role < U_MAIN_ROLE || role > U_SHUTDOWN_DIALOG_ROLE)
+        return U_MAIN_ROLE;
 
-    static int id = 1;
-    d->id = id++;
-
-    // Use client geometry if set explicitly, use available screen geometry otherwise.
-    QPlatformWindow::setGeometry(window()->geometry().isValid() &&  window()->geometry() != screen->geometry() ?
-        window()->geometry() : screen->availableGeometry());
-    createWindow();
-    DLOG("QMirClientWindow::QMirClientWindow (this=%p, w=%p, screen=%p, input=%p)", this, w, screen, input);
+    return static_cast<UAUiWindowRole>(role);
 }
 
-QMirClientWindow::~QMirClientWindow()
+QMirClientWindow *transientParentFor(QWindow *window)
 {
-    DLOG("QMirClientWindow::~QMirClientWindow");
-    d->destroyEGLSurface();
-
-    mir_surface_release_sync(d->surface);
-
-    delete d;
+    QWindow *parent = window->transientParent();
+    return parent ? static_cast<QMirClientWindow *>(parent->handle()) : nullptr;
 }
 
-void QMirClientWindowPrivate::createEGLSurface(EGLNativeWindowType nativeWindow)
+Spec makeSurfaceSpec(QWindow *window, QMirClientInput *input, MirConnection *connection)
 {
-  DLOG("QMirClientWindowPrivate::createEGLSurface (this=%p, nativeWindow=%p)",
-          this, reinterpret_cast<void*>(nativeWindow));
-
-  eglSurface = eglCreateWindowSurface(screen->eglDisplay(), screen->eglConfig(),
-          nativeWindow, nullptr);
+   const auto geom = window->geometry();
+   const int width = geom.width() > 0 ? geom.width() : 1;
+   const int height = geom.height() > 0 ? geom.height() : 1;
+   const auto pixelFormat = defaultPixelFormatFor(connection);
+
+   if (U_ON_SCREEN_KEYBOARD_ROLE == roleFor(window)) {
+       DLOG("[ubuntumirclient QPA] makeSurfaceSpec(window=%p) - creating input method surface (width=%d, height=%d", window, width, height);
+       return Spec{mir_connection_create_spec_for_input_method(connection, width, height, pixelFormat)};
+   }
+
+   const Qt::WindowType type = window->type();
+   if (type == Qt::Popup) {
+       auto parent = transientParentFor(window);
+       if (parent == nullptr) {
+           //NOTE: We cannot have a parentless popup -
+           //try using the last surface to receive input as that will most likely be
+           //the one that caused this popup to be created
+           parent = input->lastFocusedWindow();
+       }
+       if (parent) {
+           auto pos = geom.topLeft();
+           pos -= parent->geometry().topLeft();
+           MirRectangle location{pos.x(), pos.y(), 0, 0};
+           DLOG("[ubuntumirclient QPA] makeSurfaceSpec(window=%p) - creating menu surface(width:%d, height:%d)", window, width, height);
+           return Spec{mir_connection_create_spec_for_menu(
+                       connection, width, height, pixelFormat, parent->mirSurface(),
+                       &location, mir_edge_attachment_any)};
+       } else {
+           DLOG("[ubuntumirclient QPA] makeSurfaceSpec(window=%p) - cannot create a menu without a parent!", window);
+       }
+   } else if (type == Qt::Dialog) {
+       auto parent = transientParentFor(window);
+       if (parent) {
+           // Modal dialog
+           DLOG("[ubuntumirclient QPA] makeSurfaceSpec(window=%p) - creating modal dialog (width=%d, height=%d", window, width, height);
+           return Spec{mir_connection_create_spec_for_modal_dialog(connection, width, height, pixelFormat, parent->mirSurface())};
+       } else {
+           // TODO: do Qt parentless dialogs have the same semantics as mir?
+           DLOG("[ubuntumirclient QPA] makeSurfaceSpec(window=%p) - creating parentless dialog (width=%d, height=%d)", window, width, height);
+           return Spec{mir_connection_create_spec_for_dialog(connection, width, height, pixelFormat)};
+       }
+   }
+   DLOG("[ubuntumirclient QPA] makeSurfaceSpec(window=%p) - creating normal surface(type=0x%x, width=%d, height=%d)", window, type, width, height);
+   return Spec{mir_connection_create_spec_for_normal_surface(connection, width, height, pixelFormat)};
+}
 
-  DASSERT(eglSurface != EGL_NO_SURFACE);
+void setSizingConstraints(MirSurfaceSpec *spec, const QSize& minSize, const QSize& maxSize, const QSize& increment)
+{
+    mir_surface_spec_set_min_width(spec, minSize.width());
+    mir_surface_spec_set_min_height(spec, minSize.height());
+    if (maxSize.width() >= minSize.width()) {
+        mir_surface_spec_set_max_width(spec, maxSize.width());
+    }
+    if (maxSize.height() >= minSize.height()) {
+        mir_surface_spec_set_max_height(spec, maxSize.height());
+    }
+    if (increment.width() > 0) {
+        mir_surface_spec_set_width_increment(spec, increment.width());
+    }
+    if (increment.height() > 0) {
+        mir_surface_spec_set_height_increment(spec, increment.height());
+    }
 }
 
-void QMirClientWindowPrivate::destroyEGLSurface()
+MirSurface *createMirSurface(QWindow *window, QMirClientScreen *screen, QMirClientInput *input, MirConnection *connection)
 {
-    DLOG("QMirClientWindowPrivate::destroyEGLSurface (this=%p)", this);
-    if (eglSurface != EGL_NO_SURFACE) {
-        eglDestroySurface(screen->eglDisplay(), eglSurface);
-        eglSurface = EGL_NO_SURFACE;
+    auto spec = makeSurfaceSpec(window, input, connection);
+    const auto title = window->title().toUtf8();
+    mir_surface_spec_set_name(spec.get(), title.constData());
+
+    setSizingConstraints(spec.get(), window->minimumSize(), window->maximumSize(), window->sizeIncrement());
+
+    if (window->windowState() == Qt::WindowFullScreen) {
+        mir_surface_spec_set_fullscreen_on_output(spec.get(), screen->mirOutputId());
     }
+
+    auto surface = mir_surface_create_sync(spec.get());
+    Q_ASSERT(mir_surface_is_valid(surface));
+    return surface;
 }
 
 // FIXME - in order to work around https://bugs.launchpad.net/mir/+bug/1346633
-// we need to guess the panel height (3GU + 2DP)
-int QMirClientWindowPrivate::panelHeight()
+// we need to guess the panel height (3GU)
+int panelHeight()
 {
     if (qEnvironmentVariableIsSet("QT_MIRCLIENT_IGNORE_PANEL"))
         return 0;
@@ -210,245 +251,412 @@ int QMirClientWindowPrivate::panelHeight()
             gridUnit = defaultGridUnit;
         }
     }
-    qreal densityPixelRatio = static_cast<qreal>(gridUnit) / defaultGridUnit;
-    return gridUnit * 3 + qFloor(densityPixelRatio) * 2;
+    return gridUnit * 3;
 }
 
-namespace
+} //namespace
+
+class QMirClientSurface
 {
-static MirPixelFormat
-mir_choose_default_pixel_format(MirConnection *connection)
+public:
+    QMirClientSurface(QMirClientWindow *platformWindow, QMirClientScreen *screen, QMirClientInput *input, MirConnection *connection)
+        : mWindow(platformWindow->window())
+        , mPlatformWindow(platformWindow)
+        , mInput(input)
+        , mConnection(connection)
+        , mMirSurface(createMirSurface(mWindow, screen, input, connection))
+        , mEglDisplay(screen->eglDisplay())
+        , mEglSurface(eglCreateWindowSurface(mEglDisplay, screen->eglConfig(), nativeWindowFor(mMirSurface), nullptr))
+        , mVisible(false)
+        , mNeedsRepaint(false)
+        , mParented(mWindow->transientParent() || mWindow->parent())
+        , mWindowState(mWindow->windowState())
+
+    {
+        mir_surface_set_event_handler(mMirSurface, surfaceEventCallback, this);
+
+        // Window manager can give us a final size different from what we asked for
+        // so let's check what we ended up getting
+        MirSurfaceParameters parameters;
+        mir_surface_get_parameters(mMirSurface, &parameters);
+
+        auto geom = mWindow->geometry();
+        geom.setWidth(parameters.width);
+        geom.setHeight(parameters.height);
+        if (mWindowState == Qt::WindowFullScreen) {
+            geom.setY(0);
+        } else {
+            geom.setY(panelHeight());
+        }
+
+        // Assume that the buffer size matches the surface size at creation time
+        mBufferSize = geom.size();
+        platformWindow->QPlatformWindow::setGeometry(geom);
+        QWindowSystemInterface::handleGeometryChange(mWindow, geom);
+
+        DLOG("[ubuntumirclient QPA] created surface at (%d, %d) with size (%d, %d), title '%s', role: '%d'\n",
+             geom.x(), geom.y(), geom.width(), geom.height(), mWindow->title().toUtf8().constData(), roleFor(mWindow));
+    }
+
+    ~QMirClientSurface()
+    {
+        if (mEglSurface != EGL_NO_SURFACE)
+            eglDestroySurface(mEglDisplay, mEglSurface);
+        if (mMirSurface)
+            mir_surface_release_sync(mMirSurface);
+    }
+
+    QMirClientSurface(QMirClientSurface const&) = delete;
+    QMirClientSurface& operator=(QMirClientSurface const&) = delete;
+
+    void resize(const QSize& newSize);
+    void setState(Qt::WindowState newState);
+    void setVisible(bool state);
+    void updateTitle(const QString& title);
+    void setSizingConstraints(const QSize& minSize, const QSize& maxSize, const QSize& increment);
+
+    void onSwapBuffersDone();
+    void handleSurfaceResized(int width, int height);
+    int needsRepaint() const;
+
+    EGLSurface eglSurface() const { return mEglSurface; }
+    MirSurface *mirSurface() const { return mMirSurface; }
+
+private:
+    static void surfaceEventCallback(MirSurface* surface, const MirEvent *event, void* context);
+    void postEvent(const MirEvent *event);
+    void updateSurface();
+
+    QWindow * const mWindow;
+    QMirClientWindow * const mPlatformWindow;
+    QMirClientInput * const mInput;
+    MirConnection * const mConnection;
+
+    MirSurface * const mMirSurface;
+    const EGLDisplay mEglDisplay;
+    const EGLSurface mEglSurface;
+
+    bool mVisible;
+    bool mNeedsRepaint;
+    bool mParented;
+    Qt::WindowState mWindowState;
+    QSize mBufferSize;
+
+    QMutex mTargetSizeMutex;
+    QSize mTargetSize;
+};
+
+void QMirClientSurface::resize(const QSize& size)
 {
-    MirPixelFormat format[mir_pixel_formats];
-    unsigned int nformats;
+    DLOG("[ubuntumirclient QPA] resize(window=%p, width=%d, height=%d)", mWindow, size.width(), size.height());
+
+    if (mWindowState == Qt::WindowFullScreen || mWindowState == Qt::WindowMaximized) {
+        DLOG("[ubuntumirclient QPA] resize(window=%p) - not resizing, window is maximized or fullscreen", mWindow);
+        return;
+    }
 
-    mir_connection_get_available_surface_formats(connection,
-        format, mir_pixel_formats, &nformats);
+    if (size.isEmpty()) {
+        DLOG("[ubuntumirclient QPA] resize(window=%p) - not resizing, size is empty", mWindow);
+        return;
+    }
 
-    return format[0];
+    Spec spec{mir_connection_create_spec_for_changes(mConnection)};
+    mir_surface_spec_set_width(spec.get(), size.width());
+    mir_surface_spec_set_height(spec.get(), size.height());
+    mir_surface_apply_spec(mMirSurface, spec.get());
 }
+
+void QMirClientSurface::setState(Qt::WindowState newState)
+{
+    mir_wait_for(mir_surface_set_state(mMirSurface, qtWindowStateToMirSurfaceState(newState)));
+    mWindowState = newState;
 }
 
-void QMirClientWindow::createWindow()
+void QMirClientSurface::setVisible(bool visible)
 {
-    DLOG("QMirClientWindow::createWindow (this=%p)", this);
+    if (mVisible == visible)
+        return;
 
-    // FIXME: remove this remnant of an old platform-api enum - needs ubuntu-keyboard update
-    const int SCREEN_KEYBOARD_ROLE = 7;
-    // Get surface role and flags.
-    QVariant roleVariant = window()->property("role");
-    int role = roleVariant.isValid() ? roleVariant.toUInt() : 1;  // 1 is the default role for apps.
-    QVariant opaqueVariant = window()->property("opaque");
-    uint flags = opaqueVariant.isValid() ?
-        opaqueVariant.toUInt() ? static_cast<uint>(IS_OPAQUE_FLAG) : 0 : 0;
+    mVisible = visible;
 
-    // FIXME(loicm) Opaque flag is forced for now for non-system sessions (applications) for
-    //     performance reasons.
-    flags |= static_cast<uint>(IS_OPAQUE_FLAG);
+    if (mVisible)
+        updateSurface();
+
+    // TODO: Use the new mir_surface_state_hidden state instead of mir_surface_state_minimized.
+    //       Will have to change qtmir and unity8 for that.
+    const auto newState = visible ? qtWindowStateToMirSurfaceState(mWindowState) : mir_surface_state_minimized;
+    mir_wait_for(mir_surface_set_state(mMirSurface, newState));
+}
+
+void QMirClientSurface::updateTitle(const QString& newTitle)
+{
+    const auto title = newTitle.toUtf8();
+    Spec spec{mir_connection_create_spec_for_changes(mConnection)};
+    mir_surface_spec_set_name(spec.get(), title.constData());
+    mir_surface_apply_spec(mMirSurface, spec.get());
+}
 
-    const QByteArray title = (!window()->title().isNull()) ? window()->title().toUtf8() : "Window 1"; // legacy title
-    const int panelHeight = d->panelHeight();
+void QMirClientSurface::setSizingConstraints(const QSize& minSize, const QSize& maxSize, const QSize& increment)
+{
+    Spec spec{mir_connection_create_spec_for_changes(mConnection)};
+    ::setSizingConstraints(spec.get(), minSize, maxSize, increment);
+    mir_surface_apply_spec(mMirSurface, spec.get());
+}
+
+void QMirClientSurface::handleSurfaceResized(int width, int height)
+{
+    QMutexLocker lock(&mTargetSizeMutex);
+
+    // mir's resize event is mainly a signal that we need to redraw our content. We use the
+    // width/height as identifiers to figure out if this is the latest surface resize event
+    // that has posted, discarding any old ones. This avoids issuing too many redraw events.
+    // see TODO in postEvent as the ideal way we should handle this.
+    // The actual buffer size may or may have not changed at this point, so let the rendering
+    // thread drive the window geometry updates.
+    mNeedsRepaint = mTargetSize.width() == width && mTargetSize.height() == height;
+}
+
+int QMirClientSurface::needsRepaint() const
+{
+    if (mNeedsRepaint) {
+        if (mTargetSize != mBufferSize) {
+            //If the buffer hasn't changed yet, we need at least two redraws,
+            //once to get the new buffer size and propagate the geometry changes
+            //and the second to redraw the content at the new size
+            return 2;
+        } else {
+            // The buffer size has already been updated so we only need one redraw
+            // to render at the new size
+            return 1;
+        }
+    }
+    return 0;
+}
 
+void QMirClientSurface::onSwapBuffersDone()
+{
 #if !defined(QT_NO_DEBUG)
-    LOG("panelHeight: '%d'", panelHeight);
-    LOG("role: '%d'", role);
-    LOG("flags: '%s'", (flags & static_cast<uint>(1)) ? "Opaque" : "NotOpaque");
-    LOG("title: '%s'", title.constData());
+    static int sFrameNumber = 0;
+    ++sFrameNumber;
 #endif
 
-    // Get surface geometry.
-    QRect geometry;
-    if (d->state == Qt::WindowFullScreen) {
-        printf("QMirClientWindow - fullscreen geometry\n");
-        geometry = screen()->geometry();
-    } else if (d->state == Qt::WindowMaximized) {
-        printf("QMirClientWindow - maximized geometry\n");
-        geometry = screen()->availableGeometry();
-        /*
-         * FIXME: Autopilot relies on being able to convert coordinates relative of the window
-         * into absolute screen coordinates. Mir does not allow this, see bug lp:1346633
-         * Until there's a correct way to perform this transformation agreed, this horrible hack
-         * guesses the transformation heuristically.
-         *
-         * Assumption: this method only used on phone devices!
-         */
-        geometry.setY(panelHeight);
-    } else {
-        printf("QMirClientWindow - regular geometry\n");
-        geometry = this->geometry();
-        geometry.setY(panelHeight);
-    }
+    EGLint eglSurfaceWidth = -1;
+    EGLint eglSurfaceHeight = -1;
+    eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, &eglSurfaceWidth);
+    eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, &eglSurfaceHeight);
 
-    DLOG("[ubuntumirclient QPA] creating surface at (%d, %d) with size (%d, %d) with title '%s'\n",
-            geometry.x(), geometry.y(), geometry.width(), geometry.height(), title.data());
+    const bool validSize = eglSurfaceWidth > 0 && eglSurfaceHeight > 0;
 
-    MirSurfaceSpec *spec;
-    if (role == SCREEN_KEYBOARD_ROLE)
-    {
-        spec = mir_connection_create_spec_for_input_method(d->connection, geometry.width(),
-            geometry.height(), mir_choose_default_pixel_format(d->connection));
-    }
-    else
-    {
-        spec = mir_connection_create_spec_for_normal_surface(d->connection, geometry.width(),
-            geometry.height(), mir_choose_default_pixel_format(d->connection));
-    }
-    mir_surface_spec_set_name(spec, title.data());
+    if (validSize && (mBufferSize.width() != eglSurfaceWidth || mBufferSize.height() != eglSurfaceHeight)) {
 
-    // Create platform window
-    mir_wait_for(mir_surface_create(spec, surfaceCreateCallback, this));
-    mir_surface_spec_release(spec);
+        DLOG("[ubuntumirclient QPA] onSwapBuffersDone(window=%p) [%d] - size changed (%d, %d) => (%d, %d)",
+               mWindow, sFrameNumber, mBufferSize.width(), mBufferSize.height(), eglSurfaceWidth, eglSurfaceHeight);
 
-    DASSERT(d->surface != NULL);
-    d->createEGLSurface((EGLNativeWindowType)mir_buffer_stream_get_egl_native_window(mir_surface_get_buffer_stream(d->surface)));
+        mBufferSize.rwidth() = eglSurfaceWidth;
+        mBufferSize.rheight() = eglSurfaceHeight;
 
-    if (d->state == Qt::WindowFullScreen) {
-    // TODO: We could set this on creation once surface spec supports it (mps already up)
-        mir_wait_for(mir_surface_set_state(d->surface, mir_surface_state_fullscreen));
+        QRect newGeometry = mPlatformWindow->geometry();
+        newGeometry.setSize(mBufferSize);
+
+        mPlatformWindow->QPlatformWindow::setGeometry(newGeometry);
+        QWindowSystemInterface::handleGeometryChange(mWindow, newGeometry);
+    } else {
+#if 0
+        DLOG("[ubuntumirclient QPA] onSwapBuffersDone(window=%p) [%d] - buffer size (%d,%d)",
+               mWindow, sFrameNumber, mBufferSize.width(), mBufferSize.height());
+#endif
     }
+}
 
-    // Window manager can give us a final size different from what we asked for
-    // so let's check what we ended up getting
-    {
-        MirSurfaceParameters parameters;
-        mir_surface_get_parameters(d->surface, &parameters);
+void QMirClientSurface::surfaceEventCallback(MirSurface *surface, const MirEvent *event, void* context)
+{
+    Q_UNUSED(surface);
+    Q_ASSERT(context != nullptr);
 
-        geometry.setWidth(parameters.width);
-        geometry.setHeight(parameters.height);
-    }
+    auto s = static_cast<QMirClientSurface *>(context);
+    s->postEvent(event);
+}
 
-    DLOG("[ubuntumirclient QPA] created surface has size (%d, %d)",
-            geometry.width(), geometry.height());
+void QMirClientSurface::postEvent(const MirEvent *event)
+{
+    if (mir_event_type_resize == mir_event_get_type(event)) {
+        // TODO: The current event queue just accumulates all resize events;
+        // It would be nicer if we could update just one event if that event has not been dispatched.
+        // As a workaround, we use the width/height as an identifier of this latest event
+        // so the event handler (handleSurfaceResized) can discard/ignore old ones.
+        const auto resizeEvent = mir_event_get_resize_event(event);
+        const auto width =  mir_resize_event_get_width(resizeEvent);
+        const auto height =  mir_resize_event_get_height(resizeEvent);
+        DLOG("[ubuntumirclient QPA] resizeEvent(window=%p, width=%d, height=%d)", mWindow, width, height);
+
+        QMutexLocker lock(&mTargetSizeMutex);
+        mTargetSize.rwidth() = width;
+        mTargetSize.rheight() = height;
+    }
 
-    // Assume that the buffer size matches the surface size at creation time
-    d->bufferSize = geometry.size();
+    mInput->postEvent(mPlatformWindow, event);
+}
 
-    // Tell Qt about the geometry.
-    QWindowSystemInterface::handleGeometryChange(window(), geometry);
-    QPlatformWindow::setGeometry(geometry);
+void QMirClientSurface::updateSurface()
+{
+    DLOG("[ubuntumirclient QPA] updateSurface(window=%p)", mWindow);
+
+    if (!mParented && mWindow->type() == Qt::Dialog) {
+        // The dialog may have been parented after creation time
+        // so morph it into a modal dialog
+        auto parent = transientParentFor(mWindow);
+        if (parent) {
+            DLOG("[ubuntumirclient QPA] updateSurface(window=%p) dialog now parented", mWindow);
+            mParented = true;
+            Spec spec{mir_connection_create_spec_for_changes(mConnection)};
+            mir_surface_spec_set_parent(spec.get(), parent->mirSurface());
+            mir_surface_apply_spec(mMirSurface, spec.get());
+        }
+    }
 }
 
-void QMirClientWindow::moveResize(const QRect& rect)
+QMirClientWindow::QMirClientWindow(QWindow *w, const QSharedPointer<QMirClientClipboard> &clipboard, QMirClientScreen *screen,
+                           QMirClientInput *input, MirConnection *connection)
+    : QObject(nullptr)
+    , QPlatformWindow(w)
+    , mId(makeId())
+    , mClipboard(clipboard)
+    , mSurface(new QMirClientSurface{this, screen, input, connection})
 {
-    (void) rect;
-    // TODO: Not yet supported by mir.
+    DLOG("[ubuntumirclient QPA] QMirClientWindow(window=%p, screen=%p, input=%p, surf=%p)", w, screen, input, mSurface.get());
 }
 
-void QMirClientWindow::handleSurfaceResize(int width, int height)
+QMirClientWindow::~QMirClientWindow()
 {
-    QMutexLocker(&d->mutex);
-    LOG("QMirClientWindow::handleSurfaceResize(width=%d, height=%d)", width, height);
+    DLOG("[ubuntumirclient QPA] ~QMirClientWindow(window=%p)", this);
+}
 
-    // The current buffer size hasn't actually changed. so just render on it and swap
-    // buffers in the hope that the next buffer will match the surface size advertised
-    // in this event.
-    // But since this event is processed by a thread different from the one that swaps
-    // buffers, you can never know if this information is already outdated as there's
-    // no synchronicity whatsoever between the processing of resize events and the
-    // consumption of buffers.
-    if (d->bufferSize.width() != width || d->bufferSize.height() != height) {
-        QWindowSystemInterface::handleExposeEvent(window(), geometry());
-        QWindowSystemInterface::flushWindowSystemEvents();
+void QMirClientWindow::handleSurfaceResized(int width, int height)
+{
+    QMutexLocker lock(&mMutex);
+    DLOG("[ubuntumirclient QPA] handleSurfaceResize(window=%p, width=%d, height=%d)", window(), width, height);
+
+    mSurface->handleSurfaceResized(width, height);
+
+    // This resize event could have occurred just after the last buffer swap for this window.
+    // This means the client may still be holding a buffer with the older size. The first redraw call
+    // will then render at the old size. After swapping the client now will get a new buffer with the
+    // updated size but it still needs re-rendering so another redraw may be needed.
+    // A mir API to drop the currently held buffer would help here, so that we wouldn't have to redraw twice
+    auto const numRepaints = mSurface->needsRepaint();
+    DLOG("[ubuntumirclient QPA] handleSurfaceResize(window=%p) redraw %d times", window(), numRepaints);
+    for (int i = 0; i < numRepaints; i++) {
+        DLOG("[ubuntumirclient QPA] handleSurfaceResize(window=%p) repainting width=%d, height=%d", window(), geometry().size().width(), geometry().size().height());
+        QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
     }
 }
 
-void QMirClientWindow::handleSurfaceFocusChange(bool focused)
+void QMirClientWindow::handleSurfaceFocused()
 {
-    LOG("QMirClientWindow::handleSurfaceFocusChange(focused=%s)", focused ? "true" : "false");
-    QWindow *activatedWindow = focused ? window() : nullptr;
+    DLOG("[ubuntumirclient QPA] handleSurfaceFocused(window=%p)", window());
 
-    // System clipboard contents might have changed while this window was unfocused and wihtout
+    // System clipboard contents might have changed while this window was unfocused and without
     // this process getting notified about it because it might have been suspended (due to
     // application lifecycle policies), thus unable to listen to any changes notified through
     // D-Bus.
     // Therefore let's ensure we are up to date with the system clipboard now that we are getting
     // focused again.
-    if (focused) {
-        d->clipboard->requestDBusClipboardContents();
-    }
-
-    QWindowSystemInterface::handleWindowActivated(activatedWindow, Qt::ActiveWindowFocusReason);
+    mClipboard->requestDBusClipboardContents();
 }
 
 void QMirClientWindow::setWindowState(Qt::WindowState state)
 {
-    QMutexLocker(&d->mutex);
-    DLOG("QMirClientWindow::setWindowState (this=%p, %s)", this,  qtWindowStateToStr(state));
+    QMutexLocker lock(&mMutex);
+    DLOG("[ubuntumirclient QPA] setWindowState(window=%p, %s)", this, qtWindowStateToStr(state));
+    mSurface->setState(state);
 
-    if (state == d->state)
-        return;
+    updatePanelHeightHack(state);
+}
 
-    // TODO: Perhaps we should check if the states are applied?
-    mir_wait_for(mir_surface_set_state(d->surface, qtWindowStateToMirSurfaceState(state)));
-    d->state = state;
+/*
+    FIXME: Mir does not let clients know the position of their windows in the virtual
+    desktop space. So we have this ugly hack that assumes a phone situation where the
+    window is always on the top-left corner, right below the indicators panel if not
+    in fullscreen.
+ */
+void QMirClientWindow::updatePanelHeightHack(Qt::WindowState state)
+{
+    if (state == Qt::WindowFullScreen && geometry().y() != 0) {
+        QRect newGeometry = geometry();
+        newGeometry.setY(0);
+        QPlatformWindow::setGeometry(newGeometry);
+        QWindowSystemInterface::handleGeometryChange(window(), newGeometry);
+    } else if (geometry().y() == 0) {
+        QRect newGeometry = geometry();
+        newGeometry.setY(panelHeight());
+        QPlatformWindow::setGeometry(newGeometry);
+        QWindowSystemInterface::handleGeometryChange(window(), newGeometry);
+    }
 }
 
 void QMirClientWindow::setGeometry(const QRect& rect)
 {
-    DLOG("QMirClientWindow::setGeometry (this=%p)", this);
+    QMutexLocker lock(&mMutex);
+    DLOG("[ubuntumirclient QPA] setGeometry (window=%p, x=%d, y=%d, width=%d, height=%d)",
+           window(), rect.x(), rect.y(), rect.width(), rect.height());
 
-    bool doMoveResize;
+    //NOTE: mir surfaces cannot be moved by the client so ignore the topLeft coordinates
+    const auto newSize = rect.size();
+    auto newGeometry = geometry();
+    newGeometry.setSize(newSize);
+    QPlatformWindow::setGeometry(newGeometry);
 
-    {
-        QMutexLocker(&d->mutex);
-        QPlatformWindow::setGeometry(rect);
-        doMoveResize = d->state != Qt::WindowFullScreen && d->state != Qt::WindowMaximized;
-    }
-
-    if (doMoveResize) {
-        moveResize(rect);
-    }
+    mSurface->resize(newSize);
 }
 
 void QMirClientWindow::setVisible(bool visible)
 {
-    QMutexLocker(&d->mutex);
-    DLOG("QMirClientWindow::setVisible (this=%p, visible=%s)", this, visible ? "true" : "false");
+    QMutexLocker lock(&mMutex);
+    DLOG("[ubuntumirclient QPA] setVisible (window=%p, visible=%s)", window(), visible ? "true" : "false");
 
-    if (visible) {
-        mir_wait_for(mir_surface_set_state(d->surface, qtWindowStateToMirSurfaceState(d->state)));
+    mSurface->setVisible(visible);
+    const QRect& exposeRect = visible ? QRect(QPoint(), geometry().size()) : QRect();
 
-        QWindowSystemInterface::handleExposeEvent(window(), QRect());
-        QWindowSystemInterface::flushWindowSystemEvents();
-    } else {
-        // TODO: Use the new mir_surface_state_hidden state instead of mir_surface_state_minimized.
-        //       Will have to change qtmir and unity8 for that.
-        mir_wait_for(mir_surface_set_state(d->surface, mir_surface_state_minimized));
-    }
+    lock.unlock();
+    QWindowSystemInterface::handleExposeEvent(window(), exposeRect);
+    QWindowSystemInterface::flushWindowSystemEvents();
 }
 
-void* QMirClientWindow::eglSurface() const
+void QMirClientWindow::setWindowTitle(const QString& title)
 {
-    return d->eglSurface;
+    QMutexLocker lock(&mMutex);
+    DLOG("[ubuntumirclient QPA] setWindowTitle(window=%p) title=%s)", window(), title.toUtf8().constData());
+    mSurface->updateTitle(title);
 }
 
-WId QMirClientWindow::winId() const
+void QMirClientWindow::propagateSizeHints()
 {
-    return d->id;
+    QMutexLocker lock(&mMutex);
+    const auto win = window();
+    DLOG("[ubuntumirclient QPA] propagateSizeHints(window=%p) min(%d,%d), max(%d,%d) increment(%d, %d)",
+           win, win->minimumSize().width(), win->minimumSize().height(),
+           win->maximumSize().width(), win->maximumSize().height(),
+           win->sizeIncrement().width(), win->sizeIncrement().height());
+    mSurface->setSizingConstraints(win->minimumSize(), win->maximumSize(), win->sizeIncrement());
 }
 
-void QMirClientWindow::onBuffersSwapped_threadSafe(int newBufferWidth, int newBufferHeight)
+void* QMirClientWindow::eglSurface() const
 {
-    QMutexLocker(&d->mutex);
-
-    bool sizeKnown = newBufferWidth > 0 && newBufferHeight > 0;
-
-    if (sizeKnown && (d->bufferSize.width() != newBufferWidth ||
-                d->bufferSize.height() != newBufferHeight)) {
-
-        DLOG("QMirClientWindow::onBuffersSwapped_threadSafe - buffer size changed from (%d,%d) to (%d,%d)",
-                d->bufferSize.width(), d->bufferSize.height(), newBufferWidth, newBufferHeight);
-
-        d->bufferSize.rwidth() = newBufferWidth;
-        d->bufferSize.rheight() = newBufferHeight;
+    return mSurface->eglSurface();
+}
 
-        QRect newGeometry;
+MirSurface *QMirClientWindow::mirSurface() const
+{
+    return mSurface->mirSurface();
+}
 
-        newGeometry = geometry();
-        newGeometry.setWidth(d->bufferSize.width());
-        newGeometry.setHeight(d->bufferSize.height());
+WId QMirClientWindow::winId() const
+{
+    return mId;
+}
 
-        QPlatformWindow::setGeometry(newGeometry);
-        QWindowSystemInterface::handleGeometryChange(window(), newGeometry, QRect());
-    }
+void QMirClientWindow::onSwapBuffersDone()
+{
+    QMutexLocker lock(&mMutex);
+    mSurface->onSwapBuffersDone();
 }
diff --git a/src/plugins/platforms/mirclient/qmirclientwindow.h b/src/plugins/platforms/mirclient/qmirclientwindow.h
index f342669544e8d79032865f09687d923d7575fe5c..4ec7879949578eb663b74311627ed1e4608d5d24 100644
--- a/src/plugins/platforms/mirclient/qmirclientwindow.h
+++ b/src/plugins/platforms/mirclient/qmirclientwindow.h
@@ -40,20 +40,23 @@
 
 #include <qpa/qplatformwindow.h>
 #include <QSharedPointer>
+#include <QMutex>
 
-#include <mir_toolkit/mir_client_library.h>
+#include <memory>
 
 class QMirClientClipboard;
 class QMirClientInput;
 class QMirClientScreen;
-class QMirClientWindowPrivate;
+class QMirClientSurface;
+struct MirConnection;
+struct MirSurface;
 
 class QMirClientWindow : public QObject, public QPlatformWindow
 {
     Q_OBJECT
 public:
-    QMirClientWindow(QWindow *w, QSharedPointer<QMirClientClipboard> clipboard, QMirClientScreen *screen,
-                 QMirClientInput *input, MirConnection *mir_connection);
+    QMirClientWindow(QWindow *w, const QSharedPointer<QMirClientClipboard> &clipboard, QMirClientScreen *screen,
+                 QMirClientInput *input, MirConnection *mirConnection);
     virtual ~QMirClientWindow();
 
     // QPlatformWindow methods.
@@ -61,20 +64,22 @@ public:
     void setGeometry(const QRect&) override;
     void setWindowState(Qt::WindowState state) override;
     void setVisible(bool visible) override;
+    void setWindowTitle(const QString &title) override;
+    void propagateSizeHints() override;
 
     // New methods.
-    void* eglSurface() const;
-    void handleSurfaceResize(int width, int height);
-    void handleSurfaceFocusChange(bool focused);
-    void onBuffersSwapped_threadSafe(int newBufferWidth, int newBufferHeight);
-
-    QMirClientWindowPrivate* priv() { return d; }
+    void *eglSurface() const;
+    MirSurface *mirSurface() const;
+    void handleSurfaceResized(int width, int height);
+    void handleSurfaceFocused();
+    void onSwapBuffersDone();
 
 private:
-    void createWindow();
-    void moveResize(const QRect& rect);
-
-    QMirClientWindowPrivate *d;
+    void updatePanelHeightHack(Qt::WindowState);
+    mutable QMutex mMutex;
+    const WId mId;
+    const QSharedPointer<QMirClientClipboard> mClipboard;
+    std::unique_ptr<QMirClientSurface> mSurface;
 };
 
 #endif // QMIRCLIENTWINDOW_H
diff --git a/src/plugins/platforms/windows/accessible/accessible.pri b/src/plugins/platforms/windows/accessible/accessible.pri
index e26c6614e2b595a1ba65859e5fb23fc102a4aec0..0774d907f2a9f695dd54650bb6d100f110980db6 100644
--- a/src/plugins/platforms/windows/accessible/accessible.pri
+++ b/src/plugins/platforms/windows/accessible/accessible.pri
@@ -1,17 +1,20 @@
 SOURCES += \
-    $$PWD/qwindowsmsaaaccessible.cpp \
     $$PWD/qwindowsaccessibility.cpp \
     $$PWD/comutils.cpp
 
 HEADERS += \
-    $$PWD/qwindowsmsaaaccessible.h \
     $$PWD/qwindowsaccessibility.h \
     $$PWD/comutils.h
 
-!mingw: {
-    SOURCES += $$PWD/iaccessible2.cpp
-    HEADERS += $$PWD/iaccessible2.h
-    include(../../../../3rdparty/iaccessible2/iaccessible2.pri)
+!wince: {
+    SOURCES += $$PWD/qwindowsmsaaaccessible.cpp
+    HEADERS += $$PWD/qwindowsmsaaaccessible.h
+
+    !mingw: {
+        SOURCES += $$PWD/iaccessible2.cpp
+        HEADERS += $$PWD/iaccessible2.h
+        include(../../../../3rdparty/iaccessible2/iaccessible2.pri)
+    }
 }
 
-mingw: LIBS *= -luuid
\ No newline at end of file
+mingw: LIBS *= -luuid
diff --git a/src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp b/src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp
index 7015424f474ccc98cb57fd20db027c0b9fd9b930..0437290dcbd5bc0253ccc1db9dcbafd193f5a8b8 100644
--- a/src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp
+++ b/src/plugins/platforms/windows/accessible/qwindowsaccessibility.cpp
@@ -50,10 +50,12 @@
 #include <QtGui/qguiapplication.h>
 
 #include "qwindowsaccessibility.h"
-#ifdef Q_CC_MINGW
-# include "qwindowsmsaaaccessible.h"
-#else
-# include "iaccessible2.h"
+#if !defined(Q_OS_WINCE)
+# ifdef Q_CC_MINGW
+#  include "qwindowsmsaaaccessible.h"
+# else
+#  include "iaccessible2.h"
+# endif
 #endif
 #include "comutils.h"
 
@@ -68,8 +70,9 @@
 #if !defined(WINABLEAPI)
 #  if defined(Q_OS_WINCE)
 #    include <bldver.h>
+#  else
+#    include <winable.h>
 #  endif
-#  include <winable.h>
 #endif
 
 #include <servprov.h>
@@ -193,6 +196,11 @@ QWindow *QWindowsAccessibility::windowHelper(const QAccessibleInterface *iface)
 */
 IAccessible *QWindowsAccessibility::wrap(QAccessibleInterface *acc)
 {
+#if defined(Q_OS_WINCE)
+    Q_UNUSED(acc);
+
+    return 0;
+#else
     if (!acc)
         return 0;
 
@@ -200,14 +208,15 @@ IAccessible *QWindowsAccessibility::wrap(QAccessibleInterface *acc)
     if (!QAccessible::uniqueId(acc))
         QAccessible::registerAccessibleInterface(acc);
 
-#ifdef Q_CC_MINGW
+# ifdef Q_CC_MINGW
     QWindowsMsaaAccessible *wacc = new QWindowsMsaaAccessible(acc);
-#else
+# else
     QWindowsIA2Accessible *wacc = new QWindowsIA2Accessible(acc);
-#endif
+# endif
     IAccessible *iacc = 0;
     wacc->QueryInterface(IID_IAccessible, (void**)&iacc);
     return iacc;
+#endif // defined(Q_OS_WINCE)
 }
 
 /*
@@ -230,6 +239,7 @@ void QWindowsAccessibility::cleanup()
 
 bool QWindowsAccessibility::handleAccessibleObjectFromWindowRequest(HWND hwnd, WPARAM wParam, LPARAM lParam, LRESULT *lResult)
 {
+#if !defined(Q_OS_WINCE)
     if (static_cast<long>(lParam) == static_cast<long>(UiaRootObjectId)) {
         /* For UI Automation */
     } else if ((DWORD)lParam == DWORD(OBJID_CLIENT)) {
@@ -248,9 +258,7 @@ bool QWindowsAccessibility::handleAccessibleObjectFromWindowRequest(HWND hwnd, W
 
         if (!oleaccChecked) {
             oleaccChecked = true;
-#if !defined(Q_OS_WINCE)
             ptrLresultFromObject = (PtrLresultFromObject)QSystemLibrary::resolve(QLatin1String("oleacc"), "LresultFromObject");
-#endif
         }
 
         if (ptrLresultFromObject) {
@@ -269,6 +277,12 @@ bool QWindowsAccessibility::handleAccessibleObjectFromWindowRequest(HWND hwnd, W
             }
         }
     }
+#else
+    Q_UNUSED(hwnd);
+    Q_UNUSED(wParam);
+    Q_UNUSED(lParam);
+    Q_UNUSED(lResult);
+#endif // !defined(Q_OS_WINCE)
     return false;
 }
 
diff --git a/src/plugins/platforms/windows/qwindowsbackingstore.cpp b/src/plugins/platforms/windows/qwindowsbackingstore.cpp
index 135c9eb601b8ee4291b4e0c79abdd5f737d991b7..a6b1d0af2676e983d42e7182828ea4dfc2c2f808 100644
--- a/src/plugins/platforms/windows/qwindowsbackingstore.cpp
+++ b/src/plugins/platforms/windows/qwindowsbackingstore.cpp
@@ -39,6 +39,7 @@
 #include <QtGui/QWindow>
 #include <QtGui/QPainter>
 #include <private/qhighdpiscaling_p.h>
+#include <private/qimage_p.h>
 
 #include <QtCore/QDebug>
 
@@ -52,7 +53,8 @@ QT_BEGIN_NAMESPACE
 */
 
 QWindowsBackingStore::QWindowsBackingStore(QWindow *window) :
-    QPlatformBackingStore(window)
+    QPlatformBackingStore(window),
+    m_alphaNeedsFill(false)
 {
     qCDebug(lcQpaBackingStore) << __FUNCTION__ << this << window;
 }
@@ -144,8 +146,16 @@ void QWindowsBackingStore::resize(const QSize &size, const QRegion &region)
                 << " from: " << (m_image.isNull() ? QSize() : m_image->image().size());
         }
 #endif
-        const QImage::Format format = window()->format().hasAlpha() ?
-            QImage::Format_ARGB32_Premultiplied : QWindowsNativeImage::systemFormat();
+        QImage::Format format = window()->format().hasAlpha() ?
+                    QImage::Format_ARGB32_Premultiplied : QWindowsNativeImage::systemFormat();
+
+        // The backingstore composition (enabling render-to-texture widgets)
+        // punches holes in the backingstores using the alpha channel. Hence
+        // the need for a true alpha format.
+        if (QImage::toPixelFormat(format).alphaUsage() == QPixelFormat::UsesAlpha)
+            m_alphaNeedsFill = true;
+        else // upgrade but here we know app painting does not rely on alpha hence no need to fill
+            format = qt_alphaVersionForPainting(format);
 
         QWindowsNativeImage *oldwni = m_image.data();
         QWindowsNativeImage *newwni = new QWindowsNativeImage(size.width(), size.height(), format);
@@ -186,7 +196,7 @@ void QWindowsBackingStore::beginPaint(const QRegion &region)
     if (QWindowsContext::verbose > 1)
         qCDebug(lcQpaBackingStore) <<__FUNCTION__ << region;
 
-    if (m_image->image().hasAlphaChannel()) {
+    if (m_alphaNeedsFill) {
         QPainter p(&m_image->image());
         p.setCompositionMode(QPainter::CompositionMode_Source);
         const QColor blank = Qt::transparent;
diff --git a/src/plugins/platforms/windows/qwindowsbackingstore.h b/src/plugins/platforms/windows/qwindowsbackingstore.h
index 4badcf1b0930209ecb75c057b5dbcafb5de11496..1d644923bbd48a47053a10b45005ac8f91a1d292 100644
--- a/src/plugins/platforms/windows/qwindowsbackingstore.h
+++ b/src/plugins/platforms/windows/qwindowsbackingstore.h
@@ -65,6 +65,7 @@ public:
 
 private:
     QScopedPointer<QWindowsNativeImage> m_image;
+    bool m_alphaNeedsFill;
 };
 
 QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp b/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp
index b983ba3354beb93e82e17a6e16e410f78ee566a1..9211fd1320b2055c7861826fea7022cd0e2c7651 100644
--- a/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp
+++ b/src/plugins/platforms/windows/qwindowsdialoghelpers.cpp
@@ -876,12 +876,12 @@ public:
 
     inline static QWindowsNativeFileDialogBase *create(QFileDialogOptions::AcceptMode am, const QWindowsFileDialogSharedData &data);
 
-    virtual void setWindowTitle(const QString &title);
+    void setWindowTitle(const QString &title) Q_DECL_OVERRIDE;
     inline void setMode(QFileDialogOptions::FileMode mode, QFileDialogOptions::AcceptMode acceptMode, QFileDialogOptions::FileDialogOptions options);
     inline void setDirectory(const QUrl &directory);
     inline void updateDirectory() { setDirectory(m_data.directory()); }
     inline QString directory() const;
-    virtual void doExec(HWND owner = 0);
+    void doExec(HWND owner = 0) Q_DECL_OVERRIDE;
     virtual void setNameFilters(const QStringList &f);
     inline void selectNameFilter(const QString &filter);
     inline void updateSelectedNameFilter() { selectNameFilter(m_data.selectedNameFilter()); }
@@ -910,7 +910,7 @@ signals:
     void filterSelected(const QString & filter);
 
 public slots:
-    virtual void close();
+    void close() Q_DECL_OVERRIDE;
 
 protected:
     explicit QWindowsNativeFileDialogBase(const QWindowsFileDialogSharedData &data);
@@ -1460,9 +1460,9 @@ class QWindowsNativeSaveFileDialog : public QWindowsNativeFileDialogBase
 public:
     explicit QWindowsNativeSaveFileDialog(const QWindowsFileDialogSharedData &data)
         : QWindowsNativeFileDialogBase(data) {}
-    virtual void setNameFilters(const QStringList &f);
-    virtual QList<QUrl> selectedFiles() const;
-    virtual QList<QUrl> dialogResult() const;
+    void setNameFilters(const QStringList &f) Q_DECL_OVERRIDE;
+    QList<QUrl> selectedFiles() const Q_DECL_OVERRIDE;
+    QList<QUrl> dialogResult() const Q_DECL_OVERRIDE;
 };
 
 // Return the first suffix from the name filter "Foo files (*.foo;*.bar)" -> "foo".
@@ -1531,8 +1531,8 @@ class QWindowsNativeOpenFileDialog : public QWindowsNativeFileDialogBase
 public:
     explicit QWindowsNativeOpenFileDialog(const QWindowsFileDialogSharedData &data) :
         QWindowsNativeFileDialogBase(data) {}
-    virtual QList<QUrl> selectedFiles() const;
-    virtual QList<QUrl> dialogResult() const;
+    QList<QUrl> selectedFiles() const Q_DECL_OVERRIDE;
+    QList<QUrl> dialogResult() const Q_DECL_OVERRIDE;
 
 private:
     inline IFileOpenDialog *openFileDialog() const
@@ -1616,7 +1616,7 @@ public:
     virtual QString selectedNameFilter() const Q_DECL_OVERRIDE;
 
 private:
-    virtual QWindowsNativeDialogBase *createNativeDialog();
+    QWindowsNativeDialogBase *createNativeDialog() Q_DECL_OVERRIDE;
     inline QWindowsNativeFileDialogBase *nativeFileDialog() const
         { return static_cast<QWindowsNativeFileDialogBase *>(nativeDialog()); }
 
@@ -1744,14 +1744,13 @@ public:
 
     static QWindowsXpNativeFileDialog *create(const OptionsPtr &options, const QWindowsFileDialogSharedData &data);
 
-    virtual void setWindowTitle(const QString &t) { m_title =  t; }
-    virtual void doExec(HWND owner = 0);
-    virtual QPlatformDialogHelper::DialogCode result() const { return m_result; }
+    void setWindowTitle(const QString &t) Q_DECL_OVERRIDE { m_title =  t; }
+    void doExec(HWND owner = 0) Q_DECL_OVERRIDE;
 
     int existingDirCallback(HWND hwnd, UINT uMsg, LPARAM lParam);
 
 public slots:
-    virtual void close() {}
+     void close() Q_DECL_OVERRIDE {}
 
 private:
     typedef BOOL (APIENTRY *PtrGetOpenFileNameW)(LPOPENFILENAMEW);
@@ -1987,19 +1986,19 @@ class QWindowsXpFileDialogHelper : public QWindowsDialogHelperBase<QPlatformFile
 {
 public:
     QWindowsXpFileDialogHelper() {}
-    virtual bool supportsNonModalDialog(const QWindow * /* parent */ = 0) const { return false; }
-    virtual bool defaultNameFilterDisables() const
+    bool supportsNonModalDialog(const QWindow * /* parent */ = 0) const Q_DECL_OVERRIDE { return false; }
+    bool defaultNameFilterDisables() const Q_DECL_OVERRIDE
         { return true; }
-    virtual void setDirectory(const QUrl &directory) Q_DECL_OVERRIDE;
-    virtual QUrl directory() const Q_DECL_OVERRIDE;
-    virtual void selectFile(const QUrl &url) Q_DECL_OVERRIDE;
-    virtual QList<QUrl> selectedFiles() const Q_DECL_OVERRIDE;
-    virtual void setFilter() Q_DECL_OVERRIDE {}
-    virtual void selectNameFilter(const QString &) Q_DECL_OVERRIDE;
-    virtual QString selectedNameFilter() const Q_DECL_OVERRIDE;
+    void setDirectory(const QUrl &directory) Q_DECL_OVERRIDE;
+    QUrl directory() const Q_DECL_OVERRIDE;
+    void selectFile(const QUrl &url) Q_DECL_OVERRIDE;
+    QList<QUrl> selectedFiles() const Q_DECL_OVERRIDE;
+    void setFilter() Q_DECL_OVERRIDE {}
+    void selectNameFilter(const QString &) Q_DECL_OVERRIDE;
+    QString selectedNameFilter() const Q_DECL_OVERRIDE;
 
 private:
-    virtual QWindowsNativeDialogBase *createNativeDialog();
+    QWindowsNativeDialogBase *createNativeDialog() Q_DECL_OVERRIDE;
     inline QWindowsXpNativeFileDialog *nativeFileDialog() const
         { return static_cast<QWindowsXpNativeFileDialog *>(nativeDialog()); }
 
@@ -2073,14 +2072,13 @@ public:
 
     explicit QWindowsNativeColorDialog(const SharedPointerColor &color);
 
-    virtual void setWindowTitle(const QString &) {}
-    virtual QPlatformDialogHelper::DialogCode result() const { return m_code; }
+    void setWindowTitle(const QString &) Q_DECL_OVERRIDE {}
 
 public slots:
-    virtual void close() {}
+    void close() Q_DECL_OVERRIDE {}
 
 private:
-    virtual void doExec(HWND owner = 0);
+    void doExec(HWND owner = 0) Q_DECL_OVERRIDE;
 
     COLORREF m_customColors[CustomColorCount];
     QPlatformDialogHelper::DialogCode m_code;
diff --git a/src/plugins/platforms/windows/qwindowsdrag.cpp b/src/plugins/platforms/windows/qwindowsdrag.cpp
index 021058fa33e07731ee2913f5c56970d57e48a947..16079576a26c6fd35b13dca605835abb3e6ec027 100644
--- a/src/plugins/platforms/windows/qwindowsdrag.cpp
+++ b/src/plugins/platforms/windows/qwindowsdrag.cpp
@@ -78,7 +78,7 @@ public:
     void setPixmap(const QPixmap &p);
 
 protected:
-    void paintEvent(QPaintEvent *)
+    void paintEvent(QPaintEvent *) Q_DECL_OVERRIDE
     {
         QPainter painter(this);
         painter.drawPixmap(0, 0, m_pixmap);
diff --git a/src/plugins/platforms/windows/qwindowsfontdatabase_ft.h b/src/plugins/platforms/windows/qwindowsfontdatabase_ft.h
index ad5c005ffa0acc4dd8fcdce9606d29c14d640332..f65dc38801ae7cb289b64db03ff7578f8e469a50 100644
--- a/src/plugins/platforms/windows/qwindowsfontdatabase_ft.h
+++ b/src/plugins/platforms/windows/qwindowsfontdatabase_ft.h
@@ -43,12 +43,15 @@ QT_BEGIN_NAMESPACE
 class QWindowsFontDatabaseFT : public QBasicFontDatabase
 {
 public:
-    void populateFontDatabase();
+    void populateFontDatabase() Q_DECL_OVERRIDE;
     void populateFamily(const QString &familyName) Q_DECL_OVERRIDE;
-    QFontEngine *fontEngine(const QFontDef &fontDef, void *handle);
-    QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize, QFont::HintingPreference hintingPreference);
+    QFontEngine *fontEngine(const QFontDef &fontDef, void *handle) Q_DECL_OVERRIDE;
+    QFontEngine *fontEngine(const QByteArray &fontData, qreal pixelSize,
+                            QFont::HintingPreference hintingPreference) Q_DECL_OVERRIDE;
 
-    QStringList fallbacksForFamily(const QString &family, QFont::Style style, QFont::StyleHint styleHint, QChar::Script script) const;
+    QStringList fallbacksForFamily(const QString &family, QFont::Style style,
+                                   QFont::StyleHint styleHint,
+                                   QChar::Script script) const Q_DECL_OVERRIDE;
 
     QString fontDir() const Q_DECL_OVERRIDE;
     QFont defaultFont() const Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/windows/qwindowsfontengine.h b/src/plugins/platforms/windows/qwindowsfontengine.h
index 409b44264e42826688559c6d6c2fcc0793cd3fcc..531736845539526be3b4b410d2832ba432219c7b 100644
--- a/src/plugins/platforms/windows/qwindowsfontengine.h
+++ b/src/plugins/platforms/windows/qwindowsfontengine.h
@@ -84,7 +84,7 @@ public:
 
     void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
     virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
-                         QPainterPath *path, QTextItem::RenderFlags flags);
+                         QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
 
     HGDIOBJ selectDesignFont() const;
 
diff --git a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp
index a50ee609750942158db0e4bef78c9c6cbc058fc5..bb4f4b1abdd3c4b3f3c53a4275e15d6fdb6c2b6c 100644
--- a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp
+++ b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.cpp
@@ -520,13 +520,8 @@ QImage QWindowsFontEngineDirectWrite::imageForGlyph(glyph_t t,
                                              int margin,
                                              const QTransform &xform)
 {
-    glyph_metrics_t metrics = QFontEngine::boundingBox(t, xform);
-    // This needs to be kept in sync with alphaMapBoundingBox
-    int width = (metrics.width + margin * 2).ceil().toInt() ;
-    int height = (metrics.height + margin * 2).ceil().toInt();
-
     UINT16 glyphIndex = t;
-    FLOAT glyphAdvance = metrics.xoff.toReal();
+    FLOAT glyphAdvance = 0;
 
     DWRITE_GLYPH_OFFSET glyphOffset;
     glyphOffset.advanceOffset = 0;
@@ -542,12 +537,9 @@ QImage QWindowsFontEngineDirectWrite::imageForGlyph(glyph_t t,
     glyphRun.bidiLevel = 0;
     glyphRun.glyphOffsets = &glyphOffset;
 
-    QFixed x = margin - metrics.x.floor() + subPixelPosition;
-    QFixed y = margin - metrics.y.floor();
-
     DWRITE_MATRIX transform;
-    transform.dx = x.toReal();
-    transform.dy = y.toReal();
+    transform.dx = subPixelPosition.toReal();
+    transform.dy = 0;
     transform.m11 = xform.m11();
     transform.m12 = xform.m12();
     transform.m21 = xform.m21();
@@ -571,46 +563,56 @@ QImage QWindowsFontEngineDirectWrite::imageForGlyph(glyph_t t,
 
     if (SUCCEEDED(hr)) {
         RECT rect;
-        rect.left = 0;
-        rect.top = 0;
-        rect.right = width;
-        rect.bottom = height;
+        glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect);
 
-        int size = width * height * 3;
-        BYTE *alphaValues = new BYTE[size];
-        memset(alphaValues, 0, size);
+        rect.left -= margin;
+        rect.top -= margin;
+        rect.right += margin;
+        rect.bottom += margin;
 
-        hr = glyphAnalysis->CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1,
-                                               &rect,
-                                               alphaValues,
-                                               size);
+        const int width = rect.right - rect.left;
+        const int height = rect.bottom - rect.top;
 
-        if (SUCCEEDED(hr)) {
-            QImage img(width, height, QImage::Format_RGB32);
-            img.fill(0xffffffff);
+        const int size = width * height * 3;
+        if (size > 0) {
+            BYTE *alphaValues = new BYTE[size];
+            memset(alphaValues, 0, size);
 
-            for (int y=0; y<height; ++y) {
-                uint *dest = reinterpret_cast<uint *>(img.scanLine(y));
-                BYTE *src = alphaValues + width * 3 * y;
+            hr = glyphAnalysis->CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1,
+                                                   &rect,
+                                                   alphaValues,
+                                                   size);
 
-                for (int x=0; x<width; ++x) {
-                    dest[x] = *(src) << 16
-                            | *(src + 1) << 8
-                            | *(src + 2);
+            if (SUCCEEDED(hr)) {
+                QImage img(width, height, QImage::Format_RGB32);
+                img.fill(0xffffffff);
 
-                    src += 3;
+                for (int y=0; y<height; ++y) {
+                    uint *dest = reinterpret_cast<uint *>(img.scanLine(y));
+                    BYTE *src = alphaValues + width * 3 * y;
+
+                    for (int x=0; x<width; ++x) {
+                        dest[x] = *(src) << 16
+                                | *(src + 1) << 8
+                                | *(src + 2);
+
+                        src += 3;
+                    }
                 }
-            }
 
-            delete[] alphaValues;
-            glyphAnalysis->Release();
+                delete[] alphaValues;
+                glyphAnalysis->Release();
+
+                return img;
+            } else {
+                delete[] alphaValues;
+                glyphAnalysis->Release();
 
-            return img;
+                qErrnoWarning("%s: CreateAlphaTexture failed", __FUNCTION__);
+            }
         } else {
-            delete[] alphaValues;
             glyphAnalysis->Release();
-
-            qErrnoWarning("%s: CreateAlphaTexture failed", __FUNCTION__);
+            qWarning("%s: Glyph has no bounds", __FUNCTION__);
         }
 
     } else {
@@ -724,16 +726,65 @@ QString QWindowsFontEngineDirectWrite::fontNameSubstitute(const QString &familyN
     return QSettings(QLatin1String(keyC), QSettings::NativeFormat).value(familyName, familyName).toString();
 }
 
-glyph_metrics_t QWindowsFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph, QFixed pos, const QTransform &matrix, GlyphFormat format)
+glyph_metrics_t QWindowsFontEngineDirectWrite::alphaMapBoundingBox(glyph_t glyph,
+                                                                   QFixed subPixelPosition,
+                                                                   const QTransform &matrix,
+                                                                   GlyphFormat format)
 {
-    Q_UNUSED(pos);
     Q_UNUSED(format);
+    glyph_metrics_t bbox = QFontEngine::boundingBox(glyph, matrix); // To get transformed advance
+
+    UINT16 glyphIndex = glyph;
+    FLOAT glyphAdvance = 0;
+
+    DWRITE_GLYPH_OFFSET glyphOffset;
+    glyphOffset.advanceOffset = 0;
+    glyphOffset.ascenderOffset = 0;
+
+    DWRITE_GLYPH_RUN glyphRun;
+    glyphRun.fontFace = m_directWriteFontFace;
+    glyphRun.fontEmSize = fontDef.pixelSize;
+    glyphRun.glyphCount = 1;
+    glyphRun.glyphIndices = &glyphIndex;
+    glyphRun.glyphAdvances = &glyphAdvance;
+    glyphRun.isSideways = false;
+    glyphRun.bidiLevel = 0;
+    glyphRun.glyphOffsets = &glyphOffset;
+
+    DWRITE_MATRIX transform;
+    transform.dx = subPixelPosition.toReal();
+    transform.dy = 0;
+    transform.m11 = matrix.m11();
+    transform.m12 = matrix.m12();
+    transform.m21 = matrix.m21();
+    transform.m22 = matrix.m22();
+
+    IDWriteGlyphRunAnalysis *glyphAnalysis = NULL;
+    HRESULT hr = m_fontEngineData->directWriteFactory->CreateGlyphRunAnalysis(
+                &glyphRun,
+                1.0f,
+                &transform,
+                DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC,
+                DWRITE_MEASURING_MODE_NATURAL,
+                0.0, 0.0,
+                &glyphAnalysis
+                );
 
-    int margin = glyphMargin(QFontEngine::Format_A32);
-    glyph_metrics_t gm = QFontEngine::boundingBox(glyph, matrix);
-    gm.width += margin * 2;
-    gm.height += margin * 2;
-    return gm;
+    if (SUCCEEDED(hr)) {
+        RECT rect;
+        glyphAnalysis->GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1, &rect);
+        glyphAnalysis->Release();
+
+        int margin = glyphMargin(QFontEngine::Format_A32);
+
+        return glyph_metrics_t(rect.left,
+                               rect.top,
+                               rect.right - rect.left + margin * 2,
+                               rect.bottom - rect.top + margin * 2,
+                               bbox.xoff, bbox.yoff);
+    } else {
+        return glyph_metrics_t();
+    }
 }
 
 QT_END_NAMESPACE
diff --git a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h
index cee8691d69b3ae72d5fd92c605100e5dc4b532ef..07e040ed333222799a52a43d4d0fbaab1fe18bb0 100644
--- a/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h
+++ b/src/plugins/platforms/windows/qwindowsfontenginedirectwrite.h
@@ -61,35 +61,37 @@ public:
 
     void initFontInfo(const QFontDef &request, int dpi, IDWriteFont *font);
 
-    QFixed lineThickness() const;
-    QFixed underlinePosition() const;
-    bool getSfntTableData(uint tag, uchar *buffer, uint *length) const;
-    QFixed emSquareSize() const;
+    QFixed lineThickness() const Q_DECL_OVERRIDE;
+    QFixed underlinePosition() const Q_DECL_OVERRIDE;
+    bool getSfntTableData(uint tag, uchar *buffer, uint *length) const Q_DECL_OVERRIDE;
+    QFixed emSquareSize() const Q_DECL_OVERRIDE;
 
     glyph_t glyphIndex(uint ucs4) const Q_DECL_OVERRIDE;
-    bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, ShaperFlags flags) const;
-    void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags) const;
+    bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
+                      ShaperFlags flags) const Q_DECL_OVERRIDE;
+    void recalcAdvances(QGlyphLayout *glyphs, ShaperFlags) const Q_DECL_OVERRIDE;
 
     void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
-                         QPainterPath *path, QTextItem::RenderFlags flags);
+                         QPainterPath *path, QTextItem::RenderFlags flags) Q_DECL_OVERRIDE;
 
-    glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
-    glyph_metrics_t boundingBox(glyph_t g);
-    glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, QFixed, const QTransform &matrix, GlyphFormat);
+    glyph_metrics_t boundingBox(const QGlyphLayout &glyphs) Q_DECL_OVERRIDE;
+    glyph_metrics_t boundingBox(glyph_t g) Q_DECL_OVERRIDE;
+    glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, QFixed,
+                                        const QTransform &matrix, GlyphFormat) Q_DECL_OVERRIDE;
 
-    QFixed ascent() const;
-    QFixed descent() const;
-    QFixed leading() const;
-    QFixed xHeight() const;
-    qreal maxCharWidth() const;
+    QFixed ascent() const Q_DECL_OVERRIDE;
+    QFixed descent() const Q_DECL_OVERRIDE;
+    QFixed leading() const Q_DECL_OVERRIDE;
+    QFixed xHeight() const Q_DECL_OVERRIDE;
+    qreal maxCharWidth() const Q_DECL_OVERRIDE;
 
-    bool supportsSubPixelPositions() const;
+    bool supportsSubPixelPositions() const Q_DECL_OVERRIDE;
 
-    QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition);
-    QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t);
-    QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, const QTransform &xform);
+    QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition) Q_DECL_OVERRIDE;
+    QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t) Q_DECL_OVERRIDE;
+    QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, const QTransform &xform) Q_DECL_OVERRIDE;
 
-    QFontEngine *cloneWithSize(qreal pixelSize) const;
+    QFontEngine *cloneWithSize(qreal pixelSize) const Q_DECL_OVERRIDE;
 
     const QSharedPointer<QWindowsFontEngineData> &fontEngineData() const { return m_fontEngineData; }
 
diff --git a/src/plugins/platforms/windows/qwindowsintegration.h b/src/plugins/platforms/windows/qwindowsintegration.h
index cb10bf08f5938d3cf04221f4ec6bd4a2598621bb..da20d9261ad9c3a422a6f87589d1c358f7e1476c 100644
--- a/src/plugins/platforms/windows/qwindowsintegration.h
+++ b/src/plugins/platforms/windows/qwindowsintegration.h
@@ -60,12 +60,12 @@ public:
     explicit QWindowsIntegration(const QStringList &paramList);
     virtual ~QWindowsIntegration();
 
-    bool hasCapability(QPlatformIntegration::Capability cap) const;
+    bool hasCapability(QPlatformIntegration::Capability cap) const Q_DECL_OVERRIDE;
 
-    QPlatformWindow *createPlatformWindow(QWindow *window) const;
+    QPlatformWindow *createPlatformWindow(QWindow *window) const Q_DECL_OVERRIDE;
 #ifndef QT_NO_OPENGL
     QPlatformOpenGLContext *createPlatformOpenGLContext(QOpenGLContext *context) const Q_DECL_OVERRIDE;
-    QOpenGLContext::OpenGLModuleType openGLModuleType();
+    QOpenGLContext::OpenGLModuleType openGLModuleType() Q_DECL_OVERRIDE;
     static QWindowsStaticOpenGLContext *staticOpenGLContext();
 #endif
     QAbstractEventDispatcher *createEventDispatcher() const Q_DECL_OVERRIDE;
@@ -83,7 +83,7 @@ public:
     QPlatformFontDatabase *fontDatabase() const Q_DECL_OVERRIDE;
     QStringList themeNames() const Q_DECL_OVERRIDE;
     QPlatformTheme *createPlatformTheme(const QString &name) const Q_DECL_OVERRIDE;
-    QPlatformServices *services() const;
+    QPlatformServices *services() const Q_DECL_OVERRIDE;
     QVariant styleHint(StyleHint hint) const Q_DECL_OVERRIDE;
 
     Qt::KeyboardModifiers queryKeyboardModifiers() const Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/windows/qwindowsmime.cpp b/src/plugins/platforms/windows/qwindowsmime.cpp
index 0a2ba9b0e74cecd21e85afeef75bb84f83fe5590..171ace5c2004052f5c6cda9a750317abc513eb30 100644
--- a/src/plugins/platforms/windows/qwindowsmime.cpp
+++ b/src/plugins/platforms/windows/qwindowsmime.cpp
@@ -897,14 +897,14 @@ 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;
+    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const Q_DECL_OVERRIDE;
+    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const Q_DECL_OVERRIDE;
+    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const Q_DECL_OVERRIDE;
 
     // 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;
+    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const Q_DECL_OVERRIDE;
+    QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const Q_DECL_OVERRIDE;
+    QString mimeForFormat(const FORMATETC &formatetc) const Q_DECL_OVERRIDE;
 
 private:
     int CF_HTML;
@@ -1029,14 +1029,14 @@ 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;
+    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const Q_DECL_OVERRIDE;
+    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const Q_DECL_OVERRIDE;
+    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const Q_DECL_OVERRIDE;
 
     // 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;
+    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const Q_DECL_OVERRIDE;
+    QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const Q_DECL_OVERRIDE;
+    QString mimeForFormat(const FORMATETC &formatetc) const Q_DECL_OVERRIDE;
 private:
     bool hasOriginalDIBV5(IDataObject *pDataObj) const;
     UINT CF_PNG;
@@ -1183,14 +1183,14 @@ 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;
+    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const Q_DECL_OVERRIDE;
+    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const Q_DECL_OVERRIDE;
+    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const Q_DECL_OVERRIDE;
 
     // 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;
+    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const Q_DECL_OVERRIDE;
+    QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const Q_DECL_OVERRIDE;
+    QString mimeForFormat(const FORMATETC &formatetc) const Q_DECL_OVERRIDE;
 
 private:
     QMap<int, QString> outFormats;
@@ -1303,14 +1303,14 @@ 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;
+    bool canConvertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData) const Q_DECL_OVERRIDE;
+    bool convertFromMime(const FORMATETC &formatetc, const QMimeData *mimeData, STGMEDIUM * pmedium) const Q_DECL_OVERRIDE;
+    QVector<FORMATETC> formatsForMime(const QString &mimeType, const QMimeData *mimeData) const Q_DECL_OVERRIDE;
 
     // 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;
+    bool canConvertToMime(const QString &mimeType, IDataObject *pDataObj) const Q_DECL_OVERRIDE;
+    QVariant convertToMime(const QString &mime, IDataObject *pDataObj, QVariant::Type preferredType) const Q_DECL_OVERRIDE;
+    QString mimeForFormat(const FORMATETC &formatetc) const Q_DECL_OVERRIDE;
 
 private:
     QMap<int, QString> formats;
diff --git a/src/plugins/platforms/windows/qwindowstheme.h b/src/plugins/platforms/windows/qwindowstheme.h
index b2f8e13b6467b69b98d6d602edbef22f8a046825..fc004b68c898fcfcae0bb3f1482878dafd75f286 100644
--- a/src/plugins/platforms/windows/qwindowstheme.h
+++ b/src/plugins/platforms/windows/qwindowstheme.h
@@ -51,9 +51,9 @@ public:
     bool usePlatformNativeDialog(DialogType type) const Q_DECL_OVERRIDE;
     QPlatformDialogHelper *createPlatformDialogHelper(DialogType type) const Q_DECL_OVERRIDE;
     QVariant themeHint(ThemeHint) const Q_DECL_OVERRIDE;
-    virtual const QPalette *palette(Palette type = SystemPalette) const
+    const QPalette *palette(Palette type = SystemPalette) const Q_DECL_OVERRIDE
         { return m_palettes[type]; }
-    virtual const QFont *font(Font type = SystemFont) const
+    const QFont *font(Font type = SystemFont) const Q_DECL_OVERRIDE
         { return m_fonts[type]; }
 
     QPixmap standardPixmap(StandardPixmap sp, const QSizeF &size) const Q_DECL_OVERRIDE;
diff --git a/src/plugins/platforms/windows/qwindowswindow.h b/src/plugins/platforms/windows/qwindowswindow.h
index 710cab859708e60db2c60bf0aedf60ac10948325..6fffa1e6e9eb355fc5176ce26508ae73b3a1c548 100644
--- a/src/plugins/platforms/windows/qwindowswindow.h
+++ b/src/plugins/platforms/windows/qwindowswindow.h
@@ -171,7 +171,7 @@ public:
     void raise() Q_DECL_OVERRIDE;
     void lower() Q_DECL_OVERRIDE;
 
-    void windowEvent(QEvent *event);
+    void windowEvent(QEvent *event) Q_DECL_OVERRIDE;
 
     void propagateSizeHints() Q_DECL_OVERRIDE;
     static bool handleGeometryChangingMessage(MSG *message, const QWindow *qWindow, const QMargins &marginsDp);
@@ -189,8 +189,8 @@ public:
 
     bool startSystemResize(const QPoint &pos, Qt::Corner corner) Q_DECL_OVERRIDE;
 
-    void setFrameStrutEventsEnabled(bool enabled);
-    bool frameStrutEventsEnabled() const { return testFlag(FrameStrutEventsEnabled); }
+    void setFrameStrutEventsEnabled(bool enabled) Q_DECL_OVERRIDE;
+    bool frameStrutEventsEnabled() const Q_DECL_OVERRIDE { return testFlag(FrameStrutEventsEnabled); }
 
     QMargins customMargins() const { return m_data.customMargins; }
     void setCustomMargins(const QMargins &m);
@@ -237,15 +237,15 @@ public:
 
     void setEnabled(bool enabled);
     bool isEnabled() const;
-    void setWindowIcon(const QIcon &icon);
+    void setWindowIcon(const QIcon &icon) Q_DECL_OVERRIDE;
 
     void *surface(void *nativeConfig, int *err);
     void invalidateSurface() Q_DECL_OVERRIDE;
     void aboutToMakeCurrent();
 
 #ifndef Q_OS_WINCE
-    void setAlertState(bool enabled);
-    bool isAlertState() const { return testFlag(AlertState); }
+    void setAlertState(bool enabled) Q_DECL_OVERRIDE;
+    bool isAlertState() const Q_DECL_OVERRIDE { return testFlag(AlertState); }
     void alertWindow(int durationMs = 0);
     void stopAlertWindow();
 #endif
diff --git a/src/plugins/platforms/winrt/qwinrtintegration.cpp b/src/plugins/platforms/winrt/qwinrtintegration.cpp
index 71e92f33ca518b078c0af742658d7005cf8dd268..2281bf56ccdcdb455bbc2feeb25c6371cf2417c8 100644
--- a/src/plugins/platforms/winrt/qwinrtintegration.cpp
+++ b/src/plugins/platforms/winrt/qwinrtintegration.cpp
@@ -59,10 +59,16 @@
 #include <windows.ui.core.h>
 #include <windows.ui.viewmanagement.h>
 #include <windows.graphics.display.h>
-#ifdef Q_OS_WINPHONE
+
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
 #  include <windows.phone.ui.input.h>
+#  if _MSC_VER >= 1900
+#    include <windows.foundation.metadata.h>
+     using namespace ABI::Windows::Foundation::Metadata;
+#  endif
 #endif
 
+
 using namespace Microsoft::WRL;
 using namespace Microsoft::WRL::Wrappers;
 using namespace ABI::Windows::Foundation;
@@ -73,13 +79,13 @@ using namespace ABI::Windows::UI::Core;
 using namespace ABI::Windows::UI::ViewManagement;
 using namespace ABI::Windows::Graphics::Display;
 using namespace ABI::Windows::ApplicationModel::Core;
-#ifdef Q_OS_WINPHONE
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
 using namespace ABI::Windows::Phone::UI::Input;
 #endif
 
 typedef IEventHandler<IInspectable *> ResumeHandler;
 typedef IEventHandler<SuspendingEventArgs *> SuspendHandler;
-#ifdef Q_OS_WINPHONE
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
 typedef IEventHandler<BackPressedEventArgs*> BackPressedHandler;
 typedef IEventHandler<CameraEventArgs*> CameraButtonHandler;
 #endif
@@ -88,7 +94,7 @@ QT_BEGIN_NAMESPACE
 
 typedef HRESULT (__stdcall ICoreApplication::*CoreApplicationCallbackRemover)(EventRegistrationToken);
 uint qHash(CoreApplicationCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
-#ifdef Q_OS_WINPHONE
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
 typedef HRESULT (__stdcall IHardwareButtonsStatics::*HardwareButtonsCallbackRemover)(EventRegistrationToken);
 uint qHash(HardwareButtonsCallbackRemover key) { void *ptr = *(void **)(&key); return qHash(ptr); }
 typedef HRESULT (__stdcall IHardwareButtonsStatics2::*HardwareButtons2CallbackRemover)(EventRegistrationToken);
@@ -105,11 +111,12 @@ public:
 
     ComPtr<ICoreApplication> application;
     QHash<CoreApplicationCallbackRemover, EventRegistrationToken> applicationTokens;
-#ifdef Q_OS_WINPHONE
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
     ComPtr<IHardwareButtonsStatics> hardwareButtons;
     QHash<HardwareButtonsCallbackRemover, EventRegistrationToken> buttonsTokens;
     ComPtr<IHardwareButtonsStatics2> cameraButtons;
     QHash<HardwareButtons2CallbackRemover, EventRegistrationToken> cameraTokens;
+    boolean hasHardwareButtons;
     bool cameraHalfPressed : 1;
     bool cameraPressed : 1;
 #endif
@@ -132,31 +139,48 @@ QWinRTIntegration::QWinRTIntegration() : d_ptr(new QWinRTIntegrationPrivate)
                                       &d->applicationTokens[&ICoreApplication::remove_Resuming]);
     Q_ASSERT_SUCCEEDED(hr);
 
-#ifdef Q_OS_WINPHONE
-    hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Phone_UI_Input_HardwareButtons).Get(),
-                                IID_PPV_ARGS(&d->hardwareButtons));
-    Q_ASSERT_SUCCEEDED(hr);
-    hr = d->hardwareButtons->add_BackPressed(Callback<BackPressedHandler>(this, &QWinRTIntegration::onBackButtonPressed).Get(),
-                                             &d->buttonsTokens[&IHardwareButtonsStatics::remove_BackPressed]);
-    Q_ASSERT_SUCCEEDED(hr);
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
+#if _MSC_VER >= 1900
+    d->hasHardwareButtons = false;
+    ComPtr<IApiInformationStatics> apiInformationStatics;
+    hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Foundation_Metadata_ApiInformation).Get(),
+                                IID_PPV_ARGS(&apiInformationStatics));
 
-    hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Phone_UI_Input_HardwareButtons).Get(),
-                                IID_PPV_ARGS(&d->cameraButtons));
-    Q_ASSERT_SUCCEEDED(hr);
-    if (qEnvironmentVariableIntValue("QT_QPA_ENABLE_CAMERA_KEYS")) {
-        hr = d->cameraButtons->add_CameraPressed(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraPressed).Get(),
-                                                 &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraPressed]);
+    if (SUCCEEDED(hr)) {
+        const HStringReference valueRef(L"Windows.Phone.UI.Input.HardwareButtons");
+        hr = apiInformationStatics->IsTypePresent(valueRef.Get(), &d->hasHardwareButtons);
+    }
+#else
+    d->hasHardwareButtons = true;
+#endif // _MSC_VER >= 1900
+
+    if (d->hasHardwareButtons) {
+        hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Phone_UI_Input_HardwareButtons).Get(),
+                                    IID_PPV_ARGS(&d->hardwareButtons));
         Q_ASSERT_SUCCEEDED(hr);
-        hr = d->cameraButtons->add_CameraHalfPressed(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraHalfPressed).Get(),
-                                                     &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraHalfPressed]);
+        hr = d->hardwareButtons->add_BackPressed(Callback<BackPressedHandler>(this, &QWinRTIntegration::onBackButtonPressed).Get(),
+                                                 &d->buttonsTokens[&IHardwareButtonsStatics::remove_BackPressed]);
         Q_ASSERT_SUCCEEDED(hr);
-        hr = d->cameraButtons->add_CameraReleased(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraReleased).Get(),
-                                                  &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraReleased]);
+
+        hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Phone_UI_Input_HardwareButtons).Get(),
+                                    IID_PPV_ARGS(&d->cameraButtons));
         Q_ASSERT_SUCCEEDED(hr);
+        if (qEnvironmentVariableIntValue("QT_QPA_ENABLE_CAMERA_KEYS")) {
+            hr = d->cameraButtons->add_CameraPressed(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraPressed).Get(),
+                                                     &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraPressed]);
+            Q_ASSERT_SUCCEEDED(hr);
+            hr = d->cameraButtons->add_CameraHalfPressed(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraHalfPressed).Get(),
+                                                         &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraHalfPressed]);
+            Q_ASSERT_SUCCEEDED(hr);
+            hr = d->cameraButtons->add_CameraReleased(Callback<CameraButtonHandler>(this, &QWinRTIntegration::onCameraReleased).Get(),
+                                                      &d->cameraTokens[&IHardwareButtonsStatics2::remove_CameraReleased]);
+            Q_ASSERT_SUCCEEDED(hr);
+        }
+        d->cameraPressed = false;
+        d->cameraHalfPressed = false;
     }
-    d->cameraPressed = false;
-    d->cameraHalfPressed = false;
-#endif // Q_OS_WINPHONE
+#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
+
 
     QEventDispatcherWinRT::runOnXamlThread([d]() {
         d->mainScreen = new QWinRTScreen;
@@ -172,14 +196,17 @@ QWinRTIntegration::~QWinRTIntegration()
 {
     Q_D(QWinRTIntegration);
     HRESULT hr;
-#ifdef Q_OS_WINPHONE
-    for (QHash<HardwareButtonsCallbackRemover, EventRegistrationToken>::const_iterator i = d->buttonsTokens.begin(); i != d->buttonsTokens.end(); ++i) {
-        hr = (d->hardwareButtons.Get()->*i.key())(i.value());
-        Q_ASSERT_SUCCEEDED(hr);
-    }
-    for (QHash<HardwareButtons2CallbackRemover, EventRegistrationToken>::const_iterator i = d->cameraTokens.begin(); i != d->cameraTokens.end(); ++i) {
-        hr = (d->cameraButtons.Get()->*i.key())(i.value());
-        Q_ASSERT_SUCCEEDED(hr);
+
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
+    if (d->hasHardwareButtons) {
+        for (QHash<HardwareButtonsCallbackRemover, EventRegistrationToken>::const_iterator i = d->buttonsTokens.begin(); i != d->buttonsTokens.end(); ++i) {
+            hr = (d->hardwareButtons.Get()->*i.key())(i.value());
+            Q_ASSERT_SUCCEEDED(hr);
+        }
+        for (QHash<HardwareButtons2CallbackRemover, EventRegistrationToken>::const_iterator i = d->cameraTokens.begin(); i != d->cameraTokens.end(); ++i) {
+            hr = (d->cameraButtons.Get()->*i.key())(i.value());
+            Q_ASSERT_SUCCEEDED(hr);
+        }
     }
 #endif
     // Do not execute this on Windows Phone as the application is already
@@ -289,7 +316,7 @@ QPlatformTheme *QWinRTIntegration::createPlatformTheme(const QString &name) cons
 
 // System-level integration points
 
-#ifdef Q_OS_WINPHONE
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
 HRESULT QWinRTIntegration::onBackButtonPressed(IInspectable *, IBackPressedEventArgs *args)
 {
     Q_D(QWinRTIntegration);
@@ -339,7 +366,7 @@ HRESULT QWinRTIntegration::onCameraReleased(IInspectable *, ICameraEventArgs *)
     d->cameraPressed = false;
     return S_OK;
 }
-#endif // Q_OS_WINPHONE
+#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
 
 HRESULT QWinRTIntegration::onSuspended(IInspectable *, ISuspendingEventArgs *)
 {
diff --git a/src/plugins/platforms/winrt/qwinrtintegration.h b/src/plugins/platforms/winrt/qwinrtintegration.h
index 31a3ce7c1c4e2a8b74997cc78828e6c67721fa87..9bf5d27973e0654d3ccfdc084d50132ea099d30e 100644
--- a/src/plugins/platforms/winrt/qwinrtintegration.h
+++ b/src/plugins/platforms/winrt/qwinrtintegration.h
@@ -47,7 +47,7 @@ namespace ABI {
         namespace Foundation {
             struct IAsyncAction;
         }
-#ifdef Q_OS_WINPHONE
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
         namespace Phone {
             namespace UI {
                 namespace Input {
@@ -100,7 +100,7 @@ public:
 
     QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const Q_DECL_OVERRIDE;
 private:
-#ifdef Q_OS_WINPHONE
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
     HRESULT onBackButtonPressed(IInspectable *, ABI::Windows::Phone::UI::Input::IBackPressedEventArgs *args);
     HRESULT onCameraPressed(IInspectable *, ABI::Windows::Phone::UI::Input::ICameraEventArgs *);
     HRESULT onCameraHalfPressed(IInspectable *, ABI::Windows::Phone::UI::Input::ICameraEventArgs *);
diff --git a/src/plugins/platforms/winrt/qwinrtscreen.cpp b/src/plugins/platforms/winrt/qwinrtscreen.cpp
index 997aa0d86cf1f572773dd017d546ad8bb6602e2e..4c4d553b2d71cc3e638a93e42c601d0590c2c66f 100644
--- a/src/plugins/platforms/winrt/qwinrtscreen.cpp
+++ b/src/plugins/platforms/winrt/qwinrtscreen.cpp
@@ -1169,7 +1169,7 @@ HRESULT QWinRTScreen::onVisibilityChanged(ICoreWindow *, IVisibilityChangedEvent
     Q_D(QWinRTScreen);
     boolean visible;
     HRESULT hr = args ? args->get_Visible(&visible) : d->coreWindow->get_Visible(&visible);
-    RETURN_OK_IF_FAILED("Failed to get visbile.");
+    RETURN_OK_IF_FAILED("Failed to get visibility.");
     QWindowSystemInterface::handleApplicationStateChanged(visible ? Qt::ApplicationActive : Qt::ApplicationHidden);
     if (visible)
         handleExpose();
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
index 4cb220a02fb3efac4e6eb94d47501232e5358e1c..9bdedcc830058c3929d846a80b26992bdcb9cb67 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qglxintegration.cpp
@@ -652,7 +652,13 @@ void QGLXContext::queryDummyContext()
         oldSurface = oldContext->surface();
 
     QScopedPointer<QSurface> surface;
-    const char *glxvendor = glXGetClientString(glXGetCurrentDisplay(), GLX_VENDOR);
+    Display *display = glXGetCurrentDisplay();
+    if (!display) {
+        // FIXME: Since Qt 5.6 we don't need to check whether primary screen is NULL
+        if (QScreen *screen = QGuiApplication::primaryScreen())
+            display = DISPLAY_FROM_XCB(static_cast<QXcbScreen *>(screen->handle()));
+    }
+    const char *glxvendor = glXGetClientString(display, GLX_VENDOR);
     if (glxvendor && !strcmp(glxvendor, "ATI")) {
         QWindow *window = new QWindow;
         window->resize(64, 64);
diff --git a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxintegration.cpp b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxintegration.cpp
index ce72cb64d06adc3c3e1bee38913e25b1aea49237..a3a8aa259b9ab5c147e91b9389832fda4aecaacd 100644
--- a/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxintegration.cpp
+++ b/src/plugins/platforms/xcb/gl_integrations/xcb_glx/qxcbglxintegration.cpp
@@ -195,7 +195,12 @@ QPlatformOffscreenSurface *QXcbGlxIntegration::createPlatformOffscreenSurface(QO
     static bool glxPbufferUsable = true;
     if (!vendorChecked) {
         vendorChecked = true;
-        const char *glxvendor = glXGetClientString(glXGetCurrentDisplay(), GLX_VENDOR);
+        Display *display = glXGetCurrentDisplay();
+#ifdef XCB_USE_XLIB
+        if (!display)
+            display = static_cast<Display *>(m_connection->xlib_display());
+#endif
+        const char *glxvendor = glXGetClientString(display, GLX_VENDOR);
         if (glxvendor && !strcmp(glxvendor, "ATI"))
             glxPbufferUsable = false;
     }
diff --git a/src/plugins/platforms/xcb/qxcbbackingstore.cpp b/src/plugins/platforms/xcb/qxcbbackingstore.cpp
index 006df320febed059f2efdaf72893f08b958093de..c34bea0242394e3997d2f26981766b4d710aee50 100644
--- a/src/plugins/platforms/xcb/qxcbbackingstore.cpp
+++ b/src/plugins/platforms/xcb/qxcbbackingstore.cpp
@@ -67,6 +67,8 @@ public:
 
     QSize size() const { return m_qimage.size(); }
 
+    bool hasAlpha() const { return m_hasAlpha; }
+
     void put(xcb_window_t window, const QPoint &dst, const QRect &source);
     void preparePaint(const QRegion &region);
 
@@ -84,6 +86,8 @@ private:
     xcb_window_t m_gc_window;
 
     QRegion m_dirty;
+
+    bool m_hasAlpha;
 };
 
 class QXcbShmGraphicsBuffer : public QPlatformGraphicsBuffer
@@ -173,7 +177,8 @@ QXcbShmImage::QXcbShmImage(QXcbScreen *screen, const QSize &size, uint depth, QI
             qWarning() << "QXcbBackingStore: Error while marking the shared memory segment to be destroyed";
     }
 
-    if (QImage::toPixelFormat(format).alphaUsage() == QPixelFormat::IgnoresAlpha)
+    m_hasAlpha = QImage::toPixelFormat(format).alphaUsage() == QPixelFormat::UsesAlpha;
+    if (!m_hasAlpha)
         format = qt_alphaVersionForPainting(format);
 
     m_qimage = QImage( (uchar*) m_xcb_image->data, m_xcb_image->width, m_xcb_image->height, m_xcb_image->stride, format);
@@ -324,7 +329,7 @@ void QXcbBackingStore::beginPaint(const QRegion &region)
     m_paintRegion = region;
     m_image->preparePaint(m_paintRegion);
 
-    if (m_image->image()->hasAlphaChannel()) {
+    if (m_image->hasAlpha()) {
         QPainter p(paintDevice());
         p.setCompositionMode(QPainter::CompositionMode_Source);
         const QVector<QRect> rects = m_paintRegion.rects();
diff --git a/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp b/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
index 1b84de483448b29bbd050983bbb7bdaca1aa3339..e055ad1424f9ec51a5f4e814babd85601c920c90 100644
--- a/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
+++ b/src/plugins/platforms/xcb/qxcbconnection_xi2.cpp
@@ -867,6 +867,8 @@ void QXcbConnection::xi2HandleScrollEvent(void *event, ScrollingDevice &scrollin
                     // We do not set "pixel" delta if it is only measured in ticks.
                     if (scrollingDevice.verticalIncrement > 1)
                         rawDelta.setY(delta);
+                    else if (scrollingDevice.verticalIncrement < -1)
+                        rawDelta.setY(-delta);
                 }
             }
             if (scrollingDevice.orientations & Qt::Horizontal) {
@@ -877,6 +879,8 @@ void QXcbConnection::xi2HandleScrollEvent(void *event, ScrollingDevice &scrollin
                     // We do not set "pixel" delta if it is only measured in ticks.
                     if (scrollingDevice.horizontalIncrement > 1)
                         rawDelta.setX(delta);
+                    else if (scrollingDevice.horizontalIncrement < -1)
+                        rawDelta.setX(-delta);
                 }
             }
             if (!angleDelta.isNull()) {
diff --git a/src/plugins/platforms/xcb/qxcbwindow.cpp b/src/plugins/platforms/xcb/qxcbwindow.cpp
index 4e4a0cdaefdab0f8af8f47d2fe68884cf905e652..c6eb5aa66b91e8e92a17875111011d395b67d282 100644
--- a/src/plugins/platforms/xcb/qxcbwindow.cpp
+++ b/src/plugins/platforms/xcb/qxcbwindow.cpp
@@ -1885,6 +1885,17 @@ private:
     bool m_pending;
 };
 
+bool QXcbWindow::compressExposeEvent(QRegion &exposeRegion)
+{
+    ExposeCompressor compressor(m_window, &exposeRegion);
+    xcb_generic_event_t *filter = 0;
+    do {
+        filter = connection()->checkEvent(compressor);
+        free(filter);
+    } while (filter);
+    return compressor.pending();
+}
+
 bool QXcbWindow::handleGenericEvent(xcb_generic_event_t *event, long *result)
 {
     return QWindowSystemInterface::handleNativeEvent(window(),
@@ -1902,15 +1913,10 @@ void QXcbWindow::handleExposeEvent(const xcb_expose_event_t *event)
     else
         m_exposeRegion |= rect;
 
-    ExposeCompressor compressor(m_window, &m_exposeRegion);
-    xcb_generic_event_t *filter = 0;
-    do {
-        filter = connection()->checkEvent(compressor);
-        free(filter);
-    } while (filter);
+    bool pending = compressExposeEvent(m_exposeRegion);
 
     // if count is non-zero there are more expose events pending
-    if (event->count == 0 || !compressor.pending()) {
+    if (event->count == 0 || !pending) {
         QWindowSystemInterface::handleExposeEvent(window(), m_exposeRegion);
         m_exposeRegion = QRegion();
     }
@@ -1997,10 +2003,6 @@ void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *
         }
     }
 
-    // The original geometry requested by setGeometry() might be different
-    // from what we end up with after applying window constraints.
-    QRect requestedGeometry = geometry();
-
     const QRect actualGeometry = QRect(pos, QSize(event->width, event->height));
     QPlatformScreen *newScreen = parent() ? parent()->screen() : screenForGeometry(actualGeometry);
     if (!newScreen)
@@ -2021,15 +2023,6 @@ void QXcbWindow::handleConfigureNotifyEvent(const xcb_configure_notify_event_t *
     // will make the comparison later.
     QWindowSystemInterface::handleWindowScreenChanged(window(), newScreen->screen());
 
-    // For expose events we have no way of telling QGuiApplication to used the locally
-    // cached version of the previous state, so we may in some situations end up with
-    // an additional expose event.
-    QRect previousGeometry = requestedGeometry != actualGeometry ?
-        requestedGeometry : qt_window_private(window())->geometry;
-
-    if (m_mapped && actualGeometry.size() != previousGeometry.size())
-        QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), actualGeometry.size()));
-
     if (m_usingSyncProtocol && m_syncState == SyncReceived)
         m_syncState = SyncAndConfigureReceived;
 
@@ -2096,7 +2089,9 @@ void QXcbWindow::handleMapNotifyEvent(const xcb_map_notify_event_t *event)
         if (m_deferredActivation)
             requestActivateWindow();
 
-        QWindowSystemInterface::handleExposeEvent(window(), QRect(QPoint(), geometry().size()));
+        QRegion exposeRegion = QRect(QPoint(), geometry().size());
+        compressExposeEvent(exposeRegion);
+        QWindowSystemInterface::handleExposeEvent(window(), exposeRegion);
     }
 }
 
diff --git a/src/plugins/platforms/xcb/qxcbwindow.h b/src/plugins/platforms/xcb/qxcbwindow.h
index 3cfa71c9e014af6a69e4f3a24eb4b51453698b60..d2c02fe3df4e0d0667711dfa9bfc10fed30d9554 100644
--- a/src/plugins/platforms/xcb/qxcbwindow.h
+++ b/src/plugins/platforms/xcb/qxcbwindow.h
@@ -201,6 +201,8 @@ protected:
     void doFocusIn();
     void doFocusOut();
 
+    bool compressExposeEvent(QRegion &exposeRegion);
+
     void handleButtonPressEvent(int event_x, int event_y, int root_x, int root_y,
                                 int detail, Qt::KeyboardModifiers modifiers, xcb_timestamp_t timestamp);
 
diff --git a/src/printsupport/dialogs/qprintdialog_unix.cpp b/src/printsupport/dialogs/qprintdialog_unix.cpp
index 9633032a0f49d3720f73d527a2af8b2d257f6e02..b96d8dfd22faeeba59738888727838424439cdf5 100644
--- a/src/printsupport/dialogs/qprintdialog_unix.cpp
+++ b/src/printsupport/dialogs/qprintdialog_unix.cpp
@@ -118,9 +118,6 @@ public:
     void applyPrinterProperties(QPrinter *p);
     void setupPrinter() const;
 
-protected:
-    void showEvent(QShowEvent* event) Q_DECL_OVERRIDE;
-
 private:
     friend class QUnixPrintWidgetPrivate;
     Ui::QPrintPropertiesWidget widget;
@@ -274,11 +271,6 @@ void QPrintPropertiesDialog::selectPrinter(QPrinter::OutputFormat outputFormat,
     widget.pageSetup->selectPrinter(outputFormat, printerName);
 }
 
-void QPrintPropertiesDialog::showEvent(QShowEvent* event)
-{
-    event->accept();
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////////
 
diff --git a/src/sql/drivers/psql/qsql_psql.cpp b/src/sql/drivers/psql/qsql_psql.cpp
index 5dcabb06468242e018989dc39d35a805616e4b5f..de1f1638fd28871e8255f9b9d7e79c96a6a21720 100644
--- a/src/sql/drivers/psql/qsql_psql.cpp
+++ b/src/sql/drivers/psql/qsql_psql.cpp
@@ -757,6 +757,7 @@ QPSQLDriver::Protocol QPSQLDriverPrivate::getPSQLVersion()
                     //Client version before QPSQLDriver::Version9 only supports escape mode for bytea type,
                     //but bytea format is set to hex by default in PSQL 9 and above. So need to force the
                     //server use the old escape mode when connects to the new server with old client library.
+                    PQclear(result);
                     result = exec("SET bytea_output=escape; ");
                     status = PQresultStatus(result);
                 } else if (serverVersion == QPSQLDriver::VersionUnknown) {
diff --git a/src/testlib/qtestcase.cpp b/src/testlib/qtestcase.cpp
index 98a14f845903fca677c055bd3e9bbcabf9c82523..ae340122673d642141cb88c48cb8281ca4649c61 100644
--- a/src/testlib/qtestcase.cpp
+++ b/src/testlib/qtestcase.cpp
@@ -3219,7 +3219,7 @@ QString QTest::qFindTestData(const QString& base, const char *file, int line, co
             QString testsPath = QLibraryInfo::location(QLibraryInfo::TestsPath);
             QString candidate = QString::fromLatin1("%1/%2/%3")
                 .arg(testsPath, QFile::decodeName(testObjectName).toLower(), base);
-            if (QFileInfo(candidate).exists()) {
+            if (QFileInfo::exists(candidate)) {
                 found = candidate;
             }
             else if (QTestLog::verboseLevel() >= 2) {
@@ -3244,7 +3244,7 @@ QString QTest::qFindTestData(const QString& base, const char *file, int line, co
         }
 
         QString candidate = QString::fromLatin1("%1/%2").arg(srcdir.canonicalFilePath(), base);
-        if (QFileInfo(candidate).exists()) {
+        if (QFileInfo::exists(candidate)) {
             found = candidate;
         }
         else if (QTestLog::verboseLevel() >= 2) {
@@ -3258,21 +3258,21 @@ QString QTest::qFindTestData(const QString& base, const char *file, int line, co
     // 4. Try resources
     if (found.isEmpty()) {
         QString candidate = QString::fromLatin1(":/%1").arg(base);
-        if (QFileInfo(candidate).exists())
+        if (QFileInfo::exists(candidate))
             found = candidate;
     }
 
     // 5. Try current directory
     if (found.isEmpty()) {
         QString candidate = QString::fromLatin1("%1/%2").arg(QDir::currentPath()).arg(base);
-        if (QFileInfo(candidate).exists())
+        if (QFileInfo::exists(candidate))
             found = candidate;
     }
 
     // 6. Try main source directory
     if (found.isEmpty()) {
         QString candidate = QTest::mainSourcePath % QLatin1Char('/') % base;
-        if (QFileInfo(candidate).exists())
+        if (QFileInfo::exists(candidate))
             found = candidate;
     }
 
diff --git a/src/tools/moc/generator.cpp b/src/tools/moc/generator.cpp
index 5be58d3c4bd50aa6b5913d602ec0dcce299dfa98..99629f0427b25f47730d77cb2641f9fc490de399 100644
--- a/src/tools/moc/generator.cpp
+++ b/src/tools/moc/generator.cpp
@@ -1254,6 +1254,7 @@ void Generator::generateStaticMetacall()
             fprintf(out, "            if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&%s::%s)) {\n",
                     cdef->classname.constData(), f.name.constData());
             fprintf(out, "                *result = %d;\n", methodindex);
+            fprintf(out, "                return;\n");
             fprintf(out, "            }\n        }\n");
         }
         if (!anythingUsed)
diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp
index bdfa27282f257d6accfaf08699b55d1ba719f406..06102ec1d6f013839011a95fd8f55e349e92a30d 100644
--- a/src/widgets/dialogs/qfiledialog.cpp
+++ b/src/widgets/dialogs/qfiledialog.cpp
@@ -2822,7 +2822,9 @@ void QFileDialogPrivate::init(const QUrl &directory, const QString &nameFilter,
     qFileDialogUi->sidebar->hide();
 #endif
 
-    q->resize(q->sizeHint());
+    const QSize sizeHint = q->sizeHint();
+    if (sizeHint.isValid())
+       q->resize(sizeHint);
 }
 
 /*!
diff --git a/src/widgets/itemviews/qdirmodel.cpp b/src/widgets/itemviews/qdirmodel.cpp
index 0c157c940f5bf39e5e2a72289dc5c6ced28c0523..ac23e22ef715cefea301bca90bd0e2aa91148033 100644
--- a/src/widgets/itemviews/qdirmodel.cpp
+++ b/src/widgets/itemviews/qdirmodel.cpp
@@ -862,7 +862,7 @@ QModelIndex QDirModel::index(const QString &path, int column) const
 #endif
 
     QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts);
-    if ((pathElements.isEmpty() || !QFileInfo(path).exists())
+    if ((pathElements.isEmpty() || !QFileInfo::exists(path))
 #if !defined(Q_OS_WIN) || defined(Q_OS_WINCE)
         && path != QLatin1String("/")
 #endif
diff --git a/src/widgets/itemviews/qtreeview.cpp b/src/widgets/itemviews/qtreeview.cpp
index 57092a7cdcabbfdc0ec8761e795469c20dba2c33..0ccb98919882a4d1c6aef1aa55035e62b7ba5e77 100644
--- a/src/widgets/itemviews/qtreeview.cpp
+++ b/src/widgets/itemviews/qtreeview.cpp
@@ -2830,10 +2830,14 @@ void QTreeView::updateGeometries()
         if (d->geometryRecursionBlock)
             return;
         d->geometryRecursionBlock = true;
-        QSize hint = d->header->isHidden() ? QSize(0, 0) : d->header->sizeHint();
-        setViewportMargins(0, hint.height(), 0, 0);
+        int height = 0;
+        if (!d->header->isHidden()) {
+            height = qMax(d->header->minimumHeight(), d->header->sizeHint().height());
+            height = qMin(height, d->header->maximumHeight());
+        }
+        setViewportMargins(0, height, 0, 0);
         QRect vg = d->viewport->geometry();
-        QRect geometryRect(vg.left(), vg.top() - hint.height(), vg.width(), hint.height());
+        QRect geometryRect(vg.left(), vg.top() - height, vg.width(), height);
         d->header->setGeometry(geometryRect);
         QMetaObject::invokeMethod(d->header, "updateGeometries");
         d->updateScrollBars();
diff --git a/src/widgets/kernel/qaction.cpp b/src/widgets/kernel/qaction.cpp
index 2c4e4d312594dc1f9e4c7cd37e83f008cae1b60c..1ef9e4ef989d16c82801641bc2243dadfbc1d60a 100644
--- a/src/widgets/kernel/qaction.cpp
+++ b/src/widgets/kernel/qaction.cpp
@@ -39,10 +39,10 @@
 #include "qapplication.h"
 #include "qevent.h"
 #include "qlist.h"
-#include "qdebug.h"
 #include <private/qshortcutmap_p.h>
 #include <private/qapplication_p.h>
 #include <private/qmenu_p.h>
+#include <private/qdebug_p.h>
 
 #define QAPP_CHECK(functionName) \
     if (!qApp) { \
@@ -1296,6 +1296,31 @@ bool QAction::isIconVisibleInMenu() const
     return d->iconVisibleInMenu;
 }
 
+#ifndef QT_NO_DEBUG_STREAM
+Q_WIDGETS_EXPORT QDebug operator<<(QDebug d, const QAction *action)
+{
+    QDebugStateSaver saver(d);
+    d.nospace();
+    d << "QAction(" << static_cast<const void *>(action);
+    if (action) {
+        d << " text=" << action->text();
+        if (!action->toolTip().isEmpty())
+            d << " toolTip=" << action->toolTip();
+        if (action->isCheckable())
+            d << " checked=" << action->isChecked();
+        if (!action->shortcut().isEmpty())
+            d << " shortcut=" << action->shortcut();
+        d << " menuRole=";
+        QtDebugUtils::formatQEnum(d, action->menuRole());
+        d << " visible=" << action->isVisible();
+    } else {
+        d << '0';
+    }
+    d << ')';
+    return d;
+}
+#endif // QT_NO_DEBUG_STREAM
+
 QT_END_NAMESPACE
 
 #include "moc_qaction.cpp"
diff --git a/src/widgets/kernel/qaction.h b/src/widgets/kernel/qaction.h
index 8ef26b60bf1c2af11a793e92737f35d45186ea59..0eb2c60c7057d2ae76c917c0170a2c12e6a82125 100644
--- a/src/widgets/kernel/qaction.h
+++ b/src/widgets/kernel/qaction.h
@@ -203,6 +203,10 @@ private:
 #endif
 };
 
+#ifndef QT_NO_DEBUG_STREAM
+Q_WIDGETS_EXPORT QDebug operator<<(QDebug, const QAction *);
+#endif
+
 QT_BEGIN_INCLUDE_NAMESPACE
 #include <QtWidgets/qactiongroup.h>
 QT_END_INCLUDE_NAMESPACE
diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp
index e20e820f12a1f914b84f575dd665fff81e499f02..91302d9e62ebe3d34a77cd681a30e7e9ea96b259 100644
--- a/src/widgets/kernel/qapplication.cpp
+++ b/src/widgets/kernel/qapplication.cpp
@@ -478,22 +478,24 @@ void QApplicationPrivate::process_cmdline()
 
     j = 1;
     for (i=1; i<argc; i++) { // if you add anything here, modify QCoreApplication::arguments()
-        if (argv[i] && *argv[i] != '-') {
+        if (!argv[i])
+            continue;
+        if (*argv[i] != '-') {
             argv[j++] = argv[i];
             continue;
         }
-        QByteArray arg = argv[i];
-        if (arg.startsWith("--"))
-            arg.remove(0, 1);
-        if (arg == "-qdevel" || arg == "-qdebug") {
+        const char *arg = argv[i];
+        if (arg[1] == '-') // startsWith("--")
+            ++arg;
+        if (strcmp(arg, "-qdevel") == 0 || strcmp(arg, "-qdebug") == 0) {
             // obsolete argument
 #ifndef QT_NO_STYLE_STYLESHEET
-        } else if (arg == "-stylesheet" && i < argc -1) {
+        } else if (strcmp(arg, "-stylesheet") == 0 && i < argc -1) {
             styleSheet = QLatin1String("file:///");
             styleSheet.append(QString::fromLocal8Bit(argv[++i]));
-        } else if (arg.indexOf("-stylesheet=") != -1) {
+        } else if (strncmp(arg, "-stylesheet=", 12) == 0) {
             styleSheet = QLatin1String("file:///");
-            styleSheet.append(QString::fromLocal8Bit(arg.right(arg.length() - 12)));
+            styleSheet.append(QString::fromLocal8Bit(arg + 12));
 #endif
         } else if (qstrcmp(arg, "-widgetcount") == 0) {
             widgetCount = true;
diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp
index 229cfc0f85818fe4ed6cf60194a57b66c8400e5e..5bff30524a728cae3bff096259407ed50953d336 100644
--- a/src/widgets/kernel/qwidget.cpp
+++ b/src/widgets/kernel/qwidget.cpp
@@ -1487,9 +1487,12 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO
     if (extra && !extra->mask.isEmpty())
         setMask_sys(extra->mask);
 
-    // If widget is already shown, set window visible, too
-    if (q->isVisible())
+    if (data.crect.width() == 0 || data.crect.height() == 0) {
+        q->setAttribute(Qt::WA_OutsideWSRange, true);
+    } else if (q->isVisible()) {
+        // If widget is already shown, set window visible, too
         win->setVisible(true);
+    }
 }
 
 #ifdef Q_OS_WIN
@@ -7210,7 +7213,7 @@ void QWidgetPrivate::setGeometry_sys(int x, int y, int w, int h, bool isMove)
     if (q->isWindow() || q->windowHandle()) {
         if (!(data.window_state & Qt::WindowFullScreen) && (w == 0 || h == 0)) {
             q->setAttribute(Qt::WA_OutsideWSRange, true);
-            if (q->isVisible() && q->testAttribute(Qt::WA_Mapped))
+            if (q->isVisible())
                 hide_sys();
             data.crect = QRect(x, y, w, h);
         } else if (q->isVisible() && q->testAttribute(Qt::WA_OutsideWSRange)) {
@@ -7927,8 +7930,10 @@ void QWidgetPrivate::show_sys()
     else
         QApplication::postEvent(q, new QUpdateLaterEvent(q->rect()));
 
-    if (!q->isWindow() && !q->testAttribute(Qt::WA_NativeWindow))
+    if ((!q->isWindow() && !q->testAttribute(Qt::WA_NativeWindow))
+            || q->testAttribute(Qt::WA_OutsideWSRange)) {
         return;
+    }
 
     if (window) {
         if (q->isWindow())
@@ -9141,6 +9146,9 @@ bool QWidget::event(QEvent *event)
             const QWindow *win = te->window;
             d->setWinId((win && win->handle()) ? win->handle()->winId() : 0);
         }
+#ifndef QT_NO_OPENGL
+        d->renderToTextureReallyDirty = 1;
+#endif
         break;
 #ifndef QT_NO_PROPERTIES
     case QEvent::DynamicPropertyChange: {
@@ -12344,21 +12352,20 @@ static inline bool canMapPosition(QWindow *window)
 */
 QPoint QWidget::mapToGlobal(const QPoint &pos) const
 {
-    int x = pos.x(), y = pos.y();
-    const QWidget *w = this;
-    while (w) {
 #ifndef QT_NO_GRAPHICSVIEW
-        const QWidgetPrivate *d = w->d_func();
-        if (d->extra && d->extra->proxyWidget && d->extra->proxyWidget->scene()) {
-            const QList <QGraphicsView *> views = d->extra->proxyWidget->scene()->views();
-            if (!views.isEmpty()) {
-                const QPointF scenePos = d->extra->proxyWidget->mapToScene(QPoint(x, y));
-                const QPoint viewPortPos = views.first()->mapFromScene(scenePos);
-                return views.first()->viewport()->mapToGlobal(viewPortPos);
-            }
+    Q_D(const QWidget);
+    if (d->extra && d->extra->proxyWidget && d->extra->proxyWidget->scene()) {
+        const QList <QGraphicsView *> views = d->extra->proxyWidget->scene()->views();
+        if (!views.isEmpty()) {
+            const QPointF scenePos = d->extra->proxyWidget->mapToScene(pos);
+            const QPoint viewPortPos = views.first()->mapFromScene(scenePos);
+            return views.first()->viewport()->mapToGlobal(viewPortPos);
         }
+    }
 #endif // !QT_NO_GRAPHICSVIEW
-
+    int x = pos.x(), y = pos.y();
+    const QWidget *w = this;
+    while (w) {
         QWindow *window = w->windowHandle();
         if (window && canMapPosition(window))
             return window->mapToGlobal(QPoint(x, y));
@@ -12380,21 +12387,20 @@ QPoint QWidget::mapToGlobal(const QPoint &pos) const
 */
 QPoint QWidget::mapFromGlobal(const QPoint &pos) const
 {
-    int x = pos.x(), y = pos.y();
-    const QWidget *w = this;
-    while (w) {
 #ifndef QT_NO_GRAPHICSVIEW
-        const QWidgetPrivate *d = w->d_func();
-        if (d->extra && d->extra->proxyWidget && d->extra->proxyWidget->scene()) {
-            const QList <QGraphicsView *> views = d->extra->proxyWidget->scene()->views();
-            if (!views.isEmpty()) {
-                const QPoint viewPortPos = views.first()->viewport()->mapFromGlobal(QPoint(x, y));
-                const QPointF scenePos = views.first()->mapToScene(viewPortPos);
-                return d->extra->proxyWidget->mapFromScene(scenePos).toPoint();
-            }
+    Q_D(const QWidget);
+    if (d->extra && d->extra->proxyWidget && d->extra->proxyWidget->scene()) {
+        const QList <QGraphicsView *> views = d->extra->proxyWidget->scene()->views();
+        if (!views.isEmpty()) {
+            const QPoint viewPortPos = views.first()->viewport()->mapFromGlobal(pos);
+            const QPointF scenePos = views.first()->mapToScene(viewPortPos);
+            return d->extra->proxyWidget->mapFromScene(scenePos).toPoint();
         }
+    }
 #endif // !QT_NO_GRAPHICSVIEW
-
+    int x = pos.x(), y = pos.y();
+    const QWidget *w = this;
+    while (w) {
         QWindow *window = w->windowHandle();
         if (window && canMapPosition(window))
             return window->mapFromGlobal(QPoint(x, y));
diff --git a/src/widgets/kernel/qwidgetbackingstore.cpp b/src/widgets/kernel/qwidgetbackingstore.cpp
index 3f7f9291b679de3d6c8a0a08a63f1b1bc7ae119a..d9d1c887c1f526a9b7696503dab6a4c52a8101ef 100644
--- a/src/widgets/kernel/qwidgetbackingstore.cpp
+++ b/src/widgets/kernel/qwidgetbackingstore.cpp
@@ -1079,7 +1079,8 @@ void QWidgetBackingStore::sync(QWidget *exposedWidget, const QRegion &exposedReg
 
     // Nothing to repaint.
     if (!isDirty() && store->size().isValid()) {
-        qt_flush(exposedWidget, exposedRegion, store, tlw, tlwOffset, widgetTexturesFor(tlw, tlw), this);
+        QPlatformTextureList *tl = widgetTexturesFor(tlw, exposedWidget);
+        qt_flush(exposedWidget, tl ? QRegion() : exposedRegion, store, tlw, tlwOffset, tl, this);
         return;
     }
 
@@ -1250,9 +1251,17 @@ void QWidgetBackingStore::doSync()
         for (int i = 0; i < paintPending.count(); ++i) {
             QWidget *w = paintPending[i];
             w->d_func()->sendPaintEvent(w->rect());
-            QWidget *npw = w->nativeParentWidget();
-            if (w->internalWinId() || (npw && npw != tlw))
-                markDirtyOnScreen(w->rect(), w, w->mapTo(tlw, QPoint()));
+            if (w != tlw) {
+                QWidget *npw = w->nativeParentWidget();
+                if (w->internalWinId() || (npw && npw != tlw)) {
+                    if (!w->internalWinId())
+                        w = npw;
+                    QWidgetPrivate *wPrivate = w->d_func();
+                    if (!wPrivate->needsFlush)
+                        wPrivate->needsFlush = new QRegion;
+                    appendDirtyOnScreenWidget(w);
+                }
+            }
         }
 
         // We might have newly exposed areas on the screen if this function was
@@ -1277,13 +1286,8 @@ void QWidgetBackingStore::doSync()
             }
         }
     }
-    for (int i = 0; i < dirtyRenderToTextureWidgets.count(); ++i) {
-        QWidget *w = dirtyRenderToTextureWidgets.at(i);
-        resetWidget(w);
-        QWidget *npw = w->nativeParentWidget();
-        if (w->internalWinId() || (npw && npw != tlw))
-            markDirtyOnScreen(w->rect(), w, w->mapTo(tlw, QPoint()));
-    }
+    for (int i = 0; i < dirtyRenderToTextureWidgets.count(); ++i)
+        resetWidget(dirtyRenderToTextureWidgets.at(i));
     dirtyRenderToTextureWidgets.clear();
 #endif
 
diff --git a/src/widgets/kernel/qwidgetwindow.cpp b/src/widgets/kernel/qwidgetwindow.cpp
index 3637b76aa9c8f0f1f8cc39cf54b0c614f1350282..6f8d97e0289adb8ecf5612f25d493e213e00d54d 100644
--- a/src/widgets/kernel/qwidgetwindow.cpp
+++ b/src/widgets/kernel/qwidgetwindow.cpp
@@ -445,7 +445,7 @@ void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
                 receiver = popupChild;
             if (receiver != popup)
                 widgetPos = receiver->mapFromGlobal(event->globalPos());
-            QWidget *alien = receiver->childAt(receiver->mapFromGlobal(event->globalPos()));
+            QWidget *alien = m_widget->childAt(m_widget->mapFromGlobal(event->globalPos()));
             QMouseEvent e(event->type(), widgetPos, event->windowPos(), event->screenPos(),
                           event->button(), event->buttons(), event->modifiers(), event->source());
             e.setTimestamp(event->timestamp());
diff --git a/src/widgets/styles/qwindowsvistastyle.cpp b/src/widgets/styles/qwindowsvistastyle.cpp
index 083b1d170740b6ce72097daea786acf4cc4f188f..3fa0fc899db404197edd8b1cc12e45a85d473cb5 100644
--- a/src/widgets/styles/qwindowsvistastyle.cpp
+++ b/src/widgets/styles/qwindowsvistastyle.cpp
@@ -398,7 +398,7 @@ void QWindowsVistaStyle::drawPrimitive(PrimitiveElement element, const QStyleOpt
         {
             XPThemeData theme(widget, painter, QWindowsXPStylePrivate::TreeViewTheme);
             static int decoration_size = 0;
-            if (d->initTreeViewTheming() && theme.isValid() && !decoration_size) {
+            if (!decoration_size && d->initTreeViewTheming() && theme.isValid()) {
                 XPThemeData themeSize = theme;
                 themeSize.partId = TVP_HOTGLYPH;
                 themeSize.stateId = GLPS_OPENED;
diff --git a/src/widgets/util/qsystemtrayicon.cpp b/src/widgets/util/qsystemtrayicon.cpp
index 31bbbb97396d18642740b3ce5eab412ea9981dc5..ebb29211a4c531a35e5d6ee64b6b5ce63073cc76 100644
--- a/src/widgets/util/qsystemtrayicon.cpp
+++ b/src/widgets/util/qsystemtrayicon.cpp
@@ -687,6 +687,10 @@ void QSystemTrayIconPrivate::install_sys_qpa()
 
 void QSystemTrayIconPrivate::remove_sys_qpa()
 {
+    QObject::disconnect(qpa_sys, SIGNAL(activated(QPlatformSystemTrayIcon::ActivationReason)),
+                        q_func(), SLOT(_q_emitActivated(QPlatformSystemTrayIcon::ActivationReason)));
+    QObject::disconnect(qpa_sys, &QPlatformSystemTrayIcon::messageClicked,
+                        q_func(), &QSystemTrayIcon::messageClicked);
     qpa_sys->cleanup();
 }
 
diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp
index ed3af90532181edf8d49ede369ea61317bee5075..35c54f102fa6459828065a577d886fe6e43c6406 100644
--- a/src/widgets/widgets/qcombobox.cpp
+++ b/src/widgets/widgets/qcombobox.cpp
@@ -2432,7 +2432,11 @@ struct IndexSetter {
     int index;
     QComboBox *cb;
 
-    void operator()(void) { cb->setCurrentIndex(index); }
+    void operator()(void)
+    {
+        cb->setCurrentIndex(index);
+        emit cb->activated(index);
+    }
 };
 }
 
diff --git a/src/widgets/widgets/qfocusframe.cpp b/src/widgets/widgets/qfocusframe.cpp
index 5a403fa669fa4952ad443b1e5de54cc186da9e86..bf8cb30ef77eced64b4374afd27d89c4bba14c47 100644
--- a/src/widgets/widgets/qfocusframe.cpp
+++ b/src/widgets/widgets/qfocusframe.cpp
@@ -250,6 +250,10 @@ void
 QFocusFrame::paintEvent(QPaintEvent *)
 {
     Q_D(QFocusFrame);
+
+    if (!d->widget)
+        return;
+
     QStylePainter p(this);
     QStyleOption option;
     initStyleOption(&option);
diff --git a/src/widgets/widgets/qmainwindowlayout.cpp b/src/widgets/widgets/qmainwindowlayout.cpp
index 54e956c4cff199cfa3a8ea7632d5f86dd7fbfb8b..1bb8496505f41c3486a11a9d7904c3c80387f46e 100644
--- a/src/widgets/widgets/qmainwindowlayout.cpp
+++ b/src/widgets/widgets/qmainwindowlayout.cpp
@@ -2252,17 +2252,18 @@ void QMainWindowLayout::setCentralWidget(QWidget *widget)
 QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, bool group)
 {
 #if !defined(QT_NO_DOCKWIDGET) && !defined(QT_NO_TABBAR)
-    QDockWidgetGroupWindow *floatingParent = qobject_cast<QDockWidgetGroupWindow *>(widget->parentWidget());
-    if (group && floatingParent && !widget->isWindow()) {
-        // We are just dragging a floating window as it, not need to do anything, we just have to
-        // look up the corresponding QWidgetItem* if it exists
-        QList<int> tabbedWindowPath = layoutState.indexOf(widget->parentWidget());
-        return tabbedWindowPath.isEmpty() ? 0 : layoutState.item(tabbedWindowPath);
-    } else if (floatingParent) {
-        // We are unplugging a dock widget from a floating window.
-        if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
-            dw->d_func()->unplug(widget->geometry());
-            return 0;
+    if (!widget->isWindow() && qobject_cast<const QDockWidgetGroupWindow *>(widget->parentWidget())) {
+        if (group) {
+            // We are just dragging a floating window as it, not need to do anything, we just have to
+            // look up the corresponding QWidgetItem* if it exists
+            QList<int> tabbedWindowPath = layoutState.indexOf(widget->parentWidget());
+            return tabbedWindowPath.isEmpty() ? 0 : layoutState.item(tabbedWindowPath);
+        } else {
+            // We are unplugging a dock widget from a floating window.
+            if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
+                dw->d_func()->unplug(widget->geometry());
+                return 0;
+            }
         }
     }
 #endif
diff --git a/src/xml/sax/sax.pri b/src/xml/sax/sax.pri
index 65916271bda026fc4c1b9288d67dae9d43ba1f33..5793996898292e9e9b397a7992a6cdf58323a9cd 100644
--- a/src/xml/sax/sax.pri
+++ b/src/xml/sax/sax.pri
@@ -1,2 +1,3 @@
 SOURCES += $$PWD/qxml.cpp
-HEADERS += $$PWD/qxml.h
+HEADERS += $$PWD/qxml_p.h \
+           $$PWD/qxml.h
diff --git a/tests/auto/cmake/CMakeLists.txt b/tests/auto/cmake/CMakeLists.txt
index 3a607983f98b12a765f44987996a94dfbd27dae6..5248f75a84ade7e764615bc255945ba0dd5b9f4f 100644
--- a/tests/auto/cmake/CMakeLists.txt
+++ b/tests/auto/cmake/CMakeLists.txt
@@ -50,7 +50,9 @@ include("${_Qt5CTestMacros}")
 if(NOT ${CMAKE_VERSION} VERSION_LESS 2.8.9)
     # Requires INCLUDE_DIRECTORIES target property in CMake 2.8.8
     # and POSITION_INDEPENDENT_CODE target property in 2.8.9
-    expect_pass(test_use_modules_function)
+    if (NOT NO_GUI)
+        expect_pass(test_use_modules_function)
+    endif()
     expect_pass(test_umbrella_config)
 else()
     message("CMake version older than 2.8.9 (Found ${CMAKE_VERSION}). Not running test \"test_use_modules_function\" or \"test_umbrella_config\"")
diff --git a/tests/auto/corelib/codecs/qtextcodec/tst_qtextcodec.cpp b/tests/auto/corelib/codecs/qtextcodec/tst_qtextcodec.cpp
index 3aa06d237dc04319c437b1c2b683f0f46ed48b0d..8a9ae0cd72baef5d13ae51e26dad4f9fed9740fb 100644
--- a/tests/auto/corelib/codecs/qtextcodec/tst_qtextcodec.cpp
+++ b/tests/auto/corelib/codecs/qtextcodec/tst_qtextcodec.cpp
@@ -1588,10 +1588,17 @@ void tst_QTextCodec::utf8bom_data()
             << QString("a");
     }
 
-    {
+    { // test the non-SIMD code-path
         static const ushort data[] = { 0x61, 0xfeff, 0x62 };
-        QTest::newRow("middle-bom")
-            << QByteArray("a\357\273\277b", 5)
+        QTest::newRow("middle-bom (non SIMD)")
+            << QByteArray("a\357\273\277b")
+            << QString::fromUtf16(data, sizeof(data)/sizeof(short));
+    }
+
+    { // test the SIMD code-path
+        static const ushort data[] = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0xfeff, 0x6d };
+        QTest::newRow("middle-bom (SIMD)")
+            << QByteArray("abcdefghijkl\357\273\277m")
             << QString::fromUtf16(data, sizeof(data)/sizeof(short));
     }
 }
diff --git a/tests/auto/corelib/io/io.pro b/tests/auto/corelib/io/io.pro
index 24592238bd25a65d9afe39ba6f80d11a47623ab2..29717b3a1c708ac59712bfe65023f92abea8d5c2 100644
--- a/tests/auto/corelib/io/io.pro
+++ b/tests/auto/corelib/io/io.pro
@@ -63,4 +63,5 @@ winrt: SUBDIRS -= \
     qprocess \
     qprocess-noapplication \
     qprocessenvironment \
+    qstorageinfo \
     qwinoverlappedionotifier
diff --git a/tests/auto/corelib/io/largefile/tst_largefile.cpp b/tests/auto/corelib/io/largefile/tst_largefile.cpp
index 0a28ee7b9cfecb75e301415798c0db26c4587073..afbb307f033b2ff3710babd44a552a1c5494fbbc 100644
--- a/tests/auto/corelib/io/largefile/tst_largefile.cpp
+++ b/tests/auto/corelib/io/largefile/tst_largefile.cpp
@@ -70,7 +70,7 @@ public:
         , fd_(-1)
         , stream_(0)
     {
-    #if defined(QT_LARGEFILE_SUPPORT) && !defined(Q_OS_MAC)
+    #if defined(QT_LARGEFILE_SUPPORT) && !defined(Q_OS_MAC) && !defined(Q_OS_WINRT)
         maxSizeBits = 36; // 64 GiB
     #elif defined(Q_OS_MAC)
         // HFS+ does not support sparse files, so we limit file size for the test
@@ -135,6 +135,9 @@ private:
 
     int fd_;
     FILE *stream_;
+
+    QSharedPointer<QTemporaryDir> m_tempDir;
+    QString m_previousCurrent;
 };
 
 /*
@@ -229,6 +232,11 @@ QByteArray const &tst_LargeFile::getDataBlock(int index, qint64 position)
 
 void tst_LargeFile::initTestCase()
 {
+    m_previousCurrent = QDir::currentPath();
+    m_tempDir = QSharedPointer<QTemporaryDir>(new QTemporaryDir);
+    QVERIFY2(!m_tempDir.isNull(), qPrintable("Could not create temporary directory."));
+    QVERIFY2(QDir::setCurrent(m_tempDir->path()), qPrintable("Could not switch current directory"));
+
     QFile file("qt_largefile.tmp");
     QVERIFY( !file.exists() || file.remove() );
 }
@@ -240,6 +248,8 @@ void tst_LargeFile::cleanupTestCase()
 
     QFile file("qt_largefile.tmp");
     QVERIFY( !file.exists() || file.remove() );
+
+    QDir::setCurrent(m_previousCurrent);
 }
 
 void tst_LargeFile::init()
diff --git a/tests/auto/corelib/io/qabstractfileengine/tst_qabstractfileengine.cpp b/tests/auto/corelib/io/qabstractfileengine/tst_qabstractfileengine.cpp
index 977c396e21e3ff7d3165bd35959cfc4d58cf349e..8c4c8b48d7620ed2cc4b1c0df670039e40fa8b0b 100644
--- a/tests/auto/corelib/io/qabstractfileengine/tst_qabstractfileengine.cpp
+++ b/tests/auto/corelib/io/qabstractfileengine/tst_qabstractfileengine.cpp
@@ -52,6 +52,7 @@ class tst_QAbstractFileEngine
 {
     Q_OBJECT
 public slots:
+    void initTestCase();
     void cleanupTestCase();
 
 private slots:
@@ -64,6 +65,8 @@ private slots:
     void mounting();
 private:
     QStringList filesForRemoval;
+    QSharedPointer<QTemporaryDir> m_currentDir;
+    QString m_previousCurrent;
 };
 
 class ReferenceFileEngine
@@ -563,6 +566,14 @@ class FileEngineHandler
     }
 };
 
+void tst_QAbstractFileEngine::initTestCase()
+{
+    m_previousCurrent = QDir::currentPath();
+    m_currentDir = QSharedPointer<QTemporaryDir>(new QTemporaryDir());
+    QVERIFY2(!m_currentDir.isNull(), qPrintable("Could not create current directory."));
+    QDir::setCurrent(m_currentDir->path());
+}
+
 void tst_QAbstractFileEngine::cleanupTestCase()
 {
     bool failed = false;
@@ -576,6 +587,8 @@ void tst_QAbstractFileEngine::cleanupTestCase()
         }
 
     QVERIFY(!failed);
+
+    QDir::setCurrent(m_previousCurrent);
 }
 
 void tst_QAbstractFileEngine::customHandler()
diff --git a/tests/auto/corelib/io/qdatastream/tst_qdatastream.cpp b/tests/auto/corelib/io/qdatastream/tst_qdatastream.cpp
index d9d3f55d4ae33ec5d30e6fa0fb968370c994049d..86fd1420362378e7996345e03e8bf724df74fdcf 100644
--- a/tests/auto/corelib/io/qdatastream/tst_qdatastream.cpp
+++ b/tests/auto/corelib/io/qdatastream/tst_qdatastream.cpp
@@ -50,6 +50,7 @@ public:
     void stream_data(int noOfElements);
 
 public slots:
+    void initTestCase();
     void cleanupTestCase();
 
 private slots:
@@ -243,6 +244,10 @@ private:
     void readqint64(QDataStream *s);
     void readQIcon(QDataStream *s);
     void readQEasingCurve(QDataStream *s);
+
+private:
+    QSharedPointer<QTemporaryDir> m_tempDir;
+    QString m_previousCurrent;
 };
 
 static int NColorRoles[] = {
@@ -293,10 +298,20 @@ void tst_QDataStream::getSetCheck()
     QCOMPARE(QDataStream::ReadCorruptData, obj1.status());
 }
 
+void tst_QDataStream::initTestCase()
+{
+    m_previousCurrent = QDir::currentPath();
+    m_tempDir = QSharedPointer<QTemporaryDir>(new QTemporaryDir);
+    QVERIFY2(!m_tempDir.isNull(), qPrintable("Could not create temporary directory."));
+    QVERIFY2(QDir::setCurrent(m_tempDir->path()), qPrintable("Could not switch current directory"));
+}
+
 void tst_QDataStream::cleanupTestCase()
 {
     QFile::remove(QLatin1String("qdatastream.out"));
     QFile::remove(QLatin1String("datastream.tmp"));
+
+    QDir::setCurrent(m_previousCurrent);
 }
 
 static int dataIndex(const QString &tag)
diff --git a/tests/auto/corelib/io/qdir/qdir.pro b/tests/auto/corelib/io/qdir/qdir.pro
index 0adc7e045032804a6f621bb782f00fb256c53371..65cfd3faa932b11b62788960d5bde07bfee14165 100644
--- a/tests/auto/corelib/io/qdir/qdir.pro
+++ b/tests/auto/corelib/io/qdir/qdir.pro
@@ -5,6 +5,9 @@ SOURCES = tst_qdir.cpp
 RESOURCES += qdir.qrc
 
 TESTDATA += testdir testData searchdir resources entrylist types tst_qdir.cpp
+
+contains(CONFIG, builtin_testdata): DEFINES += BUILTIN_TESTDATA
+
 DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
 
 android:!android-no-sdk {
diff --git a/tests/auto/corelib/io/qdir/tst_qdir.cpp b/tests/auto/corelib/io/qdir/tst_qdir.cpp
index ae6fe7eaef961fabff7fd049cea5fa977fb87f51..ad496782458c8f200f83030e4fa175e037565ce9 100644
--- a/tests/auto/corelib/io/qdir/tst_qdir.cpp
+++ b/tests/auto/corelib/io/qdir/tst_qdir.cpp
@@ -56,7 +56,7 @@
 # include <sys/stat.h>
 #endif
 
-#if defined(Q_OS_VXWORKS)
+#if defined(Q_OS_VXWORKS) || defined(Q_OS_WINRT)
 #define Q_NO_SYMLINKS
 #endif
 
@@ -216,7 +216,12 @@ private slots:
     void cdBelowRoot();
 
 private:
+#ifdef BUILTIN_TESTDATA
+    QString m_dataPath;
+    QSharedPointer<QTemporaryDir> m_dataDir;
+#else
     const QString m_dataPath;
+#endif
 };
 
 Q_DECLARE_METATYPE(tst_QDir::UncHandling)
@@ -224,7 +229,7 @@ Q_DECLARE_METATYPE(tst_QDir::UncHandling)
 tst_QDir::tst_QDir()
 #if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK)
     : m_dataPath(QStandardPaths::writableLocation(QStandardPaths::CacheLocation))
-#else
+#elif !defined(BUILTIN_TESTDATA)
     : m_dataPath(QFileInfo(QFINDTESTDATA("testData")).absolutePath())
 #endif
 {
@@ -261,12 +266,23 @@ void tst_QDir::init()
 
 void tst_QDir::initTestCase()
 {
+#ifdef BUILTIN_TESTDATA
+    m_dataDir = QEXTRACTTESTDATA("/");
+    QVERIFY2(!m_dataDir.isNull(), qPrintable("Did not find testdata. Is this builtin?"));
+    m_dataPath = m_dataDir->path();
+#endif
+
     QVERIFY2(!m_dataPath.isEmpty(), "test data not found");
 }
 
 void tst_QDir::cleanupTestCase()
 {
+#ifdef BUILTIN_TESTDATA
+    // We need to reset the current directory outside of QTemporaryDir for successful deletion
+    QDir::setCurrent(QCoreApplication::applicationDirPath());
+#else
     QDir(QDir::currentPath() + "/tmpdir").removeRecursively();
+#endif
 }
 
 // Testing get/set functions
@@ -532,7 +548,7 @@ void tst_QDir::exists_data()
 
     QTest::newRow("simple dir") << (m_dataPath + "/resources") << true;
     QTest::newRow("simple dir with slash") << (m_dataPath + "/resources/") << true;
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE))
+#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE)) && !defined(Q_OS_WINRT)
     const QString uncRoot = QStringLiteral("//") + QtNetworkSettings::winServerName();
     QTest::newRow("unc 1") << uncRoot << true;
     QTest::newRow("unc 2") << uncRoot + QLatin1Char('/') << true;
@@ -544,7 +560,7 @@ void tst_QDir::exists_data()
     QTest::newRow("unc 8") << uncRoot + "/asharethatshouldnotexist" << false;
     QTest::newRow("unc 9") << "//ahostthatshouldnotexist" << false;
 #endif
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE))
+#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT))
     QTest::newRow("This drive should exist") <<  "C:/" << true;
     // find a non-existing drive and check if it does not exist
 #ifdef QT_BUILD_INTERNAL
@@ -897,7 +913,7 @@ void tst_QDir::entryListSimple_data()
     QTest::newRow("simple dir with slash") << (m_dataPath + "/resources/") << 2;
 #endif
 
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
     const QString uncRoot = QStringLiteral("//") + QtNetworkSettings::winServerName();
     QTest::newRow("unc 1") << uncRoot << 2;
     QTest::newRow("unc 2") << uncRoot + QLatin1Char('/') << 2;
@@ -980,7 +996,6 @@ void tst_QDir::canonicalPath_data()
 
     QTest::newRow("relative") << "." << m_dataPath;
     QTest::newRow("relativeSubDir") << "./testData/../testData" << m_dataPath + "/testData";
-
 #ifndef Q_OS_WIN
     QTest::newRow("absPath") << m_dataPath + "/testData/../testData" << m_dataPath + "/testData";
 #else
@@ -1179,7 +1194,7 @@ tst_QDir::cleanPath_data()
     QTest::newRow("data10") << "/:/" << "/:";
 #endif
 #endif
-#ifdef Q_OS_WIN
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
     QTest::newRow("data11") << "//foo//bar" << "//foo/bar";
 #endif
     QTest::newRow("data12") << "ab/a/" << "ab/a"; // Path item with length of 2
@@ -1191,11 +1206,13 @@ tst_QDir::cleanPath_data()
 
     QTest::newRow("data14") << "c://foo" << "c:/foo";
     // Drive letters and unc path in one string
+#ifndef Q_OS_WINRT
 #ifdef Q_OS_WIN
     QTest::newRow("data15") << "//c:/foo" << "//c:/foo";
 #else
     QTest::newRow("data15") << "//c:/foo" << "/c:/foo";
 #endif
+#endif // !Q_OS_WINRT
 
     QTest::newRow("QTBUG-23892_0") << "foo/.." << ".";
     QTest::newRow("QTBUG-23892_1") << "foo/../" << ".";
@@ -1314,7 +1331,7 @@ void tst_QDir::absoluteFilePath_data()
     QTest::newRow("2") << "/" << "passwd" << "/passwd";
     QTest::newRow("3") << "relative" << "path" << QDir::currentPath() + "/relative/path";
     QTest::newRow("4") << "" << "" << QDir::currentPath();
-#ifdef Q_OS_WIN
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
     QTest::newRow("5") << "//machine" << "share" << "//machine/share";
 #endif
 
@@ -1338,7 +1355,7 @@ void tst_QDir::absolutePath_data()
     QTest::addColumn<QString>("expectedPath");
 
     QTest::newRow("0") << "/machine/share/dir1" << "/machine/share/dir1";
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE))
+#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT))
     QTest::newRow("1") << "\\machine\\share\\dir1" << "/machine/share/dir1";
     QTest::newRow("2") << "//machine/share/dir1" << "//machine/share/dir1";
     QTest::newRow("3") << "\\\\machine\\share\\dir1" << "//machine/share/dir1";
@@ -1406,10 +1423,12 @@ void tst_QDir::relativeFilePath_data()
     QTest::newRow("27") << "C:" << "D:/" << "D:/";
     QTest::newRow("28") << "C:/" << "D:" << "D:";
     QTest::newRow("29") << "C:/" << "D:/" << "D:/";
+#ifndef Q_OS_WINRT
     QTest::newRow("30") << "C:/foo/bar" << "//anotherHost/foo/bar" << "//anotherHost/foo/bar";
     QTest::newRow("31") << "//anotherHost/foo" << "//anotherHost/foo/bar" << "bar";
     QTest::newRow("32") << "//anotherHost/foo" << "bar" << "bar";
     QTest::newRow("33") << "//anotherHost/foo" << "C:/foo/bar" << "C:/foo/bar";
+#endif // !Q_OS_WINRT
 #endif
 
     QTest::newRow("resource0") << ":/prefix" << "foo.bar" << "foo.bar";
@@ -1594,7 +1613,11 @@ void tst_QDir::homePath()
     qputenv("HOME", envHome);
 
 #elif defined(Q_OS_WIN)
-    if (strHome.length() > 3)      // root dir = "c:/"; "//" is not really valid...
+    if (strHome.length() > 3      // root dir = "c:/"; "//" is not really valid...
+#if  defined(Q_OS_WINRT)
+        && strHome.length() > QDir::rootPath().length()
+#endif
+    )
         QVERIFY(!strHome.endsWith('/'));
 #endif
 
@@ -2059,6 +2082,9 @@ void tst_QDir::drives()
     QVERIFY(list.count() >= 1); //system
     QLatin1Char systemdrive('c');
 #endif
+#if defined(Q_OS_WINRT)
+    QSKIP("WinRT has no concept of drives");
+#endif
 #if defined(Q_OS_WIN)
     QVERIFY(list.count() <= 26);
     bool foundsystem = false;
@@ -2115,7 +2141,9 @@ void tst_QDir::equalityOperator_data()
         << true;
 
     //need a path in the root directory that is unlikely to be a symbolic link.
-#if defined (Q_OS_WIN)
+#if defined (Q_OS_WINRT)
+    QString pathinroot(QDir::rootPath() + QLatin1String("assets/.."));
+#elif defined (Q_OS_WIN)
     QString pathinroot("c:/windows/..");
 #elif defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK)
     QString pathinroot("/system/..");
@@ -2246,6 +2274,10 @@ void tst_QDir::cdBelowRoot()
 #define ROOT QString("/")
 #define DIR QString("/tmp")
 #define CD_INTO "tmp"
+#elif defined (Q_OS_WINRT)
+#define ROOT QDir::rootPath()
+#define DIR QDir::rootPath()
+#define CD_INTO QDir::rootPath()
 #else
 #define ROOT QString::fromLocal8Bit(qgetenv("SystemDrive"))+"/"
 #define DIR QString::fromLocal8Bit(qgetenv("SystemRoot")).replace('\\', '/')
@@ -2260,6 +2292,9 @@ void tst_QDir::cdBelowRoot()
 #ifdef Q_OS_UNIX
     if (::getuid() == 0)
         QSKIP("Running this test as root doesn't make sense");
+#endif
+#ifdef Q_OS_WINRT
+    QSKIP("WinRT has no concept of system root");
 #endif
     QDir dir(DIR);
     QVERIFY(!dir.cd("../.."));
diff --git a/tests/auto/corelib/io/qdiriterator/qdiriterator.pro b/tests/auto/corelib/io/qdiriterator/qdiriterator.pro
index a2429bf2f0d95b6893e64280a64561c65e2412f5..51bfcb36a589247dbce9c57bc932004c44965abb 100644
--- a/tests/auto/corelib/io/qdiriterator/qdiriterator.pro
+++ b/tests/auto/corelib/io/qdiriterator/qdiriterator.pro
@@ -5,6 +5,7 @@ SOURCES = tst_qdiriterator.cpp
 RESOURCES += qdiriterator.qrc
 
 TESTDATA += entrylist
+contains(CONFIG, builtin_testdata): DEFINES += BUILTIN_TESTDATA
 
 wince*mips*|wincewm50smart-msvc200*: DEFINES += WINCE_BROKEN_ITERATE=1
 DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0
diff --git a/tests/auto/corelib/io/qdiriterator/tst_qdiriterator.cpp b/tests/auto/corelib/io/qdiriterator/tst_qdiriterator.cpp
index 6b1719ad53d57f13a193820c09f3b85afa6b3e0a..554771f4d2eb6e811fae931eadb750c3866eaf8d 100644
--- a/tests/auto/corelib/io/qdiriterator/tst_qdiriterator.cpp
+++ b/tests/auto/corelib/io/qdiriterator/tst_qdiriterator.cpp
@@ -42,7 +42,7 @@
 
 #include <QtCore/private/qfsfileengine_p.h>
 
-#if defined(Q_OS_VXWORKS)
+#if defined(Q_OS_VXWORKS) || defined(Q_OS_WINRT)
 #define Q_NO_SYMLINKS
 #endif
 
@@ -115,6 +115,10 @@ private slots:
 #ifndef Q_OS_WIN
     void hiddenDirs_hiddenFiles();
 #endif
+#ifdef BUILTIN_TESTDATA
+private:
+    QSharedPointer<QTemporaryDir> m_dataDir;
+#endif
 };
 
 void tst_QDirIterator::initTestCase()
@@ -141,6 +145,10 @@ void tst_QDirIterator::initTestCase()
     }
 
     testdata_dir += QStringLiteral("/entrylist");
+#elif defined(BUILTIN_TESTDATA)
+    m_dataDir = QEXTRACTTESTDATA("/");
+    QVERIFY2(!m_dataDir.isNull(), qPrintable("Could not extract test data"));
+    QString testdata_dir = m_dataDir->path();
 #else
 
     // chdir into testdata directory, then find testdata by relative paths.
@@ -217,6 +225,11 @@ void tst_QDirIterator::cleanupTestCase()
 
     Q_FOREACH(QString dirName, createdDirectories)
         currentDir.rmdir(dirName);
+
+#ifdef Q_OS_WINRT
+    QDir::setCurrent(QCoreApplication::applicationDirPath());
+#endif // Q_OS_WINRT
+
 }
 
 void tst_QDirIterator::iterateRelativeDirectory_data()
diff --git a/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp b/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
index 210fdb5a12aa2fd1d987652941f40b2822a0ab31..d2c43f79d6f8828909578bc6a4ddf596d21c5005 100644
--- a/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
+++ b/tests/auto/corelib/io/qfileinfo/tst_qfileinfo.cpp
@@ -66,7 +66,7 @@
 #include <private/qfileinfo_p.h>
 #include "../../../../shared/filesystem.h"
 
-#if defined(Q_OS_VXWORKS)
+#if defined(Q_OS_VXWORKS) || defined(Q_OS_WINRT)
 #define Q_NO_SYMLINKS
 #endif
 
@@ -427,12 +427,12 @@ void tst_QFileInfo::isDir_data()
 
     QTest::newRow("broken link") << "brokenlink.lnk" << false;
 
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE))
+#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT))
     QTest::newRow("drive 1") << "c:" << true;
     QTest::newRow("drive 2") << "c:/" << true;
     //QTest::newRow("drive 2") << "t:s" << false;
 #endif
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
     const QString uncRoot = QStringLiteral("//") + QtNetworkSettings::winServerName();
     QTest::newRow("unc 1") << uncRoot << true;
     QTest::newRow("unc 2") << uncRoot + QLatin1Char('/') << true;
@@ -469,7 +469,7 @@ void tst_QFileInfo::isRoot_data()
 
     QTest::newRow("simple dir") << m_resourcesDir << false;
     QTest::newRow("simple dir with slash") << (m_resourcesDir + QLatin1Char('/')) << false;
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE))
+#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT))
     QTest::newRow("drive 1") << "c:" << false;
     QTest::newRow("drive 2") << "c:/" << true;
     QTest::newRow("drive 3") << "p:/" << false;
@@ -513,7 +513,12 @@ void tst_QFileInfo::exists_data()
     QTest::newRow("data8") << (m_resourcesDir + "/*.ext1") << false;
     QTest::newRow("data9") << (m_resourcesDir + "/file?.ext1") << false;
     QTest::newRow("data10") << "." << true;
+
+    // Skip for the WinRT case, as GetFileAttributesEx removes _any_
+    // trailing whitespace and "." is a valid entry as seen in data10
+#ifndef Q_OS_WINRT
     QTest::newRow("data11") << ". " << false;
+#endif
     QTest::newRow("empty") << "" << false;
 
     QTest::newRow("simple dir") << m_resourcesDir << true;
@@ -554,7 +559,7 @@ void tst_QFileInfo::absolutePath_data()
     QTest::addColumn<QString>("filename");
 
     QString drivePrefix;
-#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE))
+#if (defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT))
     drivePrefix = QDir::currentPath().left(2);
     QString nonCurrentDrivePrefix =
         drivePrefix.left(1).compare("X", Qt::CaseInsensitive) == 0 ? QString("Y:") : QString("X:");
@@ -564,6 +569,8 @@ void tst_QFileInfo::absolutePath_data()
     QTest::newRow("<not current drive>:my.dll") << nonCurrentDrivePrefix + "my.dll"
                                                 << nonCurrentDrivePrefix + "/"
                                                 << "my.dll";
+#elif defined(Q_OS_WINRT)
+    drivePrefix = QDir::currentPath().left(2);
 #endif
     QTest::newRow("0") << "/machine/share/dir1/" << drivePrefix + "/machine/share/dir1" << "";
     QTest::newRow("1") << "/machine/share/dir1" << drivePrefix + "/machine/share" << "dir1";
@@ -571,7 +578,7 @@ void tst_QFileInfo::absolutePath_data()
     QTest::newRow("3") << "/usr/local/bin/" << drivePrefix + "/usr/local/bin" << "";
     QTest::newRow("/test") << "/test" << drivePrefix + "/" << "test";
 
-#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
     QTest::newRow("c:\\autoexec.bat") << "c:\\autoexec.bat" << "C:/"
                                       << "autoexec.bat";
     QTest::newRow("c:autoexec.bat") << QDir::currentPath().left(2) + "autoexec.bat" << QDir::currentPath()
@@ -735,7 +742,7 @@ void tst_QFileInfo::canonicalFilePath()
     }
 #endif
 
-#ifdef Q_OS_WIN
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
     typedef BOOL (WINAPI *PtrCreateSymbolicLink)(LPTSTR, LPTSTR, DWORD);
     PtrCreateSymbolicLink ptrCreateSymbolicLink =
             (PtrCreateSymbolicLink)QLibrary::resolve(QLatin1String("kernel32"), "CreateSymbolicLinkW");
@@ -831,7 +838,7 @@ void tst_QFileInfo::dir_data()
     QTest::newRow("absFilePath") << QDir::currentPath() + "/tmp.txt" << false << QDir::currentPath();
     QTest::newRow("absFilePathAbsPath") << QDir::currentPath() + "/tmp.txt" << true << QDir::currentPath();
     QTest::newRow("resource1") << ":/tst_qfileinfo/resources/file1.ext1" << true << ":/tst_qfileinfo/resources";
-#ifdef Q_OS_WIN
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
     QTest::newRow("driveWithSlash") << "C:/file1.ext1.ext2" << true << "C:/";
     QTest::newRow("driveWithoutSlash") << QDir::currentPath().left(2) + "file1.ext1.ext2" << false << QDir::currentPath().left(2);
 #endif
@@ -1022,7 +1029,7 @@ void tst_QFileInfo::size()
 
 void tst_QFileInfo::systemFiles()
 {
-#if !defined(Q_OS_WIN) || defined(Q_OS_WINCE)
+#if !defined(Q_OS_WIN) || defined(Q_OS_WINCE) || defined(Q_OS_WINRT)
     QSKIP("This is a Windows only test");
 #endif
     QFileInfo fi("c:\\pagefile.sys");
@@ -1193,6 +1200,8 @@ void tst_QFileInfo::fileTimes()
 #endif
 #if defined(Q_OS_WINCE)
     QEXPECT_FAIL("simple", "WinCE only stores date of access data, not the time", Continue);
+#elif defined(Q_OS_WINRT)
+    QEXPECT_FAIL("", "WinRT does not allow timestamp handling change in the filesystem due to sandboxing", Continue);
 #elif defined(Q_OS_QNX)
     QEXPECT_FAIL("", "QNX uses the noatime filesystem option", Continue);
 #elif defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK)
@@ -1628,7 +1637,7 @@ void tst_QFileInfo::isWritable()
     QVERIFY(QFileInfo("tempfile.txt").isWritable());
     tempfile.remove();
 
-#ifdef Q_OS_WIN
+#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
 #ifdef Q_OS_WINCE
     QFileInfo fi("\\Windows\\wince.nls");
 #else
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+windows/+winrt/test b/tests/auto/corelib/io/qfileselector/platforms/+windows/+winrt/test
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+winrt/test b/tests/auto/corelib/io/qfileselector/platforms/+winrt/test
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/auto/corelib/io/qfileselector/platforms/+winrt/test2 b/tests/auto/corelib/io/qfileselector/platforms/+winrt/test2
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tests/auto/corelib/io/qfileselector/qfileselector.qrc b/tests/auto/corelib/io/qfileselector/qfileselector.qrc
index 6e2699774d3ddb840dea1678ff621346b740d607..37bd397c9da42290c3fee420790aa16d3aca91a8 100644
--- a/tests/auto/corelib/io/qfileselector/qfileselector.qrc
+++ b/tests/auto/corelib/io/qfileselector/qfileselector.qrc
@@ -24,6 +24,7 @@
    <file>platforms/+unix/test</file>
    <file>platforms/+windows/+wince/test</file>
    <file>platforms/+windows/+winnt/test</file>
+   <file>platforms/+windows/+winrt/test</file>
    <file>platforms/+windows/test</file>
    <file>platforms/+android/test</file>
    <file>platforms/+blackberry/test</file>
@@ -34,6 +35,7 @@
    <file>platforms/+haiku/test</file>
    <file>platforms/+linux/test</file>
    <file>platforms/+wince/test</file>
+   <file>platforms/+winrt/test</file>
 
    <!-- platforms/test2: shallow selection for the deepest selector -->
    <file>platforms/test2</file>
@@ -45,6 +47,7 @@
    <file>platforms/+linux/test2</file>
    <file>platforms/+wince/test2</file>
    <file>platforms/+winnt/test2</file>
+   <file>platforms/+winrt/test2</file>
 
    <!-- platforms/test3: selection for the family only -->
    <file>platforms/test3</file>
diff --git a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
index 87381f4c4eb132d0d1fe26f9471f703f458e00de..112aca224c5882bcf2bbd7d698c821286dbcc4aa 100644
--- a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
+++ b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp
@@ -99,7 +99,7 @@ void tst_QFileSelector::basicTest_data()
     expectedPlatform2File = QString(":/platforms/test2");
 #else
     QString distributionName;
-#  if (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) || defined(Q_OS_FREEBSD)
+#  if (defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)) || defined(Q_OS_FREEBSD) || defined(Q_OS_WINRT)
     distributionName = QSysInfo::productType();
 #  endif
     foreach (const QString &selector, QFileSelectorPrivate::platformSelectors()) {
diff --git a/tests/auto/corelib/io/qiodevice/tst_qiodevice.cpp b/tests/auto/corelib/io/qiodevice/tst_qiodevice.cpp
index 334f5aba05ad631bf679610aa870b94b7a7715a7..0fdddd11808227e723dfb1724f7ed75b19668f59 100644
--- a/tests/auto/corelib/io/qiodevice/tst_qiodevice.cpp
+++ b/tests/auto/corelib/io/qiodevice/tst_qiodevice.cpp
@@ -43,6 +43,7 @@ class tst_QIODevice : public QObject
 
 private slots:
     void initTestCase();
+    void cleanupTestCase();
     void getSetCheck();
     void constructing_QTcpSocket();
     void constructing_QFile();
@@ -60,6 +61,10 @@ private slots:
     void peekBug();
     void readAllKeepPosition();
     void writeInTextMode();
+
+private:
+    QSharedPointer<QTemporaryDir> m_tempDir;
+    QString m_previousCurrent;
 };
 
 void tst_QIODevice::initTestCase()
@@ -68,6 +73,15 @@ void tst_QIODevice::initTestCase()
     QVERIFY(QFileInfo(QStringLiteral("./tst_qiodevice.cpp")).exists()
             || QFile::copy(QStringLiteral(":/tst_qiodevice.cpp"), QStringLiteral("./tst_qiodevice.cpp")));
 #endif
+    m_previousCurrent = QDir::currentPath();
+    m_tempDir = QSharedPointer<QTemporaryDir>(new QTemporaryDir);
+    QVERIFY2(!m_tempDir.isNull(), qPrintable("Could not create temporary directory."));
+    QVERIFY2(QDir::setCurrent(m_tempDir->path()), qPrintable("Could not switch current directory"));
+}
+
+void tst_QIODevice::cleanupTestCase()
+{
+    QDir::setCurrent(m_previousCurrent);
 }
 
 // Testing get/set functions
@@ -75,16 +89,15 @@ void tst_QIODevice::getSetCheck()
 {
     // OpenMode QIODevice::openMode()
     // void QIODevice::setOpenMode(OpenMode)
-    class MyIODevice : public QIODevice {
+    class MyIODevice : public QTcpSocket {
     public:
-        void setOpenMode(OpenMode openMode) { QIODevice::setOpenMode(openMode); }
+        using QTcpSocket::setOpenMode;
     };
-    QTcpSocket var1;
-    MyIODevice *obj1 = reinterpret_cast<MyIODevice*>(&var1);
-    obj1->setOpenMode(QIODevice::OpenMode(QIODevice::NotOpen));
-    QCOMPARE(QIODevice::OpenMode(QIODevice::NotOpen), obj1->openMode());
-    obj1->setOpenMode(QIODevice::OpenMode(QIODevice::ReadWrite));
-    QCOMPARE(QIODevice::OpenMode(QIODevice::ReadWrite), obj1->openMode());
+    MyIODevice var1;
+    var1.setOpenMode(QIODevice::OpenMode(QIODevice::NotOpen));
+    QCOMPARE(QIODevice::OpenMode(QIODevice::NotOpen), var1.openMode());
+    var1.setOpenMode(QIODevice::OpenMode(QIODevice::ReadWrite));
+    QCOMPARE(QIODevice::OpenMode(QIODevice::ReadWrite), var1.openMode());
 }
 
 //----------------------------------------------------------------------------------
diff --git a/tests/auto/corelib/io/qloggingregistry/qloggingregistry.pro b/tests/auto/corelib/io/qloggingregistry/qloggingregistry.pro
index 6be5fb10674e3acfb122f038a53c478227d92fac..a311173c0e7eddb2a12f9824444b166b013074bd 100644
--- a/tests/auto/corelib/io/qloggingregistry/qloggingregistry.pro
+++ b/tests/auto/corelib/io/qloggingregistry/qloggingregistry.pro
@@ -6,6 +6,7 @@ QT = core core-private testlib
 
 SOURCES += tst_qloggingregistry.cpp
 OTHER_FILES += qtlogging.ini
+TESTDATA += qtlogging.ini
 
 android:!android-no-sdk: {
     RESOURCES += \
diff --git a/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp b/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp
index 50c5b938e9d61cc6437f50f4c1b05cbed2ea924f..e1c277717ddde095e60240099b15e7aa7a803341 100644
--- a/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp
+++ b/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp
@@ -429,6 +429,8 @@ void tst_qstandardpaths::testFindExecutable()
 
 void tst_qstandardpaths::testFindExecutableLinkToDirectory()
 {
+    // WinRT has no link support
+#ifndef Q_OS_WINRT
     // link to directory
     const QString target = QDir::tempPath() + QDir::separator() + QLatin1String("link.lnk");
     QFile::remove(target);
@@ -436,15 +438,16 @@ void tst_qstandardpaths::testFindExecutableLinkToDirectory()
     QVERIFY(appFile.link(target));
     QVERIFY(QStandardPaths::findExecutable(target).isEmpty());
     QFile::remove(target);
+#endif
 }
 
 void tst_qstandardpaths::testRuntimeDirectory()
 {
+#ifdef Q_XDG_PLATFORM
     const QString runtimeDir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
     QVERIFY(!runtimeDir.isEmpty());
 
     // Check that it can automatically fix permissions
-#ifdef Q_XDG_PLATFORM
     QFile file(runtimeDir);
     const QFile::Permissions wantedPerms = QFile::ReadUser | QFile::WriteUser | QFile::ExeUser;
     const QFile::Permissions additionalPerms = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner;
diff --git a/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp b/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
index 621e215d60ab998333130d4db58d8f7d3192a7fb..6e03d8360e8c5f3b63dc5952a16620ff3a2fb837 100644
--- a/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
+++ b/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp
@@ -72,11 +72,14 @@ private slots:
 
     void QTBUG43352_failedSetPermissions();
 
-public:
+private:
+    QString m_previousCurrent;
 };
 
 void tst_QTemporaryDir::initTestCase()
 {
+    m_previousCurrent = QDir::currentPath();
+    QDir::setCurrent(QDir::tempPath());
     QVERIFY(QDir("test-XXXXXX").exists() || QDir().mkdir("test-XXXXXX"));
     QCoreApplication::setApplicationName("tst_qtemporarydir");
 }
@@ -84,6 +87,8 @@ void tst_QTemporaryDir::initTestCase()
 void tst_QTemporaryDir::cleanupTestCase()
 {
     QVERIFY(QDir().rmdir("test-XXXXXX"));
+
+    QDir::setCurrent(m_previousCurrent);
 }
 
 void tst_QTemporaryDir::construction()
diff --git a/tests/auto/corelib/io/qtemporaryfile/tst_qtemporaryfile.cpp b/tests/auto/corelib/io/qtemporaryfile/tst_qtemporaryfile.cpp
index 94e6bbaade2014bd0925399e9931731ca0fd068a..6e461cae17e1d5148cef1cf29a5b6756bedaea39 100644
--- a/tests/auto/corelib/io/qtemporaryfile/tst_qtemporaryfile.cpp
+++ b/tests/auto/corelib/io/qtemporaryfile/tst_qtemporaryfile.cpp
@@ -85,10 +85,15 @@ private slots:
     void QTBUG_4796_data();
     void QTBUG_4796();
     void guaranteeUnique();
+private:
+    QString m_previousCurrent;
 };
 
 void tst_QTemporaryFile::initTestCase()
 {
+    m_previousCurrent = QDir::currentPath();
+    QDir::setCurrent(QDir::tempPath());
+
     // For QTBUG_4796
     QVERIFY(QDir("test-XXXXXX").exists() || QDir().mkdir("test-XXXXXX"));
     QCoreApplication::setApplicationName("tst_qtemporaryfile");
@@ -116,6 +121,8 @@ void tst_QTemporaryFile::cleanupTestCase()
 {
     // From QTBUG_4796
     QVERIFY(QDir().rmdir("test-XXXXXX"));
+
+    QDir::setCurrent(m_previousCurrent);
 }
 
 void tst_QTemporaryFile::construction()
@@ -678,8 +685,11 @@ void tst_QTemporaryFile::createNativeFile_data()
     const QString nativeFilePath = QFINDTESTDATA("resources/test.txt");
 #endif
 
-    QTest::newRow("nativeFile") << nativeFilePath << (qint64)-1 << false << QByteArray();
-    QTest::newRow("nativeFileWithPos") << nativeFilePath << (qint64)5 << false << QByteArray();
+    // File might not exist locally in case of sandboxing or remote testing
+    if (!nativeFilePath.startsWith(QLatin1String(":/"))) {
+        QTest::newRow("nativeFile") << nativeFilePath << (qint64)-1 << false << QByteArray();
+        QTest::newRow("nativeFileWithPos") << nativeFilePath << (qint64)5 << false << QByteArray();
+    }
     QTest::newRow("resourceFile") << ":/resources/test.txt" << (qint64)-1 << true << QByteArray("This is a test");
     QTest::newRow("resourceFileWithPos") << ":/resources/test.txt" << (qint64)5 << true << QByteArray("This is a test");
 }
diff --git a/tests/auto/corelib/io/qurl/tst_qurl.cpp b/tests/auto/corelib/io/qurl/tst_qurl.cpp
index 031a35b3806a4bd4a1da48774cd5c47bc08ddc84..b284e5fc9c6d72bd6db06318c712b348bd5506ed 100644
--- a/tests/auto/corelib/io/qurl/tst_qurl.cpp
+++ b/tests/auto/corelib/io/qurl/tst_qurl.cpp
@@ -69,6 +69,8 @@ private slots:
     void resolving();
     void toString_data();
     void toString();
+    void toString_PreferLocalFile_data();
+    void toString_PreferLocalFile();
     void toString_constructed_data();
     void toString_constructed();
     void toAndFromStringList_data();
@@ -1050,6 +1052,29 @@ void tst_QUrl::toString()
 
     QCOMPARE(url.adjusted(opt).toString(), string);
 }
+void tst_QUrl::toString_PreferLocalFile_data()
+{
+    QTest::addColumn<QUrl>("url");
+    QTest::addColumn<QString>("string");
+
+#ifdef Q_OS_WIN
+    QTest::newRow("win-drive") << QUrl(QString::fromLatin1("file:///c:/windows/regedit.exe"))
+                               << QString::fromLatin1("c:/windows/regedit.exe");
+    QTest::newRow("win-share") << QUrl(QString::fromLatin1("//Anarki/homes"))
+                               << QString::fromLatin1("//anarki/homes");
+#else
+    QTest::newRow("unix-path") << QUrl(QString::fromLatin1("file:///tmp"))
+                               << QString::fromLatin1("/tmp");
+#endif
+}
+
+void tst_QUrl::toString_PreferLocalFile()
+{
+    QFETCH(QUrl, url);
+    QFETCH(QString, string);
+
+    QCOMPARE(url.toString(QUrl::PreferLocalFile), string);
+}
 
 void tst_QUrl::toAndFromStringList_data()
 {
@@ -2988,14 +3013,20 @@ void tst_QUrl::fromUserInputWithCwd_data()
         it.next();
         QUrl url = QUrl::fromLocalFile(it.filePath());
         if (it.fileName() == QLatin1String(".")) {
-            url = QUrl::fromLocalFile(QDir::currentPath()); // fromUserInput cleans the path
+            url = QUrl::fromLocalFile(QDir::currentPath()
+#ifdef Q_OS_WINRT
+                                      + QLatin1Char('/')
+#endif
+                                      ); // fromUserInput cleans the path
         }
         QTest::newRow(QString("file-%1").arg(c++).toLatin1()) << it.fileName() << QDir::currentPath() << url << url;
     }
+#ifndef Q_OS_WINRT // WinRT cannot cd outside current / sandbox
     QDir parent = QDir::current();
     QVERIFY(parent.cdUp());
     QUrl parentUrl = QUrl::fromLocalFile(parent.path());
     QTest::newRow("dotdot") << ".." << QDir::currentPath() << parentUrl << parentUrl;
+#endif
 
     QTest::newRow("nonexisting") << "nonexisting" << QDir::currentPath() << QUrl("http://nonexisting") << QUrl::fromLocalFile(QDir::currentPath() + "/nonexisting");
     QTest::newRow("short-url") << "example.org" << QDir::currentPath() << QUrl("http://example.org") << QUrl::fromLocalFile(QDir::currentPath() + "/example.org");
diff --git a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
index 10ffa062457555a65942dc6ddd729d06c1be8fde..c74a43b6829bc729b3e6f62c1b8dd093654421e6 100644
--- a/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
+++ b/tests/auto/corelib/kernel/qmetatype/tst_qmetatype.cpp
@@ -369,40 +369,40 @@ void tst_QMetaType::normalizedTypes()
 }
 
 #define TYPENAME_DATA(MetaTypeName, MetaTypeId, RealType)\
-    QTest::newRow(#RealType) << QMetaType::MetaTypeName << #RealType;
+    QTest::newRow(#RealType) << int(QMetaType::MetaTypeName) << #RealType;
 
 void tst_QMetaType::typeName_data()
 {
-    QTest::addColumn<QMetaType::Type>("aType");
+    QTest::addColumn<int>("aType");
     QTest::addColumn<QString>("aTypeName");
 
     QT_FOR_EACH_STATIC_TYPE(TYPENAME_DATA)
-    QTest::newRow("QMetaType::UnknownType") << QMetaType::UnknownType << static_cast<const char*>(0);
+    QTest::newRow("QMetaType::UnknownType") << int(QMetaType::UnknownType) << static_cast<const char*>(0);
 
-    QTest::newRow("Whity<double>") << static_cast<QMetaType::Type>(::qMetaTypeId<Whity<double> >()) << QString::fromLatin1("Whity<double>");
-    QTest::newRow("Whity<int>") << static_cast<QMetaType::Type>(::qMetaTypeId<Whity<int> >()) << QString::fromLatin1("Whity<int>");
-    QTest::newRow("Testspace::Foo") << static_cast<QMetaType::Type>(::qMetaTypeId<TestSpace::Foo>()) << QString::fromLatin1("TestSpace::Foo");
+    QTest::newRow("Whity<double>") << ::qMetaTypeId<Whity<double> >() << QString::fromLatin1("Whity<double>");
+    QTest::newRow("Whity<int>") << ::qMetaTypeId<Whity<int> >() << QString::fromLatin1("Whity<int>");
+    QTest::newRow("Testspace::Foo") << ::qMetaTypeId<TestSpace::Foo>() << QString::fromLatin1("TestSpace::Foo");
 
-    QTest::newRow("-1") << QMetaType::Type(-1) << QString();
-    QTest::newRow("-124125534") << QMetaType::Type(-124125534) << QString();
-    QTest::newRow("124125534") << QMetaType::Type(124125534) << QString();
+    QTest::newRow("-1") << -1 << QString();
+    QTest::newRow("-124125534") << -124125534 << QString();
+    QTest::newRow("124125534") << 124125534 << QString();
 
     // automatic registration
-    QTest::newRow("QList<int>") << static_cast<QMetaType::Type>(::qMetaTypeId<QList<int> >()) << QString::fromLatin1("QList<int>");
-    QTest::newRow("QHash<int,int>") << static_cast<QMetaType::Type>(::qMetaTypeId<QHash<int, int> >()) << QString::fromLatin1("QHash<int,int>");
-    QTest::newRow("QMap<int,int>") << static_cast<QMetaType::Type>(::qMetaTypeId<QMap<int, int> >()) << QString::fromLatin1("QMap<int,int>");
-    QTest::newRow("QVector<QList<int>>") << static_cast<QMetaType::Type>(::qMetaTypeId<QVector<QList<int> > >()) << QString::fromLatin1("QVector<QList<int> >");
-    QTest::newRow("QVector<QMap<int,int>>") << static_cast<QMetaType::Type>(::qMetaTypeId<QVector<QMap<int, int> > >()) << QString::fromLatin1("QVector<QMap<int,int> >");
+    QTest::newRow("QList<int>") << ::qMetaTypeId<QList<int> >() << QString::fromLatin1("QList<int>");
+    QTest::newRow("QHash<int,int>") << ::qMetaTypeId<QHash<int, int> >() << QString::fromLatin1("QHash<int,int>");
+    QTest::newRow("QMap<int,int>") << ::qMetaTypeId<QMap<int, int> >() << QString::fromLatin1("QMap<int,int>");
+    QTest::newRow("QVector<QList<int>>") << ::qMetaTypeId<QVector<QList<int> > >() << QString::fromLatin1("QVector<QList<int> >");
+    QTest::newRow("QVector<QMap<int,int>>") << ::qMetaTypeId<QVector<QMap<int, int> > >() << QString::fromLatin1("QVector<QMap<int,int> >");
 
-    QTest::newRow("CustomQObject*") << static_cast<QMetaType::Type>(::qMetaTypeId<CustomQObject*>()) << QString::fromLatin1("CustomQObject*");
-    QTest::newRow("CustomGadget") << static_cast<QMetaType::Type>(::qMetaTypeId<CustomGadget>()) << QString::fromLatin1("CustomGadget");
-    QTest::newRow("CustomQObject::CustomQEnum") << static_cast<QMetaType::Type>(::qMetaTypeId<CustomQObject::CustomQEnum>()) << QString::fromLatin1("CustomQObject::CustomQEnum");
-    QTest::newRow("Qt::ArrowType") << static_cast<QMetaType::Type>(::qMetaTypeId<Qt::ArrowType>()) << QString::fromLatin1("Qt::ArrowType");
+    QTest::newRow("CustomQObject*") << ::qMetaTypeId<CustomQObject*>() << QString::fromLatin1("CustomQObject*");
+    QTest::newRow("CustomGadget") << ::qMetaTypeId<CustomGadget>() << QString::fromLatin1("CustomGadget");
+    QTest::newRow("CustomQObject::CustomQEnum") << ::qMetaTypeId<CustomQObject::CustomQEnum>() << QString::fromLatin1("CustomQObject::CustomQEnum");
+    QTest::newRow("Qt::ArrowType") << ::qMetaTypeId<Qt::ArrowType>() << QString::fromLatin1("Qt::ArrowType");
 }
 
 void tst_QMetaType::typeName()
 {
-    QFETCH(QMetaType::Type, aType);
+    QFETCH(int, aType);
     QFETCH(QString, aTypeName);
 
     QString name = QString::fromLatin1(QMetaType::typeName(aType));
@@ -413,15 +413,15 @@ void tst_QMetaType::typeName()
 
 void tst_QMetaType::type_data()
 {
-    QTest::addColumn<QMetaType::Type>("aType");
+    QTest::addColumn<int>("aType");
     QTest::addColumn<QByteArray>("aTypeName");
 
 #define TST_QMETATYPE_TYPE_DATA(MetaTypeName, MetaTypeId, RealType)\
-    QTest::newRow(#RealType) << QMetaType::MetaTypeName << QByteArray( #RealType );
+    QTest::newRow(#RealType) << int(QMetaType::MetaTypeName) << QByteArray( #RealType );
 #define TST_QMETATYPE_TYPE_DATA_ALIAS(MetaTypeName, MetaTypeId, AliasType, RealTypeString)\
-    QTest::newRow(RealTypeString) << QMetaType::MetaTypeName << QByteArray( #AliasType );
+    QTest::newRow(RealTypeString) << int(QMetaType::MetaTypeName) << QByteArray( #AliasType );
 
-    QTest::newRow("empty") << QMetaType::UnknownType << QByteArray();
+    QTest::newRow("empty") << int(QMetaType::UnknownType) << QByteArray();
 
     QT_FOR_EACH_STATIC_TYPE(TST_QMETATYPE_TYPE_DATA)
     QT_FOR_EACH_STATIC_ALIAS_TYPE(TST_QMETATYPE_TYPE_DATA_ALIAS)
@@ -432,13 +432,13 @@ void tst_QMetaType::type_data()
 
 void tst_QMetaType::type()
 {
-    QFETCH(QMetaType::Type, aType);
+    QFETCH(int, aType);
     QFETCH(QByteArray, aTypeName);
 
     // QMetaType::type(QByteArray)
-    QCOMPARE(QMetaType::type(aTypeName), int(aType));
+    QCOMPARE(QMetaType::type(aTypeName), aType);
     // QMetaType::type(const char *)
-    QCOMPARE(QMetaType::type(aTypeName.constData()), int(aType));
+    QCOMPARE(QMetaType::type(aTypeName.constData()), aType);
 }
 
 void tst_QMetaType::type_fromSubString_data()
@@ -727,9 +727,9 @@ template<> struct TestValueFactory<QMetaType::QVariant> {
 
 void tst_QMetaType::create_data()
 {
-    QTest::addColumn<QMetaType::Type>("type");
+    QTest::addColumn<int>("type");
 #define ADD_METATYPE_TEST_ROW(MetaTypeName, MetaTypeId, RealType) \
-    QTest::newRow(QMetaType::typeName(QMetaType::MetaTypeName)) << QMetaType::MetaTypeName;
+    QTest::newRow(QMetaType::typeName(QMetaType::MetaTypeName)) << int(QMetaType::MetaTypeName);
 FOR_EACH_CORE_METATYPE(ADD_METATYPE_TEST_ROW)
 #undef ADD_METATYPE_TEST_ROW
 }
@@ -781,7 +781,7 @@ FOR_EACH_CORE_METATYPE(RETURN_CREATE_FUNCTION)
         }
     };
 
-    QFETCH(QMetaType::Type, type);
+    QFETCH(int, type);
     TypeTestFunctionGetter::get(type)();
 }
 
@@ -832,33 +832,33 @@ FOR_EACH_CORE_METATYPE(RETURN_CREATE_COPY_FUNCTION)
         }
     };
 
-    QFETCH(QMetaType::Type, type);
+    QFETCH(int, type);
     TypeTestFunctionGetter::get(type)();
 }
 
 void tst_QMetaType::sizeOf_data()
 {
-    QTest::addColumn<QMetaType::Type>("type");
+    QTest::addColumn<int>("type");
     QTest::addColumn<size_t>("size");
 
-    QTest::newRow("QMetaType::UnknownType") << QMetaType::UnknownType << size_t(0);
+    QTest::newRow("QMetaType::UnknownType") << int(QMetaType::UnknownType) << size_t(0);
 #define ADD_METATYPE_TEST_ROW(MetaTypeName, MetaTypeId, RealType) \
-    QTest::newRow(#RealType) << QMetaType::MetaTypeName << size_t(QTypeInfo<RealType>::sizeOf);
+    QTest::newRow(#RealType) << int(QMetaType::MetaTypeName) << size_t(QTypeInfo<RealType>::sizeOf);
 FOR_EACH_CORE_METATYPE(ADD_METATYPE_TEST_ROW)
 #undef ADD_METATYPE_TEST_ROW
 
-    QTest::newRow("Whity<double>") << static_cast<QMetaType::Type>(::qMetaTypeId<Whity<double> >()) << sizeof(Whity<double>);
-QTest::newRow("Whity<int>") << static_cast<QMetaType::Type>(::qMetaTypeId<Whity<int> >()) << sizeof(Whity<int>);
-    QTest::newRow("Testspace::Foo") << static_cast<QMetaType::Type>(::qMetaTypeId<TestSpace::Foo>()) << sizeof(TestSpace::Foo);
+    QTest::newRow("Whity<double>") << ::qMetaTypeId<Whity<double> >() << sizeof(Whity<double>);
+    QTest::newRow("Whity<int>") << ::qMetaTypeId<Whity<int> >() << sizeof(Whity<int>);
+    QTest::newRow("Testspace::Foo") << ::qMetaTypeId<TestSpace::Foo>() << sizeof(TestSpace::Foo);
 
-    QTest::newRow("-1") << QMetaType::Type(-1) << size_t(0);
-    QTest::newRow("-124125534") << QMetaType::Type(-124125534) << size_t(0);
-    QTest::newRow("124125534") << QMetaType::Type(124125534) << size_t(0);
+    QTest::newRow("-1") << -1 << size_t(0);
+    QTest::newRow("-124125534") << -124125534 << size_t(0);
+    QTest::newRow("124125534") << 124125534 << size_t(0);
 }
 
 void tst_QMetaType::sizeOf()
 {
-    QFETCH(QMetaType::Type, type);
+    QFETCH(int, type);
     QFETCH(size_t, size);
     QCOMPARE(size_t(QMetaType::sizeOf(type)), size);
 }
@@ -870,7 +870,7 @@ void tst_QMetaType::sizeOfStaticLess_data()
 
 void tst_QMetaType::sizeOfStaticLess()
 {
-    QFETCH(QMetaType::Type, type);
+    QFETCH(int, type);
     QFETCH(size_t, size);
     QCOMPARE(size_t(QMetaType(type).sizeOf()), size);
 }
@@ -1126,7 +1126,7 @@ FOR_EACH_CORE_METATYPE(RETURN_CONSTRUCT_FUNCTION)
         }
     };
 
-    QFETCH(QMetaType::Type, type);
+    QFETCH(int, type);
     TypeTestFunctionGetter::get(type)();
 }
 
@@ -1194,7 +1194,7 @@ FOR_EACH_CORE_METATYPE(RETURN_CONSTRUCT_COPY_FUNCTION)
         }
     };
 
-    QFETCH(QMetaType::Type, type);
+    QFETCH(int, type);
     TypeTestFunctionGetter::get(type)();
 }
 
diff --git a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
index a3c6d8e9dfdec9db1b00f00128642b9d3c89ebc8..f7c1f03c0fa7a2ed8baa449349a067525d66a603 100644
--- a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
+++ b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp
@@ -5987,7 +5987,7 @@ class GetSenderObject : public QObject
 {
     Q_OBJECT
 public:
-    QObject *accessSender() { return sender(); }
+    using QObject::sender; // make public
 
 public Q_SLOTS:
     void triggerSignal() { Q_EMIT aSignal(); }
@@ -6003,8 +6003,8 @@ struct CountedStruct
     CountedStruct(GetSenderObject *sender) : sender(sender) { ++countedStructObjectsCount; }
     CountedStruct(const CountedStruct &o) : sender(o.sender) { ++countedStructObjectsCount; }
     CountedStruct &operator=(const CountedStruct &) { return *this; }
-    // accessSender here allows us to check if there's a deadlock
-    ~CountedStruct() { --countedStructObjectsCount; if (sender != Q_NULLPTR) (void)sender->accessSender(); }
+    // calling sender() here allows us to check if there's a deadlock
+    ~CountedStruct() { --countedStructObjectsCount; if (sender) (void)sender->sender(); }
     void operator()() const { }
 
     GetSenderObject *sender;
@@ -6396,7 +6396,8 @@ void tst_QObject::noDeclarativeParentChangedOnDestruction()
     QObject *parent = new QObject;
     QObject *child = new QObject;
 
-    QAbstractDeclarativeData dummy;
+    QAbstractDeclarativeDataImpl dummy;
+    dummy.ownedByQml1 = false;
     QObjectPrivate::get(child)->declarativeData = &dummy;
 
     parentChangeCalled = false;
diff --git a/tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp b/tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp
index cfbb88a123d1ad1f188802774c13e138c9de4bf8..8c76809c481ccd5c29b6a277a158c79ff990bf05 100644
--- a/tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp
+++ b/tests/auto/corelib/statemachine/qstatemachine/tst_qstatemachine.cpp
@@ -252,6 +252,7 @@ private slots:
     void conflictingTransition2();
     void qtbug_46059();
     void qtbug_46703();
+    void postEventFromBeginSelectTransitions();
 };
 
 class TestState : public QState
@@ -6606,5 +6607,33 @@ void tst_QStateMachine::qtbug_46703()
     QVERIFY(machine.isRunning());
 }
 
+void tst_QStateMachine::postEventFromBeginSelectTransitions()
+{
+    class StateMachine : public QStateMachine {
+    protected:
+        void beginSelectTransitions(QEvent* e) Q_DECL_OVERRIDE {
+            if (e->type() == QEvent::Type(QEvent::User + 2))
+                postEvent(new QEvent(QEvent::Type(QEvent::User + 1)), QStateMachine::HighPriority);
+        }
+    } machine;
+    QState a(&machine);
+    QState success(&machine);
+
+    machine.setInitialState(&a);
+    a.addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), &success));
+
+    machine.start();
+
+    QTRY_COMPARE(machine.configuration().contains(&a), true);
+    QTRY_COMPARE(machine.configuration().contains(&success), false);
+
+    machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 2)), QStateMachine::NormalPriority);
+
+    QTRY_COMPARE(machine.configuration().contains(&a), false);
+    QTRY_COMPARE(machine.configuration().contains(&success), true);
+
+    QVERIFY(machine.isRunning());
+}
+
 QTEST_MAIN(tst_QStateMachine)
 #include "tst_qstatemachine.moc"
diff --git a/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp b/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp
index 228ce73c6be131107f486745c337e3e1572320cd..1078aef6ad874c86756336ac82bdb8d7d5f296fe 100644
--- a/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp
+++ b/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp
@@ -155,7 +155,7 @@ private slots:
 
 private:
     enum { LocalTimeIsUtc = 0, LocalTimeAheadOfUtc = 1, LocalTimeBehindUtc = -1} localTimeType;
-    bool europeanTimeZone;
+    bool zoneIsCET;
     QDate defDate() const { return QDate(1900, 1, 1); }
     QTime defTime() const { return QTime(0, 0, 0); }
     QDateTime defDateTime() const { return QDateTime(defDate(), defTime()); }
@@ -171,21 +171,70 @@ Q_DECLARE_METATYPE(Qt::DateFormat)
 
 tst_QDateTime::tst_QDateTime()
 {
-    uint x1 = QDateTime(QDate(1990, 1, 1), QTime()).toTime_t();
-    uint x2 = QDateTime(QDate(1990, 6, 1), QTime()).toTime_t();
-    europeanTimeZone = (x1 == 631148400 && x2 == 644191200);
-
-    QDateTime dt1 = QDateTime::fromTime_t(0);
-    QDateTime dt2 = QDateTime::fromTime_t(181 * 86400); // six months later, Jul 1
-    if (dt1.date().year() < 1970 || dt2.date().month() < 7) {
-        localTimeType = LocalTimeBehindUtc;
-    } else if (dt1.time().hour() > 0 || dt1.date().day() > 1) {
-        localTimeType = LocalTimeAheadOfUtc;
-    } else if (dt2.time().hour() > 0 || dt2.date().day() > 1) {
-        localTimeType = LocalTimeAheadOfUtc;
-    } else {
-        localTimeType = LocalTimeIsUtc;
+    /*
+      Due to some jurisdictions changing their zones and rules, it's possible
+      for a non-CET zone to accidentally match CET at a few tested moments but
+      be different a few years later or earlier.  This would lead to tests
+      failing if run in the partially-aliasing zone (e.g. Algeria, Lybia).  So
+      test thoroughly; ideally at every mid-winter or mid-summer in whose
+      half-year any test below assumes zoneIsCET means what it says.  (Tests at
+      or near a DST transition implicate both of the half-years that meet
+      there.)  Years outside the 1970--2038 range, however, are likely not
+      properly handled by the TZ-database; and QDateTime explicitly handles them
+      differently, so don't probe them here.
+    */
+    const uint day = 24 * 3600; // in seconds
+    zoneIsCET = (QDateTime(QDate(2038, 1, 19), QTime(4, 14, 7)).toTime_t() == 0x7fffffff
+                 // Entries a year apart robustly differ by multiples of day.
+                 && QDateTime(QDate(2015, 7, 1), QTime()).toTime_t() == 1435701600
+                 && QDateTime(QDate(2015, 1, 1), QTime()).toTime_t() == 1420066800
+                 && QDateTime(QDate(2013, 7, 1), QTime()).toTime_t() == 1372629600
+                 && QDateTime(QDate(2013, 1, 1), QTime()).toTime_t() == 1356994800
+                 && QDateTime(QDate(2012, 7, 1), QTime()).toTime_t() == 1341093600
+                 && QDateTime(QDate(2012, 1, 1), QTime()).toTime_t() == 1325372400
+                 && QDateTime(QDate(2008, 7, 1), QTime()).toTime_t() == 1214863200
+                 && QDateTime(QDate(2004, 1, 1), QTime()).toTime_t() == 1072911600
+                 && QDateTime(QDate(2000, 1, 1), QTime()).toTime_t() == 946681200
+                 && QDateTime(QDate(1990, 7, 1), QTime()).toTime_t() == 646783200
+                 && QDateTime(QDate(1990, 1, 1), QTime()).toTime_t() == 631148400
+                 && QDateTime(QDate(1979, 1, 1), QTime()).toTime_t() == 283993200
+                 // .toTime_t() returns -1 for everything before this:
+                 && QDateTime(QDate(1970, 1, 1), QTime(1, 0, 0)).toTime_t() == 0);
+    // Use .toMSecsSinceEpoch() if you really need to test anything earlier.
+
+    /*
+      Again, rule changes can cause a TZ to look like UTC at some sample dates
+      but deviate at some date relevant to a test using localTimeType.  These
+      tests mostly use years outside the 1970--2038 range for which TZ data is
+      credible, so we can't helpfully be exhaustive.  So scan a sample of years'
+      starts and middles.
+    */
+    const int sampled = 3;
+    // UTC starts of months in 2004, 2038 and 1970:
+    uint jans[sampled] = { 12418 * day, 24837 * day, 0 };
+    uint juls[sampled] = { 12600 * day, 25018 * day, 181 * day };
+    localTimeType = LocalTimeIsUtc;
+    for (int i = sampled; i-- > 0; ) {
+        QDateTime jan = QDateTime::fromTime_t(jans[i]);
+        QDateTime jul = QDateTime::fromTime_t(juls[i]);
+        if (jan.date().year() < 1970 || jul.date().month() < 7) {
+            localTimeType = LocalTimeBehindUtc;
+            break;
+        } else if (jan.time().hour() > 0 || jul.time().hour() > 0
+                   || jan.date().day() > 1 || jul.date().day() > 1) {
+            localTimeType = LocalTimeAheadOfUtc;
+            break;
+        }
     }
+    /*
+      Even so, TZ=Africa/Algiers will fail fromMSecsSinceEpoch(-1) because it
+      switched from WET without DST (i.e. UTC) in the late 1960s to WET with DST
+      for all of 1970 - so they had a DST transition *on the epoch*.  They've
+      since switched to CET with no DST, making life simple; but our tests for
+      mistakes around the epoch can't tell the difference between what Algeria
+      really did and the symptoms we can believe a bug might produce: there's
+      not much we can do about that, that wouldn't hide real bugs.
+    */
 }
 
 void tst_QDateTime::initTestCase()
@@ -201,7 +250,7 @@ void tst_QDateTime::initTestCase()
         break;
     case LocalTimeAheadOfUtc:
         typemsg1 = "ahead of";
-        typemsg2 = europeanTimeZone ? "and is" : "but isn't";
+        typemsg2 = zoneIsCET ? "and is" : "but isn't";
         break;
     }
 
@@ -245,7 +294,7 @@ void tst_QDateTime::ctor()
     QCOMPARE(dt3.timeSpec(), Qt::UTC);
 
     QVERIFY(dt1 == dt2);
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QVERIFY(dt1 != dt3);
         QVERIFY(dt1 < dt3);
         QVERIFY(dt1.addSecs(3600).toUTC() == dt3);
@@ -492,7 +541,7 @@ void tst_QDateTime::setTime_t()
 
     dt1.setTime_t(123456);
     QCOMPARE(dt1, QDateTime(QDate(1970, 1, 2), QTime(10, 17, 36), Qt::UTC));
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QDateTime dt2;
         dt2.setTime_t(123456);
         QCOMPARE(dt2, QDateTime(QDate(1970, 1, 2), QTime(11, 17, 36), Qt::LocalTime));
@@ -500,7 +549,7 @@ void tst_QDateTime::setTime_t()
 
     dt1.setTime_t((uint)(quint32)-123456);
     QCOMPARE(dt1, QDateTime(QDate(2106, 2, 5), QTime(20, 10, 40), Qt::UTC));
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QDateTime dt2;
         dt2.setTime_t((uint)(quint32)-123456);
         QCOMPARE(dt2, QDateTime(QDate(2106, 2, 5), QTime(21, 10, 40), Qt::LocalTime));
@@ -508,7 +557,7 @@ void tst_QDateTime::setTime_t()
 
     dt1.setTime_t(1214567890);
     QCOMPARE(dt1, QDateTime(QDate(2008, 6, 27), QTime(11, 58, 10), Qt::UTC));
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QDateTime dt2;
         dt2.setTime_t(1214567890);
         QCOMPARE(dt2, QDateTime(QDate(2008, 6, 27), QTime(13, 58, 10), Qt::LocalTime));
@@ -516,7 +565,7 @@ void tst_QDateTime::setTime_t()
 
     dt1.setTime_t(0x7FFFFFFF);
     QCOMPARE(dt1, QDateTime(QDate(2038, 1, 19), QTime(3, 14, 7), Qt::UTC));
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QDateTime dt2;
         dt2.setTime_t(0x7FFFFFFF);
         QCOMPARE(dt2, QDateTime(QDate(2038, 1, 19), QTime(4, 14, 7), Qt::LocalTime));
@@ -533,7 +582,7 @@ void tst_QDateTime::setMSecsSinceEpoch_data()
 {
     QTest::addColumn<qint64>("msecs");
     QTest::addColumn<QDateTime>("utc");
-    QTest::addColumn<QDateTime>("european");
+    QTest::addColumn<QDateTime>("cet");
 
     QTest::newRow("zero")
             << Q_INT64_C(0)
@@ -584,7 +633,7 @@ void tst_QDateTime::setMSecsSinceEpoch()
 {
     QFETCH(qint64, msecs);
     QFETCH(QDateTime, utc);
-    QFETCH(QDateTime, european);
+    QFETCH(QDateTime, cet);
 
     QDateTime dt;
     dt.setTimeSpec(Qt::UTC);
@@ -595,8 +644,8 @@ void tst_QDateTime::setMSecsSinceEpoch()
     QCOMPARE(dt.time(), utc.time());
     QCOMPARE(dt.timeSpec(), Qt::UTC);
 
-    if (europeanTimeZone) {
-        QCOMPARE(dt.toLocalTime(), european);
+    if (zoneIsCET) {
+        QCOMPARE(dt.toLocalTime(), cet);
 
         // Test converting from LocalTime to UTC back to LocalTime.
         QDateTime localDt;
@@ -613,13 +662,13 @@ void tst_QDateTime::setMSecsSinceEpoch()
         QDateTime dt2;
         dt2.setTimeZone(europe);
         dt2.setMSecsSinceEpoch(msecs);
-        QCOMPARE(dt2.date(), european.date());
+        QCOMPARE(dt2.date(), cet.date());
 
         // don't compare the time if the date is too early or too late: prior
         // to 1916, timezones in Europe were not standardised and some OS APIs
         // have hard limits. Let's restrict it to the 32-bit Unix range
         if (dt2.date().year() >= 1970 && dt2.date().year() <= 2037)
-            QCOMPARE(dt2.time(), european.time());
+            QCOMPARE(dt2.time(), cet.time());
         QCOMPARE(dt2.timeSpec(), Qt::TimeZone);
         QCOMPARE(dt2.timeZone(), europe);
     }
@@ -643,7 +692,7 @@ void tst_QDateTime::fromMSecsSinceEpoch()
 {
     QFETCH(qint64, msecs);
     QFETCH(QDateTime, utc);
-    QFETCH(QDateTime, european);
+    QFETCH(QDateTime, cet);
 
     QDateTime dtLocal = QDateTime::fromMSecsSinceEpoch(msecs, Qt::LocalTime);
     QDateTime dtUtc = QDateTime::fromMSecsSinceEpoch(msecs, Qt::UTC);
@@ -665,10 +714,10 @@ void tst_QDateTime::fromMSecsSinceEpoch()
     if (msecs != std::numeric_limits<qint64>::max())
         QCOMPARE(dtOffset.time(), utc.time().addMSecs(60*60*1000));
 
-    if (europeanTimeZone) {
-        QCOMPARE(dtLocal.toLocalTime(), european);
-        QCOMPARE(dtUtc.toLocalTime(), european);
-        QCOMPARE(dtOffset.toLocalTime(), european);
+    if (zoneIsCET) {
+        QCOMPARE(dtLocal.toLocalTime(), cet);
+        QCOMPARE(dtUtc.toLocalTime(), cet);
+        QCOMPARE(dtOffset.toLocalTime(), cet);
     } else {
         QSKIP("You must test using Central European (CET/CEST) time zone, e.g. TZ=Europe/Oslo");
     }
@@ -753,16 +802,18 @@ void tst_QDateTime::toString_textDate_data()
     QTest::addColumn<QDateTime>("datetime");
     QTest::addColumn<QString>("expected");
 
+    QString wednesdayJanuary = QDate::shortDayName(3) + ' ' + QDate::shortMonthName(1);
+
     QTest::newRow("localtime")  << QDateTime(QDate(2013, 1, 2), QTime(1, 2, 3), Qt::LocalTime)
-                                << QString("Wed Jan 2 01:02:03 2013");
+                                << wednesdayJanuary + QString(" 2 01:02:03 2013");
     QTest::newRow("utc")        << QDateTime(QDate(2013, 1, 2), QTime(1, 2, 3), Qt::UTC)
-                                << QString("Wed Jan 2 01:02:03 2013 GMT");
+                                << wednesdayJanuary + QString(" 2 01:02:03 2013 GMT");
     QTest::newRow("offset+")    << QDateTime(QDate(2013, 1, 2), QTime(1, 2, 3), Qt::OffsetFromUTC,
                                              10 * 60 * 60)
-                                << QString("Wed Jan 2 01:02:03 2013 GMT+1000");
+                                << wednesdayJanuary + QString(" 2 01:02:03 2013 GMT+1000");
     QTest::newRow("offset-")    << QDateTime(QDate(2013, 1, 2), QTime(1, 2, 3), Qt::OffsetFromUTC,
                                              -10 * 60 * 60)
-                                << QString("Wed Jan 2 01:02:03 2013 GMT-1000");
+                                << wednesdayJanuary + QString(" 2 01:02:03 2013 GMT-1000");
     QTest::newRow("invalid")    << QDateTime()
                                 << QString("");
 }
@@ -772,9 +823,6 @@ void tst_QDateTime::toString_textDate()
     QFETCH(QDateTime, datetime);
     QFETCH(QString, expected);
 
-    QLocale oldLocale;
-    QLocale::setDefault(QLocale("en_US"));
-
     QString result = datetime.toString(Qt::TextDate);
     QCOMPARE(result, expected);
 
@@ -784,8 +832,6 @@ void tst_QDateTime::toString_textDate()
     QCOMPARE(resultDatetime.time(), datetime.time());
     QCOMPARE(resultDatetime.timeSpec(), datetime.timeSpec());
     QCOMPARE(resultDatetime.utcOffset(), datetime.utcOffset());
-
-    QLocale::setDefault(oldLocale);
 }
 
 void tst_QDateTime::toString_rfcDate_data()
@@ -793,7 +839,7 @@ void tst_QDateTime::toString_rfcDate_data()
     QTest::addColumn<QDateTime>("dt");
     QTest::addColumn<QString>("formatted");
 
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QTest::newRow("localtime")
                 << QDateTime(QDate(1978, 11, 9), QTime(13, 28, 34))
                 << QString("09 Nov 1978 13:28:34 +0100");
@@ -1050,7 +1096,7 @@ void tst_QDateTime::addSecs_data()
     QTest::newRow("utc9") << QDateTime(QDate(4000, 1, 1), standardTime, Qt::UTC) << 0
                        << QDateTime(QDate(4000, 1, 1), standardTime, Qt::UTC);
 
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QTest::newRow("cet0") << QDateTime(QDate(2004, 1, 1), standardTime, Qt::LocalTime) << 86400
                            << QDateTime(QDate(2004, 1, 2), standardTime, Qt::LocalTime);
         QTest::newRow("cet1") << QDateTime(QDate(2004, 1, 1), standardTime, Qt::LocalTime) << (86400 * 185)
@@ -1162,7 +1208,7 @@ void tst_QDateTime::toTimeSpec_data()
         << QDateTime(QDate(-271821, 4, 20), QTime(23, 0, 0), Qt::UTC)
         << QDateTime(QDate(-271821, 4, 21), QTime(0, 0, 0), Qt::LocalTime);
 
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QTest::newRow("summer1") << QDateTime(QDate(2004, 6, 30), utcTime, Qt::UTC)
                                  << QDateTime(QDate(2004, 6, 30), localDaylightTime, Qt::LocalTime);
         QTest::newRow("summer2") << QDateTime(QDate(1760, 6, 30), utcTime, Qt::UTC)
@@ -1185,7 +1231,7 @@ void tst_QDateTime::toTimeSpec_data()
 
 void tst_QDateTime::toTimeSpec()
 {
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QFETCH(QDateTime, fromUtc);
         QFETCH(QDateTime, fromLocal);
 
@@ -1240,7 +1286,7 @@ void tst_QDateTime::toTimeSpec()
         QCOMPARE(localToOffset.time(), fromUtc.time());
         QCOMPARE(localToOffset.timeSpec(), Qt::UTC);
     } else {
-        QSKIP("Not tested with timezone other than Central European (CET/CST)");
+        QSKIP("Not tested with timezone other than Central European (CET/CEST)");
     }
 }
 
@@ -1251,7 +1297,7 @@ void tst_QDateTime::toLocalTime_data()
 
 void tst_QDateTime::toLocalTime()
 {
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QFETCH(QDateTime, fromUtc);
         QFETCH(QDateTime, fromLocal);
 
@@ -1262,7 +1308,7 @@ void tst_QDateTime::toLocalTime()
         QCOMPARE(fromUtc.toLocalTime(), fromLocal);
         QCOMPARE(fromUtc.toLocalTime(), fromLocal.toLocalTime());
     } else {
-        QSKIP("Not tested with timezone other than Central European (CET/CST)");
+        QSKIP("Not tested with timezone other than Central European (CET/CEST)");
     }
 }
 
@@ -1273,7 +1319,7 @@ void tst_QDateTime::toUTC_data()
 
 void tst_QDateTime::toUTC()
 {
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QFETCH(QDateTime, fromUtc);
         QFETCH(QDateTime, fromLocal);
 
@@ -1284,7 +1330,7 @@ void tst_QDateTime::toUTC()
         QCOMPARE(fromLocal.toUTC(), fromUtc);
         QCOMPARE(fromUtc.toUTC(), fromLocal.toUTC());
     } else {
-        QSKIP("Not tested with timezone other than Central European (CET/CST)");
+        QSKIP("Not tested with timezone other than Central European (CET/CEST)");
     }
 
     QDateTime dt = QDateTime::currentDateTime();
@@ -1568,8 +1614,14 @@ void tst_QDateTime::daylightSavingsTimeChange_data()
 {
     QTest::addColumn<QDate>("inDST");
     QTest::addColumn<QDate>("outDST");
-    QTest::newRow("Autumn") << QDate(2006, 8, 1) << QDate(2006, 12, 1);
-    QTest::newRow("Spring") << QDate(2006, 5, 1) << QDate(2006, 2, 1);
+    QTest::addColumn<int>("days"); // from in to out; -ve if reversed
+    QTest::addColumn<int>("months");
+
+    QTest::newRow("Autumn") << QDate(2006, 8, 1) << QDate(2006, 12, 1)
+                            << 122 << 4;
+
+    QTest::newRow("Spring") << QDate(2006, 5, 1) << QDate(2006, 2, 1)
+                            << -89 << -3;
 }
 
 void tst_QDateTime::daylightSavingsTimeChange()
@@ -1589,6 +1641,8 @@ void tst_QDateTime::daylightSavingsTimeChange()
 
     QFETCH(QDate, inDST);
     QFETCH(QDate, outDST);
+    QFETCH(int, days);
+    QFETCH(int, months);
 
     // First with simple construction
     QDateTime dt = QDateTime(outDST, QTime(0, 0, 0), Qt::LocalTime);
@@ -1598,6 +1652,22 @@ void tst_QDateTime::daylightSavingsTimeChange()
     dt = dt.addSecs(1);
     QCOMPARE(dt, QDateTime(inDST, QTime(0, 0, 1)));
 
+    // now using addDays:
+    dt = dt.addDays(days).addSecs(1);
+    QCOMPARE(dt, QDateTime(outDST, QTime(0, 0, 2)));
+
+    // ... and back again:
+    dt = dt.addDays(-days).addSecs(1);
+    QCOMPARE(dt, QDateTime(inDST, QTime(0, 0, 3)));
+
+    // now using addMonths:
+    dt = dt.addMonths(months).addSecs(1);
+    QCOMPARE(dt, QDateTime(outDST, QTime(0, 0, 4)));
+
+    // ... and back again:
+    dt = dt.addMonths(-months).addSecs(1);
+    QCOMPARE(dt, QDateTime(inDST, QTime(0, 0, 5)));
+
     // now using fromTime_t
     dt = QDateTime::fromTime_t(outDSTsecs);
     QCOMPARE(dt, QDateTime(outDST, QTime(0, 0, 0)));
@@ -1605,6 +1675,44 @@ void tst_QDateTime::daylightSavingsTimeChange()
     dt.setDate(inDST);
     dt = dt.addSecs(60);
     QCOMPARE(dt, QDateTime(inDST, QTime(0, 1, 0)));
+
+    // using addMonths:
+    dt = dt.addMonths(months).addSecs(60);
+    QCOMPARE(dt, QDateTime(outDST, QTime(0, 2, 0)));
+    // back again:
+    dt = dt.addMonths(-months).addSecs(60);
+    QCOMPARE(dt, QDateTime(inDST, QTime(0, 3, 0)));
+
+    // using addDays:
+    dt = dt.addDays(days).addSecs(60);
+    QCOMPARE(dt, QDateTime(outDST, QTime(0, 4, 0)));
+    // back again:
+    dt = dt.addDays(-days).addSecs(60);
+    QCOMPARE(dt, QDateTime(inDST, QTime(0, 5, 0)));
+
+    // Now use the result of a UTC -> LocalTime conversion
+    dt = QDateTime(outDST, QTime(0, 0, 0), Qt::LocalTime).toUTC();
+    dt = QDateTime(dt.date(), dt.time(), Qt::UTC).toLocalTime();
+    QCOMPARE(dt, QDateTime(outDST, QTime(0, 0, 0)));
+
+    // using addDays:
+    dt = dt.addDays(-days).addSecs(3600);
+    QCOMPARE(dt, QDateTime(inDST, QTime(1, 0, 0)));
+    // back again
+    dt = dt.addDays(days).addSecs(3600);
+    QCOMPARE(dt, QDateTime(outDST, QTime(2, 0, 0)));
+
+    // using addMonths:
+    dt = dt.addMonths(-months).addSecs(3600);
+    QCOMPARE(dt, QDateTime(inDST, QTime(3, 0, 0)));
+    // back again:
+    dt = dt.addMonths(months).addSecs(3600);
+    QCOMPARE(dt, QDateTime(outDST, QTime(4, 0, 0)));
+
+    // using setDate:
+    dt.setDate(inDST);
+    dt = dt.addSecs(3600);
+    QCOMPARE(dt, QDateTime(inDST, QTime(5, 0, 0)));
 }
 
 void tst_QDateTime::springForward_data()
@@ -1614,12 +1722,44 @@ void tst_QDateTime::springForward_data()
     QTest::addColumn<int>("step"); // days to step; +ve from before, -ve from after
     QTest::addColumn<int>("adjust"); // minutes ahead of UTC on day stepped from
 
-    if (europeanTimeZone) {
-        QTest::newRow("Europe from day before") << QDate(2015, 3, 29) << QTime(2, 30, 0) << 1 << 60;
-        QTest::newRow("Europe from day after") << QDate(2015, 3, 29) << QTime(2, 30, 0) << -1 << 120;
- // } else if (otherZone) {
+    /*
+      Zone tests compare a summer and winter moment's time_t to known values.
+      This could in principle be flawed (two DST-using zones in the same
+      hemisphere with the same DST and standard times but different transition
+      times) but no actual example is known where this is a problem.  Please
+      document any such conflicts, if discovered.
+
+      See http://www.timeanddate.com/time/zones/ for data on more candidates to
+      test.
+     */
+
+    uint winter = QDateTime(QDate(2015, 1, 1), QTime()).toTime_t();
+    uint summer = QDateTime(QDate(2015, 7, 1), QTime()).toTime_t();
+
+    if (winter == 1420066800 && summer == 1435701600) {
+        QTest::newRow("CET from day before") << QDate(2015, 3, 29) << QTime(2, 30, 0) << 1 << 60;
+        QTest::newRow("CET from day after") << QDate(2015, 3, 29) << QTime(2, 30, 0) << -1 << 120;
+    } else if (winter == 1420063200 && summer == 1435698000) {
+        // e.g. Finland, where our CI runs ...
+        QTest::newRow("EET from day before") << QDate(2015, 3, 29) << QTime(3, 30, 0) << 1 << 120;
+        QTest::newRow("EET from day after") << QDate(2015, 3, 29) << QTime(3, 30, 0) << -1 << 180;
+    } else if (winter == 1420070400 && summer == 1435705200) {
+        // Western European Time, WET/WEST; a.k.a. GMT/BST
+        QTest::newRow("WET from day before") << QDate(2015, 3, 29) << QTime(1, 30, 0) << 1 << 0;
+        QTest::newRow("WET from day after") << QDate(2015, 3, 29) << QTime(1, 30, 0) << -1 << 60;
+    } else if (winter == 1420099200 && summer == 1435734000) {
+        // Western USA, Canada: Pacific Time (e.g. US/Pacific)
+        QTest::newRow("PT from day before") << QDate(2015, 3, 8) << QTime(2, 30, 0) << 1 << -480;
+        QTest::newRow("PT from day after") << QDate(2015, 3, 8) << QTime(2, 30, 0) << -1 << -420;
+    } else if (winter == 1420088400 && summer == 1435723200) {
+        // Eastern USA, Canada: Eastern Time (e.g. US/Eastern)
+        QTest::newRow("ET from day before") << QDate(2015, 3, 8) << QTime(2, 30, 0) << 1 << -300;
+        QTest::newRow("ET from day after") << QDate(2015, 3, 8) << QTime(2, 30, 0) << -1 << -240;
     } else {
-        QSKIP("No spring forward test data for this TZ");
+        // Includes the numbers you need to test for your zone, as above:
+        QString msg(QString::fromLatin1("No spring forward test data for this TZ (%1, %2)"
+                        ).arg(winter).arg(summer));
+        QSKIP(qPrintable(msg));
     }
 }
 
@@ -1687,7 +1827,7 @@ void tst_QDateTime::operator_eqeq_data()
     QTest::newRow("invalid == invalid") << invalidDateTime() << invalidDateTime() << true << false;
     QTest::newRow("invalid == valid #1") << invalidDateTime() << dateTime1 << false << false;
 
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QTest::newRow("data14") << QDateTime(QDate(2004, 1, 2), QTime(2, 2, 3), Qt::LocalTime)
              << QDateTime(QDate(2004, 1, 2), QTime(1, 2, 3), Qt::UTC) << true << true;
     }
@@ -1719,7 +1859,7 @@ void tst_QDateTime::operator_eqeq()
     if (equal)
         QVERIFY(qHash(dt1) == qHash(dt2));
 
-    if (checkEuro && europeanTimeZone) {
+    if (checkEuro && zoneIsCET) {
         QVERIFY(dt1.toUTC() == dt2);
         QVERIFY(dt1 == dt2.toLocalTime());
     }
@@ -2233,7 +2373,7 @@ void tst_QDateTime::offsetFromUtc()
     QCOMPARE(dt2.offsetFromUtc(), 0);
 
     // LocalTime should vary
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         // Time definitely in Standard Time so 1 hour ahead
         QDateTime dt3(QDate(2013, 1, 1), QTime(0, 0, 0), Qt::LocalTime);
         QCOMPARE(dt3.offsetFromUtc(), 1 * 60 * 60);
@@ -2358,7 +2498,7 @@ void tst_QDateTime::timeZoneAbbreviation()
     QCOMPARE(dt3.timeZoneAbbreviation(), QString("UTC"));
 
     // LocalTime should vary
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         // Time definitely in Standard Time
         QDateTime dt4(QDate(2013, 1, 1), QTime(0, 0, 0), Qt::LocalTime);
 #ifdef Q_OS_WIN
@@ -2482,7 +2622,7 @@ void tst_QDateTime::isDaylightTime() const
     QDateTime offset2(QDate(2012, 6, 1), QTime(0, 0, 0), Qt::OffsetFromUTC, 1 * 60 * 60);
     QVERIFY(!offset2.isDaylightTime());
 
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         QDateTime cet1(QDate(2012, 1, 1), QTime(0, 0, 0));
         QVERIFY(!cet1.isDaylightTime());
         QDateTime cet2(QDate(2012, 6, 1), QTime(0, 0, 0));
@@ -2494,7 +2634,7 @@ void tst_QDateTime::isDaylightTime() const
 
 void tst_QDateTime::daylightTransitions() const
 {
-    if (europeanTimeZone) {
+    if (zoneIsCET) {
         // CET transitions occur at 01:00:00 UTC on last Sunday in March and October
         // 2011-03-27 02:00:00 CET  became 03:00:00 CEST at msecs = 1301187600000
         // 2011-10-30 03:00:00 CEST became 02:00:00 CET  at msecs = 1319936400000
diff --git a/tests/auto/corelib/tools/qsharedpointer/tst_qsharedpointer.cpp b/tests/auto/corelib/tools/qsharedpointer/tst_qsharedpointer.cpp
index b63485e91eb3c0063b8c1adcba0407e3a01e6a7b..ab5bc410f6c284afb9bb8a26b9cf4c452bf7cf39 100644
--- a/tests/auto/corelib/tools/qsharedpointer/tst_qsharedpointer.cpp
+++ b/tests/auto/corelib/tools/qsharedpointer/tst_qsharedpointer.cpp
@@ -254,8 +254,10 @@ void tst_QSharedPointer::basics()
 
         QCOMPARE(ptr.data(), aData);
         QCOMPARE(ptr.operator->(), aData);
-        Data &dataReference = *ptr;
-        QCOMPARE(&dataReference, aData);
+        if (!isNull) {
+            Data &dataReference = *ptr;
+            QCOMPARE(&dataReference, aData);
+        }
 
         QVERIFY(ptr == aData);
         QVERIFY(!(ptr != aData));
diff --git a/tests/auto/gui/kernel/kernel.pro b/tests/auto/gui/kernel/kernel.pro
index b03a117f8398121073e5efe934786dae00867d7b..5254e755d4ecfd67d6987077139f340c2020b74b 100644
--- a/tests/auto/gui/kernel/kernel.pro
+++ b/tests/auto/gui/kernel/kernel.pro
@@ -24,7 +24,7 @@ SUBDIRS=\
    qopenglwindow \
    qrasterwindow
 
-win32:!wince*:!winrt: SUBDIRS += noqteventloop
+win32:!wince:!winrt:qtHaveModule(network): SUBDIRS += noqteventloop
 
 !qtHaveModule(widgets): SUBDIRS -= \
    qmouseevent_modal \
diff --git a/tests/auto/gui/kernel/noqteventloop/noqteventloop.pro b/tests/auto/gui/kernel/noqteventloop/noqteventloop.pro
index de5715e1474ff6d8159b6e8cb7244ee5ef762e65..a42b359f29e3d2e9c7f82412d83fd4f880aa74c9 100644
--- a/tests/auto/gui/kernel/noqteventloop/noqteventloop.pro
+++ b/tests/auto/gui/kernel/noqteventloop/noqteventloop.pro
@@ -1,7 +1,7 @@
 CONFIG += testcase
 TARGET = tst_noqteventloop
 
-QT += core-private gui-private testlib
+QT += core-private network gui-private testlib
 
 SOURCES  += tst_noqteventloop.cpp
 
diff --git a/tests/auto/gui/kernel/noqteventloop/tst_noqteventloop.cpp b/tests/auto/gui/kernel/noqteventloop/tst_noqteventloop.cpp
index d21569dcc00823935e8926e03dc9431201fac691..735d23b137c2d45f551bad41a1f89b8aafffaca6 100644
--- a/tests/auto/gui/kernel/noqteventloop/tst_noqteventloop.cpp
+++ b/tests/auto/gui/kernel/noqteventloop/tst_noqteventloop.cpp
@@ -36,6 +36,9 @@
 #include <QEvent>
 #include <QtCore/qthread.h>
 #include <QtGui/qguiapplication.h>
+#include <QtNetwork/qtcpserver.h>
+#include <QtNetwork/qtcpsocket.h>
+#include <QtCore/qelapsedtimer.h>
 
 #include <QtCore/qt_windows.h>
 
@@ -47,6 +50,7 @@ private slots:
     void initTestCase();
     void cleanup();
     void consumeMouseEvents();
+    void consumeSocketEvents();
 
 };
 
@@ -265,6 +269,36 @@ void tst_NoQtEventLoop::consumeMouseEvents()
 
 }
 
+void tst_NoQtEventLoop::consumeSocketEvents()
+{
+    int argc = 1;
+    char *argv[] = { const_cast<char *>("test"), 0 };
+    QGuiApplication app(argc, argv);
+    QTcpServer server;
+    QTcpSocket client;
+
+    QVERIFY(server.listen(QHostAddress::LocalHost));
+    client.connectToHost(server.serverAddress(), server.serverPort());
+    QVERIFY(client.waitForConnected());
+
+    QElapsedTimer elapsedTimer;
+    elapsedTimer.start();
+
+    // Exec own message loop
+    MSG msg;
+    forever {
+        if (elapsedTimer.hasExpired(3000) || server.hasPendingConnections())
+            break;
+
+        if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
+            ::TranslateMessage(&msg);
+            ::DispatchMessage(&msg);
+        }
+    }
+
+    QVERIFY(server.hasPendingConnections());
+}
+
 #include <tst_noqteventloop.moc>
 
 QTEST_APPLESS_MAIN(tst_NoQtEventLoop)
diff --git a/tests/auto/gui/qopengl/tst_qopengl.cpp b/tests/auto/gui/qopengl/tst_qopengl.cpp
index 8103f2791110282f512ccfd2ec794046becf60e7..e2ad502a52a5337fb49aea835e8286fb097a9af5 100644
--- a/tests/auto/gui/qopengl/tst_qopengl.cpp
+++ b/tests/auto/gui/qopengl/tst_qopengl.cpp
@@ -39,6 +39,7 @@
 #include <QtGui/QOpenGLVertexArrayObject>
 #include <QtGui/QOpenGLBuffer>
 #include <QtGui/QOpenGLPaintDevice>
+#include <QtGui/QOpenGLTexture>
 #include <QtGui/QPainter>
 #include <QtGui/QScreen>
 #include <QtGui/QWindow>
@@ -99,8 +100,8 @@ private slots:
     void textureblitterFullTargetRectTransform();
     void textureblitterPartTargetRectTransform();
     void defaultSurfaceFormat();
-
     void imageFormatPainting();
+    void nullTextureInitializtion();
 
 #ifdef USE_GLX
     void glxContextWrap();
@@ -1524,6 +1525,18 @@ void tst_QOpenGL::bufferMapRange()
     ctx->doneCurrent();
 }
 
+void tst_QOpenGL::nullTextureInitializtion()
+{
+    QScopedPointer<QSurface> surface(createSurface(QSurface::Window));
+    QOpenGLContext ctx;
+    ctx.create();
+    ctx.makeCurrent(surface.data());
+
+    QImage i;
+    QOpenGLTexture t(i);
+    QVERIFY(!t.isCreated());
+}
+
 QTEST_MAIN(tst_QOpenGL)
 
 #include "tst_qopengl.moc"
diff --git a/tests/auto/gui/text/qtextcursor/qtextcursor.pro b/tests/auto/gui/text/qtextcursor/qtextcursor.pro
index 5e045404f1cfe607a9cb0efad09f0e3acbadb0d0..d984b30fbb24fe204ac5429ae1e778b427927f76 100644
--- a/tests/auto/gui/text/qtextcursor/qtextcursor.pro
+++ b/tests/auto/gui/text/qtextcursor/qtextcursor.pro
@@ -2,4 +2,4 @@ CONFIG += testcase
 CONFIG += parallel_test
 TARGET = tst_qtextcursor
 SOURCES  += tst_qtextcursor.cpp
-QT += testlib
+QT += core-private gui-private testlib
diff --git a/tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp b/tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp
index 9396cd678bdc07f066fddad16b99294c2a8e5972..423d87591a50e37f0b35461d0306417b4283d83e 100644
--- a/tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp
+++ b/tests/auto/gui/text/qtextcursor/tst_qtextcursor.cpp
@@ -34,7 +34,6 @@
 
 #include <QtTest/QtTest>
 
-
 #include <qtextdocument.h>
 #include <qtexttable.h>
 #include <qvariant.h>
@@ -45,6 +44,8 @@
 #include <qtextobject.h>
 #include <qdebug.h>
 
+#include <private/qtextcursor_p.h>
+
 QT_FORWARD_DECLARE_CLASS(QTextDocument)
 
 class tst_QTextCursor : public QObject
@@ -1292,7 +1293,7 @@ void tst_QTextCursor::anchorInitialized1()
 void tst_QTextCursor::anchorInitialized2()
 {
     cursor.insertBlock();
-    cursor = QTextCursor(cursor.block().docHandle(), 1);
+    cursor = QTextCursorPrivate::fromPosition(cursor.block().docHandle(), 1);
     QCOMPARE(cursor.position(), 1);
     QCOMPARE(cursor.anchor(), 1);
     QCOMPARE(cursor.selectionStart(), 1);
diff --git a/tests/auto/gui/text/qtextdocumentlayout/tst_qtextdocumentlayout.cpp b/tests/auto/gui/text/qtextdocumentlayout/tst_qtextdocumentlayout.cpp
index f59f542a2be51b8bd58367934dbff3795a15463b..6a14928219e5d10b8c40a13caf94c1ee8037b38f 100644
--- a/tests/auto/gui/text/qtextdocumentlayout/tst_qtextdocumentlayout.cpp
+++ b/tests/auto/gui/text/qtextdocumentlayout/tst_qtextdocumentlayout.cpp
@@ -319,7 +319,7 @@ void tst_QTextDocumentLayout::blockVisibility()
     for (int i = 0; i < 10; ++i) {
         if (!doc->isEmpty())
             cursor.insertBlock();
-        cursor.insertText(QString::number(i));
+        cursor.insertText("A");
     }
 
     qreal margin = doc->documentMargin();
diff --git a/tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp b/tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp
index 519ee0dc847a5b4f0888f2a44b27f785a8e3778e..51d87afea199e1f6bee5098e2a08069d4888473d 100644
--- a/tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp
+++ b/tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp
@@ -232,13 +232,6 @@ void tst_QNetworkInterface::interfaceFromXXX()
             // but only for IPv4 (there is no such thing as broadcast in IPv6)
             if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                 QVERIFY(!entry.broadcast().isNull());
-
-                // verify that the broadcast address is correct
-                quint32 ip = entry.ip().toIPv4Address();
-                quint32 mask = entry.netmask().toIPv4Address();
-                quint32 bcast = entry.broadcast().toIPv4Address();
-
-                QCOMPARE(bcast, ip | ~mask);
             }
         }
 
diff --git a/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp b/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
index 179cdb76bc06e4ee8a6b4ba8da69953eeea5c854..f6662b6712ee859015cab7c9a8ef1a6890f7f0c2 100644
--- a/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
+++ b/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
@@ -72,6 +72,7 @@ private slots:
     void downloadBigFile();
    // void tcpLoopbackPerformance();
     void passwordAuth();
+    void ensureEofTriggersNotification();
 
 protected slots:
     void tcpSocketNonBlocking_hostFound();
@@ -739,5 +740,51 @@ void tst_QHttpSocketEngine::passwordAuth()
 
 //----------------------------------------------------------------------------------
 
+void tst_QHttpSocketEngine::ensureEofTriggersNotification()
+{
+    QList<QByteArray> serverData;
+    // Set the handshake and server response data
+    serverData << "HTTP/1.0 200 Connection established\r\n\r\n" << "0";
+    MiniHttpServer server(serverData);
+
+    QTcpSocket socket;
+    connect(&socket, SIGNAL(connected()), SLOT(exitLoopSlot()));
+    socket.setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, server.serverAddress().toString(),
+                                  server.serverPort()));
+    socket.connectToHost("0.1.2.3", 12345);
+
+    QTestEventLoop::instance().enterLoop(5);
+    if (QTestEventLoop::instance().timeout())
+        QFAIL("Connect timed out");
+
+    QCOMPARE(socket.state(), QTcpSocket::ConnectedState);
+    // Disable read notification on server response
+    socket.setReadBufferSize(1);
+    socket.putChar(0);
+
+    // Wait for the response
+    connect(&socket, SIGNAL(readyRead()), SLOT(exitLoopSlot()));
+    QTestEventLoop::instance().enterLoop(5);
+    if (QTestEventLoop::instance().timeout())
+        QFAIL("Read timed out");
+
+    QCOMPARE(socket.state(), QTcpSocket::ConnectedState);
+    QCOMPARE(socket.bytesAvailable(), 1);
+    // Trigger a read notification
+    socket.readAll();
+    // Check for pending EOF at input
+    QCOMPARE(socket.bytesAvailable(), 0);
+    QCOMPARE(socket.state(), QTcpSocket::ConnectedState);
+
+    // Try to read EOF
+    connect(&socket, SIGNAL(disconnected()), SLOT(exitLoopSlot()));
+    QTestEventLoop::instance().enterLoop(5);
+    if (QTestEventLoop::instance().timeout())
+        QFAIL("Disconnect timed out");
+
+    // Check that it's closed
+    QCOMPARE(socket.state(), QTcpSocket::UnconnectedState);
+}
+
 QTEST_MAIN(tst_QHttpSocketEngine)
 #include "tst_qhttpsocketengine.moc"
diff --git a/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp b/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
index abbc560414d241aea1ab2b22975695b214818b8a..cde453c1917825370d2bc5e4552ef40b0d6f37ac 100644
--- a/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
+++ b/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
@@ -201,6 +201,7 @@ private slots:
     void setSocketOption();
     void clientSendDataOnDelayedDisconnect();
     void serverDisconnectWithBuffered();
+    void readNotificationsAfterBind();
 
 protected slots:
     void nonBlockingIMAP_hostFound();
@@ -3028,5 +3029,25 @@ void tst_QTcpSocket::serverDisconnectWithBuffered()
     delete socket;
 }
 
+// Test that the socket does not enable the read notifications in bind()
+void tst_QTcpSocket::readNotificationsAfterBind()
+{
+    QFETCH_GLOBAL(bool, setProxy);
+    if (setProxy)
+        return;
+
+    QAbstractSocket socket(QAbstractSocket::TcpSocket, Q_NULLPTR);
+    QVERIFY2(socket.bind(), "Bind error!");
+
+    connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), &QTestEventLoop::instance(), SLOT(exitLoop()));
+    QSignalSpy spyReadyRead(&socket, SIGNAL(readyRead()));
+    socket.connectToHost(QtNetworkSettings::serverName(), 12346);
+
+    QTestEventLoop::instance().enterLoop(10);
+    QVERIFY2(!QTestEventLoop::instance().timeout(), "Connection to closed port timed out instead of refusing, something is wrong");
+    QVERIFY2(socket.state() == QAbstractSocket::UnconnectedState, "Socket connected unexpectedly!");
+    QCOMPARE(spyReadyRead.count(), 0);
+}
+
 QTEST_MAIN(tst_QTcpSocket)
 #include "tst_qtcpsocket.moc"
diff --git a/tests/auto/other/networkselftest/tst_networkselftest.cpp b/tests/auto/other/networkselftest/tst_networkselftest.cpp
index 7ce385121cb32835a7e3a246e7a1e9898e69d763..7ef830d89f73983b9bc88d2af59339c6f12006d9 100644
--- a/tests/auto/other/networkselftest/tst_networkselftest.cpp
+++ b/tests/auto/other/networkselftest/tst_networkselftest.cpp
@@ -171,14 +171,16 @@ static bool doSocketRead(QTcpSocket *socket, int minBytesAvailable, int timeout
 {
     QElapsedTimer timer;
     timer.start();
+    int t = timeout;
     forever {
         if (socket->bytesAvailable() >= minBytesAvailable)
             return true;
-        timeout = qt_subtract_from_timeout(timeout, timer.elapsed());
-        if (socket->state() == QAbstractSocket::UnconnectedState
-            || timeout == 0)
+        if (socket->state() == QAbstractSocket::UnconnectedState)
             return false;
-        if (!socket->waitForReadyRead(timeout))
+        if (!socket->waitForReadyRead(t))
+            return false;
+        t = qt_subtract_from_timeout(timeout, timer.elapsed());
+        if (t == 0)
             return false;
     }
 }
@@ -199,6 +201,7 @@ static bool doSocketFlush(QTcpSocket *socket, int timeout = 4000)
 #endif
     QTime timer;
     timer.start();
+    int t = timeout;
     forever {
         if (socket->bytesToWrite() == 0
 #ifndef QT_NO_SSL
@@ -206,11 +209,12 @@ static bool doSocketFlush(QTcpSocket *socket, int timeout = 4000)
 #endif
             )
             return true;
-        timeout = qt_subtract_from_timeout(timeout, timer.elapsed());
-        if (socket->state() == QAbstractSocket::UnconnectedState
-            || timeout == 0)
+        if (socket->state() == QAbstractSocket::UnconnectedState)
+            return false;
+        if (!socket->waitForBytesWritten(t))
             return false;
-        if (!socket->waitForBytesWritten(timeout))
+        t = qt_subtract_from_timeout(timeout, timer.elapsed());
+        if (t == 0)
             return false;
     }
 }
diff --git a/tests/auto/widgets/dialogs/qdialog/tst_qdialog.cpp b/tests/auto/widgets/dialogs/qdialog/tst_qdialog.cpp
index d5769554becfaac9fd8836bc614365d0537bd962..37afa7f0a5e88f8de0e6ee696657a12c6647ef35 100644
--- a/tests/auto/widgets/dialogs/qdialog/tst_qdialog.cpp
+++ b/tests/auto/widgets/dialogs/qdialog/tst_qdialog.cpp
@@ -51,6 +51,14 @@
 
 QT_FORWARD_DECLARE_CLASS(QDialog)
 
+// work around function being protected
+class DummyDialog : public QDialog
+{
+public:
+    DummyDialog(): QDialog(0, Qt::X11BypassWindowManagerHint) {}
+    using QDialog::showExtension;
+};
+
 class tst_QDialog : public QObject
 {
     Q_OBJECT
@@ -85,7 +93,7 @@ private slots:
     void dialogInGraphicsView();
 
 private:
-    QDialog *testWidget;
+    DummyDialog *testWidget;
 };
 
 // Testing get/set functions
@@ -111,13 +119,6 @@ void tst_QDialog::getSetCheck()
     QCOMPARE(INT_MAX, obj1.result());
 }
 
-// work around function being protected
-class DummyDialog : public QDialog {
-public:
-    DummyDialog(): QDialog(0) {}
-    void showExtension( bool b ) { QDialog::showExtension( b ); }
-};
-
 class ToolDialog : public QDialog
 {
 public:
@@ -155,7 +156,7 @@ tst_QDialog::tst_QDialog()
 void tst_QDialog::initTestCase()
 {
     // Create the test class
-    testWidget = new QDialog(0, Qt::X11BypassWindowManagerHint);
+    testWidget = new DummyDialog;
     testWidget->resize(200,200);
     testWidget->show();
     qApp->setActiveWindow(testWidget);
@@ -200,7 +201,7 @@ void tst_QDialog::showExtension()
     QPoint oldPosition = testWidget->pos();
 
     // show
-    ((DummyDialog*)testWidget)->showExtension( true );
+    testWidget->showExtension( true );
 //     while ( testWidget->size() == dlgSize )
 //         qApp->processEvents();
 
@@ -209,7 +210,7 @@ void tst_QDialog::showExtension()
     QCOMPARE(testWidget->pos(), oldPosition);
 
     // hide extension. back to old size ?
-    ((DummyDialog*)testWidget)->showExtension( false );
+    testWidget->showExtension( false );
     QCOMPARE( testWidget->size(), dlgSize );
 
     testWidget->setExtension( 0 );
diff --git a/tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp b/tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp
index 8760dc176c48fb8ca3fb95d80512561f8a2d5cd9..d8a8ed6b4b33f23560685ed1e47801025e5b4218 100644
--- a/tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp
+++ b/tests/auto/widgets/graphicsview/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp
@@ -3685,6 +3685,7 @@ void tst_QGraphicsProxyWidget::mapToGlobal() // QTBUG-41135
     const QSize size = availableGeometry.size() / 5;
     QGraphicsScene scene;
     QGraphicsView view(&scene);
+    view.setTransform(QTransform::fromScale(2, 2));  // QTBUG-50136, use transform.
     view.setWindowTitle(QTest::currentTestFunction());
     view.resize(size);
     view.move(availableGeometry.bottomRight() - QPoint(size.width(), size.height()) - QPoint(100, 100));
@@ -3707,10 +3708,15 @@ void tst_QGraphicsProxyWidget::mapToGlobal() // QTBUG-41135
     QVERIFY2((viewCenter - embeddedCenterGlobal).manhattanLength() <= 2,
              msgPointMismatch(embeddedCenterGlobal, viewCenter).constData());
 
-    // Same test with child centered on embeddedWidget
+    // Same test with child centered on embeddedWidget. The correct
+    // mapping is not implemented yet, but at least make sure
+    // the roundtrip maptoGlobal()/mapFromGlobal() returns the same
+    // point since that is important for mouse event handling (QTBUG-50030,
+    // QTBUG-50136).
     const QPoint childCenter = childWidget->rect().center();
     const QPoint childCenterGlobal = childWidget->mapToGlobal(childCenter);
     QCOMPARE(childWidget->mapFromGlobal(childCenterGlobal), childCenter);
+    QEXPECT_FAIL("", "Not implemented for child widgets of embedded widgets", Continue);
     QVERIFY2((viewCenter - childCenterGlobal).manhattanLength() <= 4,
              msgPointMismatch(childCenterGlobal, viewCenter).constData());
 }
diff --git a/tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp b/tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp
index 0b22dc7893bd71b9e0e23a657199d61b4f446e35..ae516639a6e7f8135d92a835e0df0717c6165055 100644
--- a/tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp
+++ b/tests/auto/widgets/widgets/qcombobox/tst_qcombobox.cpp
@@ -166,6 +166,7 @@ private slots:
     void updateDelegateOnEditableChange();
     void respectChangedOwnershipOfItemView();
     void task_QTBUG_39088_inputMethodHints();
+    void task_QTBUG_49831_scrollerNotActivated();
 };
 
 class MyAbstractItemDelegate : public QAbstractItemDelegate
@@ -3206,6 +3207,36 @@ void tst_QComboBox::respectChangedOwnershipOfItemView()
     QCOMPARE(spy2.count(), 1);
 }
 
+void tst_QComboBox::task_QTBUG_49831_scrollerNotActivated()
+{
+    QStringList modelData;
+    for (int i = 0; i < 1000; i++)
+        modelData << QStringLiteral("Item %1").arg(i);
+    QStringListModel model(modelData);
+
+    QComboBox box;
+    box.setModel(&model);
+    box.setCurrentIndex(500);
+    box.show();
+    QTest::qWaitForWindowShown(&box);
+    QTest::mouseMove(&box, QPoint(5, 5), 100);
+    box.showPopup();
+    QFrame *container = box.findChild<QComboBoxPrivateContainer *>();
+    QVERIFY(container);
+    QTest::qWaitForWindowShown(container);
+
+    QList<QComboBoxPrivateScroller *> scrollers = container->findChildren<QComboBoxPrivateScroller *>();
+    // Not all styles support scrollers. We rely only on those platforms that do to catch any regression.
+    if (!scrollers.isEmpty()) {
+        Q_FOREACH (QComboBoxPrivateScroller *scroller, scrollers) {
+            if (scroller->isVisible()) {
+                QSignalSpy doScrollSpy(scroller, SIGNAL(doScroll(int)));
+                QTest::mouseMove(scroller, QPoint(5, 5), 500);
+                QTRY_VERIFY(doScrollSpy.count() > 0);
+            }
+        }
+    }
+}
 
 QTEST_MAIN(tst_QComboBox)
 #include "tst_qcombobox.moc"
diff --git a/tests/manual/diaglib/qwidgetdump.cpp b/tests/manual/diaglib/qwidgetdump.cpp
index f057a58ff0229432f898949ca0463a9d0cdec6c5..e5fdfaeb71da72f70382a051779ac03dc19a5387 100644
--- a/tests/manual/diaglib/qwidgetdump.cpp
+++ b/tests/manual/diaglib/qwidgetdump.cpp
@@ -61,10 +61,32 @@ static void dumpWidgetRecursion(QTextStream &str, const QWidget *w,
     if (const int states = w->windowState())
         str << "windowState=" << hex << showbase << states << dec << noshowbase << ' ';
     formatRect(str, w->geometry());
+    if (w->isWindow()) {
+        const QRect normalGeometry = w->normalGeometry();
+        if (normalGeometry.isValid() && !normalGeometry.isEmpty() && normalGeometry != w->geometry()) {
+            str << " normal=";
+            formatRect(str, w->normalGeometry());
+        }
+    }
     if (!(options & DontPrintWindowFlags)) {
         str << ' ';
         formatWindowFlags(str, w->windowFlags());
     }
+    if (options & PrintSizeConstraints) {
+        str << ' ';
+        const QSize minimumSize = w->minimumSize();
+        if (minimumSize.width() > 0 || minimumSize.height() > 0)
+            str << "minimumSize=" << minimumSize.width() << 'x' << minimumSize.height() << ' ';
+        const QSize sizeHint = w->sizeHint();
+        const QSize minimumSizeHint = w->minimumSizeHint();
+        if (minimumSizeHint.isValid() && !(sizeHint.isValid() && minimumSizeHint == sizeHint))
+            str << "minimumSizeHint=" << minimumSizeHint.width() << 'x' << minimumSizeHint.height() << ' ';
+        if (sizeHint.isValid())
+            str << "sizeHint=" << sizeHint.width() << 'x' << sizeHint.height() << ' ';
+        const QSize maximumSize = w->maximumSize();
+        if (maximumSize.width() < QWIDGETSIZE_MAX || maximumSize.height() < QWIDGETSIZE_MAX)
+            str << "maximumSize=" << maximumSize.width() << 'x' << maximumSize.height() << ' ';
+    }
     str << '\n';
 #if QT_VERSION > 0x050000
     if (const QWindow *win = w->windowHandle()) {
@@ -79,12 +101,17 @@ static void dumpWidgetRecursion(QTextStream &str, const QWidget *w,
     }
 }
 
-void dumpAllWidgets(FormatWindowOptions options)
+void dumpAllWidgets(FormatWindowOptions options, const QWidget *root)
 {
     QString d;
     QTextStream str(&d);
     str << "### QWidgets:\n";
-    foreach (QWidget *tw, QApplication::topLevelWidgets())
+    QWidgetList topLevels;
+    if (root)
+        topLevels.append(const_cast<QWidget *>(root));
+    else
+        topLevels = QApplication::topLevelWidgets();
+    foreach (QWidget *tw, topLevels)
         dumpWidgetRecursion(str, tw, options);
 #if QT_VERSION >= 0x050400
     qDebug().noquote() << d;
diff --git a/tests/manual/diaglib/qwidgetdump.h b/tests/manual/diaglib/qwidgetdump.h
index 0519a0307c9e3715277b536fa4b079c4e0f6b3ae..6f8d9548b3a96f245fbf6221bf7e04cd80acc2a0 100644
--- a/tests/manual/diaglib/qwidgetdump.h
+++ b/tests/manual/diaglib/qwidgetdump.h
@@ -36,9 +36,11 @@
 
 #include "qwindowdump.h"
 
+QT_FORWARD_DECLARE_CLASS(QWidget)
+
 namespace QtDiag {
 
-void dumpAllWidgets(FormatWindowOptions options = 0);
+void dumpAllWidgets(FormatWindowOptions options = 0, const QWidget *root = 0);
 
 } // namespace QtDiag
 
diff --git a/tests/manual/diaglib/qwindowdump.cpp b/tests/manual/diaglib/qwindowdump.cpp
index c0faefb9188f86b5eaac0ac677c47c0d120c3da9..04576dbcf4a747e1540880abf6a61c4df655279a 100644
--- a/tests/manual/diaglib/qwindowdump.cpp
+++ b/tests/manual/diaglib/qwindowdump.cpp
@@ -38,6 +38,7 @@
 #  include <QtGui/QScreen>
 #  include <QtGui/QWindow>
 #  include <qpa/qplatformwindow.h>
+#  include <private/qwindow_p.h>
 #  if QT_VERSION >= 0x050600
 #    include <private/qhighdpiscaling_p.h>
 #  endif
@@ -151,6 +152,15 @@ void formatWindow(QTextStream &str, const QWindow *w, FormatWindowOptions option
         str << ' ';
         formatWindowFlags(str, w->flags());
     }
+    if (options & PrintSizeConstraints) {
+        str << ' ';
+        const QSize minimumSize = w->minimumSize();
+        if (minimumSize.width() > 0 || minimumSize.height() > 0)
+            str << "minimumSize=" << minimumSize.width() << 'x' << minimumSize.height() << ' ';
+        const QSize maximumSize = w->maximumSize();
+        if (maximumSize.width() < QWINDOWSIZE_MAX || maximumSize.height() < QWINDOWSIZE_MAX)
+            str << "maximumSize=" << maximumSize.width() << 'x' << maximumSize.height() << ' ';
+    }
     str << '\n';
 }
 
diff --git a/tests/manual/diaglib/qwindowdump.h b/tests/manual/diaglib/qwindowdump.h
index 9ab00790b6b95f8ac5e0b90fa3f0bfd58938eb9f..2a7d69c915cbab68876fa39d7ea466b01c9bd8f4 100644
--- a/tests/manual/diaglib/qwindowdump.h
+++ b/tests/manual/diaglib/qwindowdump.h
@@ -44,7 +44,8 @@ QT_FORWARD_DECLARE_CLASS(QTextStream)
 namespace QtDiag {
 
 enum FormatWindowOption {
-    DontPrintWindowFlags = 0x001
+    DontPrintWindowFlags = 0x001,
+    PrintSizeConstraints = 0x002
 };
 
 Q_DECLARE_FLAGS(FormatWindowOptions, FormatWindowOption)